Exemple #1
0
        private bool IntersectsPolygon(Polygon polygon, Ray ray, out Intersection intersection)
        {
            intersection = new Intersection();

            Vector3 vecDirection = ray.Direction;
            Vector3 rayToPlaneDirection = ray.Origin - this.Position;

            float D = Vector3.Dot(polygon.NormalDirection, vecDirection);
            float N = -Vector3.Dot(polygon.NormalDirection, rayToPlaneDirection);

            if (Math.Abs(D) <= .0005f)
            {
                return false;
            }

            float sI = N / D;
            if (sI < 0 || sI > ray.Distance) // Behind or out of range
            {
                return false;
            }

            var intersectionPoint = ray.Origin + (new Vector3(sI) * vecDirection);
            var uv = this.GetUVCoordinate(intersectionPoint);

            return true;
        }
Exemple #2
0
        public Street(Intersection node1, Intersection node2, Unit width)
        {
            var diffH = node1.Position.X - node2.Position.X;
            var diffV = node1.Position.Y - node2.Position.Y;

            var isEastWest = diffH.Squared > diffV.Squared;
            this.comparer = isEastWest ? eastWestComparer : southNorthComparer;

            this.Width = width;

            if (this.comparer.Compare(node1, node2) > 0)
            {
                this.intersections = new List<Intersection>(3)
                {
                    node2, node1
                };
            }
            else
            {
                this.intersections = new List<Intersection>(3)
                {
                    node1, node2
                };
            }
        }
Exemple #3
0
        //https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
        public override bool Intersect(Ray ray, out Intersection intersection)
        {
            Statistics.Add("Triangle test");

            intersection = null;

            //don't intersect backside
            if (Vector3.Dot(ray.Direction, Normal) > 0)
            {
                return false;
            }

            var P = Vector3.Cross(ray.Direction, _e2);

            var det = Vector3.Dot(_e1, P);

            //if determinant is near zero, then there is no intersection
            if (det > -float.Epsilon && det < float.Epsilon)
            {
                return false;
            }

            var invDet = 1/det;

            var T = Vector3.Subtract(ray.Origin, _p1);

            //calculate u coordinate of triangle
            var u = Vector3.Dot(T, P)*invDet;

            //if it lies outside the triangle
            if (u < 0 || u > 1)
            {
                return false;
            }

            var Q = Vector3.Cross(T, _e1);

            //calculate v coordinate of triangle
            var v = Vector3.Dot(ray.Direction, Q)*invDet;

            //if it lies outside the triangle
            if (v < 0 || u + v > 1)
            {
                return false;
            }

            //t parameter of ray
            float t = Vector3.Dot(_e2, Q)*invDet;

            if (t > Constants.MinimumRayT && t <= ray.T)
            {
                var intersectionPoint = ray.GetPoint(t);
                ray.SetLength(t);
                intersection = new Intersection(this, ray, Normal, intersectionPoint, t, Material);
                Statistics.Add("Triangle test success");
                return true;
            }

            return false;
        }
Exemple #4
0
    /// <summary>
    /// starting city blueprint O-type
    /// </summary>
    /// <param name="center"></param>
    /// <param name="angle"></param>
    public void AddCityCentreO(Vector2 center, float angle)
    {
        angle = 360f / 8f;
        RoadSegment last = null;
        RoadSegment first = null;
        for (int i=0; i<8; i++)
        {
            Quaternion rotationA = Quaternion.Euler (0, 0, angle * i);
            Quaternion rotationB = Quaternion.Euler (0, 0, angle * (i + 1));

            RoadPoint a = new RoadPoint ();
            a.point = rotationA * (new Vector2 (this.scale / 2.5f, 0) + center);
            RoadPoint b = new RoadPoint ();
            b.point = rotationB * (new Vector2 (this.scale / 2.5f, 0) + center);

            RoadSegment rA = new RoadSegment (a, b, 0);
            this.RoadSegments.Add(rA);
            if(first == null)
                first = rA;

            if(last != null)
            {
                Intersection iA = new Intersection (new List<RoadPoint> (){rA.PointA,last.PointA});
                this.RoadIntersections.Add (iA);
            }
            last = rA;
        }

        Intersection iB = new Intersection (new List<RoadPoint> (){first.PointA,last.PointA});
        this.RoadIntersections.Add (iB);
    }
        public override bool TryCalculateIntersection(Ray ray, out Intersection intersection)
        {
            intersection = new Intersection();

            Vector3 vecDirection = ray.Direction;
            Vector3 rayToPlaneDirection = ray.Origin - this.Position;

            float D = Vector3.Dot(this.normalDirection, vecDirection);
            float N = -Vector3.Dot(this.normalDirection, rayToPlaneDirection);

            if (Math.Abs(D) <= .0005f)
            {
                return false;
            }

            float sI = N / D;
            if (sI < 0 || sI > ray.Distance) // Behind or out of range
            {
                return false;
            }

            var intersectionPoint = ray.Origin + (new Vector3(sI) * vecDirection);
            var uv = this.GetUVCoordinate(intersectionPoint);

            var color = Material.GetDiffuseColorAtCoordinates(uv);

            intersection = new Intersection(intersectionPoint, this.normalDirection, ray.Direction, this, color, (ray.Origin - intersectionPoint).Magnitude());
            return true;
        }
        public override bool TryIntersect(Ray r, ref Intersection intersection)
        {
            Transform w2p;
            _worldToPrimitive.Interpolate(r.Time, out w2p);
            Ray ray = w2p.TransformRay(r);
            if (!_primitive.TryIntersect(ray, ref intersection))
                return false;
            r.MaxT = ray.MaxT;
            if (!w2p.IsIdentity())
            {
                // Compute world-to-object transformation for instance
                intersection.WorldToObject = intersection.WorldToObject * w2p;
                intersection.ObjectToWorld = Transform.Invert(intersection.WorldToObject);

                // Transform instance's differential geometry to world space
                Transform primitiveToWorld = Transform.Invert(w2p);
                var dg = intersection.DifferentialGeometry;
                dg.Point = primitiveToWorld.TransformPoint(ref dg.Point);
                dg.Normal = Normal.Normalize(primitiveToWorld.TransformNormal(ref dg.Normal));
                dg.DpDu = primitiveToWorld.TransformVector(ref dg.DpDu);
                dg.DpDv = primitiveToWorld.TransformVector(ref dg.DpDv);
                dg.DnDu = primitiveToWorld.TransformNormal(ref dg.DnDu);
                dg.DnDv = primitiveToWorld.TransformNormal(ref dg.DnDv);
            }
            return true;
        }
Exemple #7
0
        public bool Intersect(Ray ray, out Intersection intersection, out float t)
        {
            float a = Vector.Dot(ray.Direction, ray.Direction);
            Vector omc = ray.Origin - this._center;
            float b = 2 * Vector.Dot(ray.Direction, omc);
            float c = Vector.Dot(omc, omc) - (this._radius * this._radius);

            float sqr = b * b - 4 * c;
            if (sqr < 0)
            {
                intersection = null;
                t = 0;
                return false;
            }

            intersection = new Intersection()
            {
                Shape = this
            };
            if (sqr == 0)
            {
                t = -b / 2;
                intersection.Point = ray[t];
            }
            else
            {
                sqr = (float)System.Math.Sqrt(sqr);
                t = System.Math.Min(-b + sqr, -b - sqr) * 0.5f;
                intersection.Point = ray[t];
            }
            intersection.Normal = new Normal(intersection.Point - this._center);
            GenerateTextureCoords(intersection);
            return true;
        }
Exemple #8
0
        public override PreciseColor GetDiffuseIllumination(Intersection intersection)
        {
            Material material = intersection.Shape3D.Material;
            Vector3D dir = position - intersection.Point;

            float distance = dir.Length;

            var ray = new ColoredRay3D { Start = intersection.Point, End = position };
            NearestIntersection intersections = GetIntersections(ray);
            bool shadowed = false;
            Intersection obstacle = intersections.Get();
            if (obstacle != null && obstacle.Length > 0.05 && obstacle.Length < distance) {
                shadowed = true;
            }

            if (!shadowed) {
                var diffuseColor = new PreciseColor(omni.Color.Red * material.DiffuseColor.Red,
                                            omni.Color.Green * material.DiffuseColor.Green,
                                            omni.Color.Blue * material.DiffuseColor.Blue);
                float diffuseIntensity = omni.Power * (1 - material.Shininess) * System.Math.Abs(Vector3D.Scalar(dir.Normalize(), intersection.Normal));
                diffuseIntensity /= dir.Length * dir.Length;

                Vector3D reflected = Math3D.GetReflectedVector((intersection.Point - position).Normalize(), intersection.Normal);
                float cosTeta = Vector3D.Scalar(reflected, (intersection.Ray.Start - intersection.Ray.End).Normalize());
                float specularIntensity = cosTeta < 0 ? 0 : omni.Power * material.Shininess * (float)System.Math.Pow(cosTeta, 200);
                if (intersection.Shape3D is RESphere) {
                    specularIntensity /= material.Shininess;
                }
                specularIntensity *= 0.05f;

                return diffuseColor * diffuseIntensity + material.SpecularColor * specularIntensity;
            }
            return new PreciseColor();
        }
Exemple #9
0
 public override void OnIntersection(Intersection intersection) {
     int x = (int)(canvas.Width * intersection.TextureU);
     int y = (int)(canvas.Height * intersection.TextureV);
     if (x < 0) x = 0; else if (x >= canvas.Width) x = canvas.Width - 1;
     if (y < 0) y = 0; else if (y >= canvas.Height) y = canvas.Height - 1;
     canvas[x, y] = intersection.Ray.Color;
     base.OnIntersection(intersection);
 }
 public void Init()
 {
     gameControl = GameObject.Find("Game").GetComponent<GameControl>();
     int ix = Random.Range (0, gameControl.nBricksX * 2);
     int iy = Random.Range (0, gameControl.nBricksY);
     nextIntersetion =  new Intersection(ix, iy);
     PlaceAtIntersection();
     clearTrail();
 }
    // Update is called once per frame
    void Update()
    {
        // Move
        UpdatePosition ();

        if (gameControl.IsAtIntersection(transform.localPosition, nextIntersetion, direction)) {
            UpdateDirection();
            nextIntersetion = gameControl.GetNextIntersection(nextIntersetion, direction);
        }
    }
	private void		RetrieveCaptures (Intersection intersection) {
		GameObject		obj;
		
		for (int index = 0; index < intersection.GetDirections().Length; ++index) {
			obj = this.captures[index].transform.GetChild(0).gameObject;
			obj.GetComponent<Text> ().text = this.GetLetter(intersection.GetCaptures()[index]).ToString ();
		}
		obj = this.captures [8].transform.GetChild (0).gameObject;
		obj.GetComponent<Text> ().text = this.GetLetter(intersection.GetPawnType()).ToString ();
	}
Exemple #13
0
 public void Set(Intersection intersection) {
     if (intersection.Length < 0.05) return;
     if (_nearest == null) {
         _nearest = intersection;
         return;
     }
     if (intersection.Length < _nearest.Length) {
         _nearest = intersection;
     }
 }
	public void			EnableInfosPanel (Intersection intersection) {
		this.canvasGroup.alpha = 1;
		this.canvasGroup.interactable = true;
		this.canvasGroup.blocksRaycasts = true;
		this.SetDefaultTextValues ();
		this.RetrieveIntersectionName (intersection);
		this.RetrieveOwnedBy (intersection);
		this.RetrieveIsBreakable (intersection);
		this.RetrieveDirections (intersection);
		this.RetrieveCaptures (intersection);
	}
Exemple #15
0
 public override bool TryCalculateIntersection(Ray ray, out Intersection intersection)
 {
     if (base.TryCalculateIntersection(ray, out intersection) && WithinArea(intersection.Point))
     {
         return true;
     }
     else
     {
         return false;
     }
 }
 public override bool TryIntersect(Ray ray, ref Intersection intersection)
 {
     float thit, rayEpsilon;
     DifferentialGeometry dg;
     if (!_shape.TryIntersect(ray, out thit, out rayEpsilon, out dg))
         return false;
     intersection = new Intersection(dg, this,
         _shape.ObjectToWorld, _shape.WorldToObject,
         rayEpsilon);
     ray.MaxT = thit;
     return true;
 }
Exemple #17
0
        public override bool Intersect(Ray ray, out Intersection intersection)
        {
            intersection = null;

            var C = ray.Origin - Center;
            float t;
            //inside sphere
            var dotC = Vector3.Dot(C, C);
            var insideSphere = dotC <= _rad2;
            if (insideSphere)
            {
                //slow way to calculate
                var a = Vector3.Dot(ray.Direction, ray.Direction);
                var b = Vector3.Dot(2*ray.Direction, C);
                var c = dotC - _rad2;
                var d = b*b - 4*a*c;

                //no intersection
                if (d < 0)
                {
                    return false;
                }

                var sd = (float)Math.Sqrt(d);
                var t1 = (-b + sd)/2*a;
                var t2 = (-b - sd)/2*a;
                t = Math.Max(t1, t2);
            }
            else
            {
                //fast way to calculate
                t = Vector3.Dot(-C, ray.Direction);
                var q = -C - t*ray.Direction;
                float p2 = Vector3.Dot(q, q);
                if (p2 > _rad2) return false;
                t -= (float) Math.Sqrt(_rad2 - p2);
            }

            if (t > float.Epsilon)
            {
                var intersectionPoint = ray.GetPoint(t);
                var normal = (intersectionPoint - Center).Normalized();
                if (insideSphere)
                {
                    normal *= -1;
                }
                var mat = insideSphere ? Material.Air : Material;
                intersection = new Intersection(this, ray, normal, intersectionPoint, t, mat, insideSphere);
                return true;
            }

            return false;
        }
Exemple #18
0
        public override bool Intersect(Ray ray, out Intersection intersection)
        {
            var t = -(Vector3.Dot(ray.Origin, _normal) + _height)/Vector3.Dot(ray.Direction, _normal);
            if (t >= 0)
            {
                var loc = ray.GetPoint(t);
                intersection = new Intersection(this, ray, _normal, loc, t, Material);
                return true;
            }

            intersection = null;
            return false;
        }
Exemple #19
0
 public void intersectionClicked(Intersection i)
 {
     if (currSelectedIntersection == i) {
         i.renderer.material.color = Constants.grey;
         currSelectedIntersection = null;
         return;
     }
     if (currSelectedIntersection != null) {
         currSelectedIntersection.renderer.material.color = Constants.grey;
     }
     currSelectedIntersection = i;
     currSelectedIntersection.renderer.material.color = Constants.selectedGrey;
 }
Exemple #20
0
        public override bool TryCalculateIntersection(Ray ray, out Intersection intersection)
        {
            for (int g = 0; g < polygons.Length; g++)
            {
                if (IntersectsPolygon(polygons[g], ray, out intersection))
                {
                    return true;
                }
            }

            intersection = new Intersection();
            return false;
        }
    public static Intersection LinePlane(Vector3 pA, Vector3 pB, Plane plane, float e, Intersection dst)
    {
        if (dst == null)
        {
            dst = new Intersection();
        }
        float a = plane.normal.x;
        float b = plane.normal.y;
        float c = plane.normal.z;
        float d = plane.distance;
        float x1 = pA.x;
        float y1 = pA.y;
        float z1 = pA.z;
        float x2 = pB.x;
        float y2 = pB.y;
        float z2 = pB.z;

        float r0 = (a * x1) + (b * y1) + (c * z1) + d;
        float r1 = a * (x1 - x2) + b * (y1 - y2) + c * (z1 - z2);
        float u = r0 / r1;

        if (Mathf.Abs(u) < e)
        {
            dst.status = IntersectionType.PARALLEL;
        }
        else if ((u > 0 && u < 1))
        {
            dst.status = IntersectionType.INTERSECTION;
            Vector3 pt = dst.point;
            pt.x = x2 - x1;
            pt.y = y2 - y1;
            pt.z = z2 - z1;
            pt.x *= u;
            pt.y *= u;
            pt.z *= u;
            pt.x += x1;
            pt.y += y1;
            pt.z += z1;

            dst.alpha = u;

            dst.vert.x = pt.x;
            dst.vert.y = pt.y;
            dst.vert.z = pt.z;
        }
        else
        {
            dst.status = IntersectionType.NONE;
        }
        return dst;
    }
Exemple #22
0
        public bool TryIntersect(Ray ray, ref Intersection intersection)
        {
            RefineIfNeeded();

            // Loop over primitives in voxel and find intersections
            bool hitSomething = false;
            for (var i = 0; i < _primitives.Count; ++i)
            {
                var prim = _primitives[i];
                if (prim.TryIntersect(ray, ref intersection))
                    hitSomething = true;
            }
            return hitSomething;
        }
	public bool		breakBy(Intersection I) {
		double 		dist1, dist2;
		Point 		newPoint = new Point (I.X, I.Y);

		/*		
 		* dist1 = Math.Sqrt ((a.x - I.X) * (a.x - I.X) + (a.y - I.Y) * (a.y - I.Y));
		* dist2 = Math.Sqrt ((b.x - I.X) * (b.x - I.X) + (b.y - I.Y) * (b.y - I.Y));
		* dist3 = Math.Sqrt ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
		*/
		dist1 = segment.a.getDistanceFrom (newPoint);
		dist2 = segment.b.getDistanceFrom (newPoint);

		return (segment.distance == dist1 + dist2);
	}
        public static Spectrum SpecularTransmit(RayDifferential ray, Bsdf bsdf,
            Random rng, Intersection isect, Renderer renderer,
            Scene scene, Sample sample)
        {
            Vector wo = -ray.Direction, wi;
            float pdf;
            Point p = bsdf.DgShading.Point;
            Normal n = bsdf.DgShading.Normal;
            Spectrum f = bsdf.SampleF(wo, out wi, new BsdfSample(rng), out pdf,
                BxdfType.Transmission | BxdfType.Specular);
            Spectrum L = Spectrum.CreateBlack();
            if (pdf > 0.0f && !f.IsBlack && Vector.AbsDot(wi, n) != 0.0f)
            {
                // Compute ray differential _rd_ for specular transmission
                var rd = new RayDifferential(p, wi, ray, isect.RayEpsilon);
                if (ray.HasDifferentials)
                {
                    rd.HasDifferentials = true;
                    rd.RxOrigin = p + isect.DifferentialGeometry.DpDx;
                    rd.RyOrigin = p + isect.DifferentialGeometry.DpDy;

                    float eta = bsdf.Eta;
                    Vector w = -wo;
                    if (Vector.Dot(wo, n) < 0)
                        eta = 1.0f / eta;

                    Normal dndx = bsdf.DgShading.DnDu * bsdf.DgShading.DuDx +
                        bsdf.DgShading.DnDv * bsdf.DgShading.DvDx;
                    Normal dndy = bsdf.DgShading.DnDu * bsdf.DgShading.DuDy +
                        bsdf.DgShading.DnDv * bsdf.DgShading.DvDy;

                    Vector dwodx = -ray.RxDirection - wo, dwody = -ray.RyDirection - wo;
                    float dDNdx = Vector.Dot(dwodx, n) + Vector.Dot(wo, dndx);
                    float dDNdy = Vector.Dot(dwody, n) + Vector.Dot(wo, dndy);

                    float mu = eta * Vector.Dot(w, n) - Vector.Dot(wi, n);
                    float dmudx = (eta - (eta * eta * Vector.Dot(w, n)) / Vector.Dot(wi, n)) * dDNdx;
                    float dmudy = (eta - (eta * eta * Vector.Dot(w, n)) / Vector.Dot(wi, n)) * dDNdy;

                    rd.RxDirection = wi + eta * dwodx - (Vector) (mu * dndx + dmudx * n);
                    rd.RyDirection = wi + eta * dwody - (Vector) (mu * dndy + dmudy * n);
                }
                Spectrum Li = renderer.Li(scene, rd, sample, rng);
                L = f * Li * Vector.AbsDot(wi, n) / pdf;
            }
            return L;
        }
Exemple #25
0
 public void fileInput(string inputFile)
 {
     try
       {
           this.reset();
           FileStream readStream = new FileStream(inputFile, FileMode.Open);
           BinaryFormatter formatter = new BinaryFormatter();
           Intersection readData = (Intersection)formatter.Deserialize(readStream);
           readStream.Close();
           modelIntersection = readData;
       }
       catch (Exception ex)
       {
           MessageBox.Show(ex.StackTrace);
       }
       window.refreshSimulationReference(modelIntersection, this);
 }
Exemple #26
0
            public IEnumerator GetEnumerator()
            {
                var t1 = new TriangleIntersector(Vector3.I, Vector3.J, Vector3.K);
                var t1n = new Vector3(1, 1, 1).UnitDirection;
                var e1 = new Edge(Vector3.Zero, new Vector3(1, 1, 1));
                var e2 = new Edge(Vector3.Zero, 2 * Vector3.I);
                var e3 = new Edge(Vector3.Zero, new Vector3(-1, -1, -1));
                var e4 = new Edge(Vector3.I, Vector3.J);
                var i1 = new Intersection(new Vector3(1.0/3.0, 1.0/3.0, 1.0/3.0), t1n);
                var i2 = new Intersection(Vector3.I, t1n);
                var none = Enumerable.Empty<Intersection>();

                yield return new object[] { t1, e1, new[] { i1 } };
                yield return new object[] { t1, e2, new[] { i2 } };
                yield return new object[] { t1, e3, none };
                yield return new object[] { t1, e4, none };
            }
Exemple #27
0
        public Block(Street streetEast, Street streetSouth, Street streetWest, Street streetNorth,
            Intersection southEast, Intersection southWest, Intersection northEast, Intersection northWest)
        {
            this.SouthEast = southEast;
            this.SouthWest = southWest;
            this.NorthEast = northEast;
            this.NorthWest = northWest;
            this.Children = new List<Block>(4);
            this.streets = new[] { streetEast, streetSouth, streetWest, streetNorth };

            this.East = streetEast.Intersections[0].Position.X;
            this.West = streetWest.Intersections[0].Position.X;
            this.South = streetSouth.Intersections[0].Position.Y;
            this.North = streetNorth.Intersections[0].Position.Y;

            this.Width = this.East - this.West;
            this.Height = this.North - this.South;
        }
	// Pattern : Pion posé - Ennemi - Ennemi - Case vide
	public static void	CheckThirdCapturePattern(Intersection enemy, int direction) {
		Intersection	secondEnemy = null, empty = null;
		Coordinates		coords;
		int 			oppositeDirection;

		coords = Coordinates.GetDirection (direction, enemy.X, enemy.Y);
		secondEnemy = BoardManager.INSTANCE.GetIntersection (coords);
		if (secondEnemy != null && secondEnemy.GetPawnType () == enemy.GetPawnType ()) {
			coords = Coordinates.GetDirection(direction, secondEnemy.X, secondEnemy.Y);
			empty = BoardManager.INSTANCE.GetIntersection(coords);
			if (empty != null && empty.GetPawnType() == PawnType.NONE) {
				oppositeDirection = Coordinates.GetOppositeDirection(direction);
				empty.GetCaptures()[oppositeDirection] = BoardManager.INSTANCE.GetOppositePawnType (enemy.GetPawnType());
				enemy.Catchable += 1;
				secondEnemy.Catchable += 1;
			}
		}
	}
Exemple #29
0
 public BlockOctreeSearcher()
 {
     intersection = new Intersection();
     pool = new Box3D[10000];
     for (int i = 0; i < 10000; i++)
     {
         pool[i] = new Box3D();
     }
     listpool = new ListBox3d[50];
     for (int i = 0; i < 50; i++)
     {
         listpool[i] = new ListBox3d();
         listpool[i].arr = new Box3D[1000];
     }
     l = new BlockPosSide[1024];
     lCount = 0;
     currentHit = new float[3];
 }
    //TODO
    public Direction[] AllowedDirections(Intersection intersection, Direction currentDirection)
    {
        Direction[] allowedDirections = new Direction[0];

        //TODO: better corners
        if (intersection.ix == 0) {
            allowedDirections = new Direction[1];
            allowedDirections [0] = Direction.Right;

        } else if (intersection.ix == nIntersectionsX - 1) {
            allowedDirections = new Direction[1];
            allowedDirections [0] = Direction.Left;

        } else if (intersection.iy == 0) {
            allowedDirections = new Direction[1];
            allowedDirections [0] = Direction.Up;

        } else if (intersection.iy == nIntersectionsY - 1) {
            allowedDirections = new Direction[1];
            allowedDirections [0] = Direction.Down;

        } else if (currentDirection == Direction.Up || currentDirection == Direction.Down) {
            allowedDirections = new Direction[2];
            allowedDirections [0] = Direction.Right;
            allowedDirections [1] = Direction.Left;

        } else {
            if ((intersection.ix % 2 == 0 && intersection.iy % 2 == 0)
                    || (intersection.ix % 2 == 1 && intersection.iy % 2 == 1)) {
                allowedDirections = new Direction[2];
                allowedDirections [0] = currentDirection;
                allowedDirections [1] = Direction.Down;

            } else if ((intersection.ix % 2 == 0 && intersection.iy % 2 == 1)
                    || (intersection.ix % 2 == 1 && intersection.iy % 2 == 0)) {
                allowedDirections = new Direction[2];
                allowedDirections [0] = currentDirection;
                allowedDirections [1] = Direction.Up;

            }
        }

        return allowedDirections;
    }
Exemple #31
0
 public abstract bool Intersect(Ray ray, out Intersection intersection);
 public void addNeighborIntersection(Intersection i)
 {
     neighborIntersections.Add(i.id);
 }
Exemple #33
0
    void PickEntity(Game game, Line3D pick, BlockPosSide[] pick2, IntRef pick2count)
    {
        game.SelectedEntityId        = -1;
        game.currentlyAttackedEntity = -1;
        float one = 1;

        for (int i = 0; i < game.entitiesCount; i++)
        {
            if (game.entities[i] == null)
            {
                continue;
            }
            if (i == game.LocalPlayerId)
            {
                continue;
            }
            if (game.entities[i].drawModel == null)
            {
                continue;
            }
            Entity p_ = game.entities[i];
            if (p_.networkPosition == null)
            {
                continue;
            }
            if (!p_.networkPosition.PositionLoaded)
            {
                continue;
            }
            if (!p_.usable)
            {
                continue;
            }
            float feetposX = p_.position.x;
            float feetposY = p_.position.y;
            float feetposZ = p_.position.z;

            float dist = game.Dist(feetposX, feetposY, feetposZ, game.player.position.x, game.player.position.y, game.player.position.z);
            if (dist > 5)
            {
                continue;
            }

            //var p = PlayerPositionSpawn;
            Box3D bodybox = new Box3D();
            float h       = p_.drawModel.ModelHeight;
            float r       = one * 35 / 100;

            bodybox.AddPoint(feetposX - r, feetposY + 0, feetposZ - r);
            bodybox.AddPoint(feetposX - r, feetposY + 0, feetposZ + r);
            bodybox.AddPoint(feetposX + r, feetposY + 0, feetposZ - r);
            bodybox.AddPoint(feetposX + r, feetposY + 0, feetposZ + r);

            bodybox.AddPoint(feetposX - r, feetposY + h, feetposZ - r);
            bodybox.AddPoint(feetposX - r, feetposY + h, feetposZ + r);
            bodybox.AddPoint(feetposX + r, feetposY + h, feetposZ - r);
            bodybox.AddPoint(feetposX + r, feetposY + h, feetposZ + r);

            float[] p;
            float   localeyeposX = game.EyesPosX();
            float   localeyeposY = game.EyesPosY();
            float   localeyeposZ = game.EyesPosZ();
            p = Intersection.CheckLineBoxExact(pick, bodybox);
            if (p != null)
            {
                //do not allow to shoot through terrain
                if (pick2count.value == 0 || (game.Dist(pick2[0].blockPos[0], pick2[0].blockPos[1], pick2[0].blockPos[2], localeyeposX, localeyeposY, localeyeposZ)
                                              > game.Dist(p[0], p[1], p[2], localeyeposX, localeyeposY, localeyeposZ)))
                {
                    game.SelectedEntityId = i;
                    if (game.cameratype == CameraType.Fpp || game.cameratype == CameraType.Tpp)
                    {
                        game.currentlyAttackedEntity = i;
                    }
                }
            }
        }
    }
Exemple #34
0
    public List <Intersection> GetIntersections(Vector2 antLocation, Vector2 antDirection)
    {
        float ant_y = antLocation.y;
        float ant_x = antLocation.x;

        GV.directionQuadrants dquad = GV.directionQuadrants.q1;
        if (antDirection.y >= ant_y && antDirection.x >= ant_x)
        {
            dquad = GV.directionQuadrants.q1;
        }
        else if (antDirection.y >= ant_y && antDirection.x < ant_x)
        {
            dquad = GV.directionQuadrants.q2;
        }
        else if (antDirection.y < ant_y && antDirection.x < ant_x)
        {
            dquad = GV.directionQuadrants.q3;
        }
        else if (antDirection.y < ant_y && antDirection.x >= ant_x)
        {
            dquad = GV.directionQuadrants.q4;
        }


        List <PheromoneNode>  relevantNodes      = new List <PheromoneNode>();
        List <PheromoneTrail> relevantTrails     = new List <PheromoneTrail>();
        List <PheromoneTrail> crossingTrails     = new List <PheromoneTrail>();
        List <Intersection>   intersectionPoints = new List <Intersection>();

        if ((antDirection.x - ant_x) != 0)
        {
            float slope       = (antDirection.y - ant_y) / (antDirection.x - ant_x);
            float y_intercept = ant_y - slope * ant_x;

            switch (dquad)
            {
            case GV.directionQuadrants.q1:
                foreach (PheromoneNode node in pheromoneNodes)
                {
                    if (node.transform.position.y >= ant_y && node.transform.position.x >= ant_x)
                    {
                        relevantNodes.Add(node);
                    }
                }
                break;

            case GV.directionQuadrants.q2:
                foreach (PheromoneNode node in pheromoneNodes)
                {
                    if (node.transform.position.y >= ant_y && node.transform.position.x < ant_x)
                    {
                        relevantNodes.Add(node);
                    }
                }
                break;

            case GV.directionQuadrants.q3:
                foreach (PheromoneNode node in pheromoneNodes)
                {
                    if (node.transform.position.y < ant_y && node.transform.position.x < ant_x)
                    {
                        relevantNodes.Add(node);
                    }
                }
                break;

            case GV.directionQuadrants.q4:
                foreach (PheromoneNode node in pheromoneNodes)
                {
                    if (node.transform.position.y < ant_y && node.transform.position.x >= ant_x)
                    {
                        relevantNodes.Add(node);
                    }
                }
                break;

            default:
                break;
            }
            foreach (PheromoneTrail trail in pheromoneTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                if (relevantNodes.Contains(trail.pHome) || relevantNodes.Contains(trail.pAway))
                {
                    relevantTrails.Add(trail);
                }
            }


            foreach (PheromoneTrail trail in relevantTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                if ((trail.pHome.transform.position.y >= (slope * trail.pHome.transform.position.x) + y_intercept &&
                     trail.pAway.transform.position.y <= (slope * trail.pAway.transform.position.x) + y_intercept) ||
                    (trail.pHome.transform.position.y <= (slope * trail.pHome.transform.position.x) + y_intercept &&
                     trail.pAway.transform.position.y >= (slope * trail.pAway.transform.position.x) + y_intercept))
                {
                    crossingTrails.Add(trail);
                }
            }


            foreach (PheromoneTrail trail in pheromoneTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                float pHome_y = trail.pHome.transform.position.y;
                float pHome_x = trail.pHome.transform.position.x;
                float pAway_y = trail.pAway.transform.position.y;
                float pAway_x = trail.pAway.transform.position.x;

                if ((dquad == GV.directionQuadrants.q1 || dquad == GV.directionQuadrants.q3) &&
                    (((pHome_y >= ant_y && pHome_x <= ant_x) && (pAway_y <= ant_y && pAway_x >= ant_x)) ||
                     ((pHome_y <= ant_y && pHome_x >= ant_x) && (pAway_y >= ant_y && pAway_x <= ant_x))))
                {
                    crossingTrails.Add(trail);
                }

                if ((dquad == GV.directionQuadrants.q2 || dquad == GV.directionQuadrants.q4) &&
                    (((pHome_y >= ant_y && pHome_x >= ant_x) && (pAway_y <= ant_y && pAway_x <= ant_x)) ||
                     ((pHome_y <= ant_y && pHome_x <= ant_x) && (pAway_y >= ant_y && pAway_x >= ant_x))))
                {
                    crossingTrails.Add(trail);
                }
            }

            foreach (PheromoneTrail trail in crossingTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                Intersection intersectPoint = new Intersection(Vector2.zero, trail);
                float        pHome_y        = trail.pHome.transform.position.y;
                float        pHome_x        = trail.pHome.transform.position.x;
                float        pAway_y        = trail.pAway.transform.position.y;
                float        pAway_x        = trail.pAway.transform.position.x;
                float        trailSlope;
                float        trailIntercept;

                if (pHome_x > pAway_x)
                {
                    trailSlope = (pHome_y - pAway_y) / (pHome_x - pAway_x);
                }
                else
                {
                    trailSlope = (pAway_y - pHome_y) / (pAway_x - pHome_x);
                }
                trailIntercept = pHome_y - (trailSlope * pHome_x);
                intersectPoint._intersectionPoint.x = (trailIntercept - y_intercept) / (slope - trailSlope);
                intersectPoint._intersectionPoint.y = slope * intersectPoint._intersectionPoint.x + y_intercept;
                if (((dquad == GV.directionQuadrants.q1 || dquad == GV.directionQuadrants.q4) && (intersectPoint._intersectionPoint.x > ant_x)) ||
                    ((dquad == GV.directionQuadrants.q2 || dquad == GV.directionQuadrants.q3) && (intersectPoint._intersectionPoint.x < ant_x)))
                {
                    intersectionPoints.Add(intersectPoint);
                }
            }
        }
        else
        {
            foreach (PheromoneTrail trail in relevantTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                if ((trail.pHome.transform.position.x >= ant_x &&
                     trail.pAway.transform.position.x <= ant_x) ||
                    (trail.pHome.transform.position.x <= ant_x &&
                     trail.pAway.transform.position.x >= ant_x))

                {
                    crossingTrails.Add(trail);
                }
            }

            foreach (PheromoneTrail trail in pheromoneTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                float pHome_y = trail.pHome.transform.position.y;
                float pHome_x = trail.pHome.transform.position.x;
                float pAway_y = trail.pAway.transform.position.y;
                float pAway_x = trail.pAway.transform.position.x;

                if ((dquad == GV.directionQuadrants.q1 || dquad == GV.directionQuadrants.q3) &&
                    (((pHome_y >= ant_y && pHome_x <= ant_x) && (pAway_y <= ant_y && pAway_x >= ant_x)) ||
                     ((pHome_y <= ant_y && pHome_x >= ant_x) && (pAway_y >= ant_y && pAway_x <= ant_x))))
                {
                    crossingTrails.Add(trail);
                }

                if ((dquad == GV.directionQuadrants.q2 || dquad == GV.directionQuadrants.q4) &&
                    (((pHome_y >= ant_y && pHome_x >= ant_x) && (pAway_y <= ant_y && pAway_x <= ant_x)) ||
                     ((pHome_y <= ant_y && pHome_x <= ant_x) && (pAway_y >= ant_y && pAway_x >= ant_x))))
                {
                    crossingTrails.Add(trail);
                }
            }

            foreach (PheromoneTrail trail in crossingTrails)
            {
                if (trail.pHome == null || trail.pAway == null)
                {
                    continue;
                }
                Intersection intersectPoint = new Intersection(Vector2.zero, trail);
                float        pHome_y        = trail.pHome.transform.position.y;
                float        pHome_x        = trail.pHome.transform.position.x;
                float        pAway_y        = trail.pAway.transform.position.y;
                float        pAway_x        = trail.pAway.transform.position.x;
                float        trailSlope;
                float        trailIntercept;

                if (pHome_x > pAway_x)
                {
                    trailSlope = (pHome_y - pAway_y) / (pHome_x - pAway_x);
                }
                else
                {
                    trailSlope = (pAway_y - pHome_y) / (pAway_x - pHome_x);
                }
                trailIntercept = pHome_y - (trailSlope * pHome_x);
                intersectPoint._intersectionPoint.x = ant_x;
                intersectPoint._intersectionPoint.y = trailSlope * ant_x + trailIntercept;
                if (((dquad == GV.directionQuadrants.q1 || dquad == GV.directionQuadrants.q4) && (intersectPoint._intersectionPoint.x > ant_x)) ||
                    ((dquad == GV.directionQuadrants.q2 || dquad == GV.directionQuadrants.q3) && (intersectPoint._intersectionPoint.x < ant_x)))
                {
                    intersectionPoints.Add(intersectPoint);
                }
            }
        }


        return(intersectionPoints);
    }
Exemple #35
0
 public override RtVector LocalNormalAt(RtPoint point, Intersection hit)
 {
     return(new RtVector(point.X, point.Y, point.Z));
 }
Exemple #36
0
        public bool GetIntersection(ref BoundingSphere sphere, ref Vector3 velocityNormal, int polyIndex, out OCTreeIntersection intersection)
        {
            var flag = false;

            intersection = new OCTreeIntersection();
            var plane = Planes[polyIndex];

            if (plane.DotNormal(velocityNormal) < 0f)
            {
                if (plane.DotCoordinate(sphere.Center) < 0f)
                {
                    return(false);
                }
                if (plane.Intersects(sphere) != PlaneIntersectionType.Intersecting)
                {
                    return(false);
                }
                var a = Vertices[Indices[polyIndex * 3]];
                var b = Vertices[Indices[(polyIndex * 3) + 1]];
                var c = Vertices[Indices[(polyIndex * 3) + 2]];
                var p = Intersection.ClosestPointOnPlane(sphere.Center, plane);
                if (Intersection.PointInTriangle(p, a, b, c))
                {
                    intersection.IntersectionPoint  = p;
                    intersection.IntersectionNormal = plane.Normal;
                    intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(p, sphere.Center);
                    intersection.Node          = this;
                    intersection.PolygonIndex  = polyIndex;
                    intersection.IntersectType = OCTreeIntersectionType.Inside;
                    flag = true;
                }
                else
                {
                    float   num;
                    Vector3 vector5;
                    if (sphere.Contains(a) != ContainmentType.Disjoint)
                    {
                        intersection.IntersectionPoint  = a;
                        intersection.IntersectionNormal = Vector3.Normalize(sphere.Center - a);
                        intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(a, sphere.Center);
                        intersection.Node          = this;
                        intersection.PolygonIndex  = polyIndex;
                        intersection.IntersectType = OCTreeIntersectionType.Point;
                        return(true);
                    }
                    if (sphere.Contains(b) != ContainmentType.Disjoint)
                    {
                        intersection.IntersectionPoint  = b;
                        intersection.IntersectionNormal = Vector3.Normalize(sphere.Center - b);
                        intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(b, sphere.Center);
                        intersection.Node          = this;
                        intersection.PolygonIndex  = polyIndex;
                        intersection.IntersectType = OCTreeIntersectionType.Point;
                        return(true);
                    }
                    if (sphere.Contains(c) != ContainmentType.Disjoint)
                    {
                        intersection.IntersectionPoint  = c;
                        intersection.IntersectionNormal = Vector3.Normalize(sphere.Center - c);
                        intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(c, sphere.Center);
                        intersection.Node          = this;
                        intersection.PolygonIndex  = polyIndex;
                        intersection.IntersectType = OCTreeIntersectionType.Point;
                        return(true);
                    }
                    Intersection.ClosestPointOnSegment(sphere.Center, a, b, out num, out vector5);
                    if (sphere.Contains(vector5) != ContainmentType.Disjoint)
                    {
                        intersection.IntersectionPoint  = vector5;
                        intersection.IntersectionNormal = Vector3.Normalize(sphere.Center - vector5);
                        intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(vector5, sphere.Center);
                        intersection.IntersectType      = OCTreeIntersectionType.Edge;
                        intersection.Node         = this;
                        intersection.PolygonIndex = polyIndex;
                        return(true);
                    }
                    Intersection.ClosestPointOnSegment(sphere.Center, b, c, out num, out vector5);
                    if (sphere.Contains(vector5) != ContainmentType.Disjoint)
                    {
                        intersection.IntersectionPoint  = vector5;
                        intersection.IntersectionNormal = Vector3.Normalize(sphere.Center - vector5);
                        intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(vector5, sphere.Center);
                        intersection.IntersectType      = OCTreeIntersectionType.Edge;
                        intersection.Node         = this;
                        intersection.PolygonIndex = polyIndex;
                        flag = true;
                    }
                    else
                    {
                        Intersection.ClosestPointOnSegment(sphere.Center, c, a, out num, out vector5);
                        if (sphere.Contains(vector5) != ContainmentType.Disjoint)
                        {
                            intersection.IntersectionPoint  = vector5;
                            intersection.IntersectionNormal = Vector3.Normalize(sphere.Center - vector5);
                            intersection.IntersectionDepth  = sphere.Radius - Vector3.Distance(vector5, sphere.Center);
                            intersection.IntersectType      = OCTreeIntersectionType.Edge;
                            intersection.Node         = this;
                            intersection.PolygonIndex = polyIndex;
                            flag = true;
                        }
                    }
                }
            }
            return(flag);
        }
Exemple #37
0
 public bool HasNoNeighbors(Intersection intersection)
 {
     return(GetAdjacentEdges(intersection).
            SelectMany(edge => GetAdjacentIntersections(edge)).
            All(inter => inter.Equals(intersection) || GetPiece(inter) == null));
 }
Exemple #38
0
        public async Task TestMethod1()
        {
            Func <int, bool> accountFilter = accountId => accountId.ToString().StartsWith("45");

            //Load SBC invoices
            var fromSBC = (await Tools.LoadSBCInvoices(accountFilter)).Select(o => new SBCVariant {
                AccountId      = o.AccountId,
                Amount         = o.Amount,
                CompanyName    = o.Supplier,
                DateRegistered = NodaTime.LocalDate.FromDateTime(o.RegisteredDate),
                DateFinalized  = o.PaymentDate.HasValue ? NodaTime.LocalDate.FromDateTime(o.PaymentDate.Value) : (NodaTime.LocalDate?)null,
                Source         = o,
            }).ToList();

            //Load SIE vouchers
            List <TransactionMatched> fromSIE;
            {
                var files  = Enumerable.Range(2010, 10).Select(o => $"output_{o}.se");
                var sieDir = Tools.GetOutputFolder("SIE");
                var roots  = await SBCExtensions.ReadSIEFiles(files.Select(file => Path.Combine(sieDir, file)));

                var allVouchers = roots.SelectMany(o => o.Children).OfType <VoucherRecord>();

                var matchResult = MatchSLRResult.MatchSLRVouchers(allVouchers, VoucherRecord.DefaultIgnoreVoucherTypes);
                fromSIE = TransactionMatched.FromVoucherMatches(matchResult, TransactionMatched.RequiredAccountIds).Where(o => accountFilter(o.AccountId)).ToList();
            }

            var sbcByName = fromSBC.GroupBy(o => o.CompanyName).ToDictionary(o => o.Key, o => o.ToList());
            var sieByName = fromSIE.GroupBy(o => o.CompanyName).ToDictionary(o => o.Key, o => o.ToList());

            //Create name lookup (can be truncated in one source but not the other):
            Dictionary <string, string> nameLookup;
            {
                var(Intersection, OnlyInA, OnlyInB) = IntersectInfo(sbcByName.Keys, sieByName.Keys);
                nameLookup = Intersection.ToDictionary(o => o, o => o);

                AddLookups(OnlyInA, OnlyInB);
                AddLookups(OnlyInB, OnlyInA);
                void AddLookups(List <string> enumA, List <string> enumB)
                {
                    for (int i = enumA.Count - 1; i >= 0; i--)
                    {
                        var itemA = enumA[i];
                        var itemB = enumB.FirstOrDefault(o => o.StartsWith(itemA));
                        if (itemB != null)
                        {
                            enumB.Remove(itemB);
                            enumA.Remove(itemA);
                            nameLookup.Add(itemB, itemA);
                            nameLookup.Add(itemA, itemB);
                        }
                    }
                }

                //Non-matched: intersectInfo.OnlyInA and intersectInfo.OnlyInB
            }

            var matches = new List <(TransactionMatched, SBCVariant)>();

            foreach (var(sieName, sieList) in sieByName)
            {
                if (nameLookup.ContainsKey(sieName))
                {
                    var inSbc = sbcByName[nameLookup[sieName]].GroupBy(o => o.Amount).ToDictionary(o => o.Key, o => o.ToList());

                    //Multiple passes of the following until no more matches
                    while (true)
                    {
                        var newMatches = new List <(TransactionMatched, SBCVariant)>();
                        for (int sieIndex = sieList.Count - 1; sieIndex >= 0; sieIndex--)
                        {
                            var item = sieList[sieIndex];
                            if (inSbc.TryGetValue(item.Amount, out var sbcSameAmount))
                            {
                                var sbcSameAmountAccount = sbcSameAmount.Where(o => o.AccountId == item.AccountId);
                                //Find those with same register date (could be many)
                                //If multiple or none, take those with closest payment date.
                                //Remove match from inSbc so it can't be matched again
                                var found = new List <SBCVariant>();
                                if (item.DateRegistered is NodaTime.LocalDate dateRegistered)
                                {
                                    found = sbcSameAmountAccount.Where(o => (dateRegistered - item.DateRegistered.Value).Days <= 1).ToList();
                                }
                                else
                                {
                                    found = sbcSameAmountAccount.Where(o => (o.DateFinalized.HasValue && item.DateFinalized.HasValue) &&
                                                                       (o.DateFinalized.Value - item.DateFinalized.Value).Days <= 1).ToList();
                                }

                                if (found.Count > 1)
                                {
                                    var orderByDateDiff = found
                                                          .Where(o => (o.DateFinalized.HasValue && item.DateFinalized.HasValue))
                                                          .Select(o => new
                                    {
#pragma warning disable CS8629 // Nullable value type may be null.
                                        Diff = Math.Abs((o.DateFinalized.Value - item.DateFinalized.Value).Days),
#pragma warning restore CS8629 // Nullable value type may be null.
                                        Object = o
                                    })
                                                          .OrderBy(o => o.Diff);
                                    var minDiff = orderByDateDiff.First().Diff;
                                    if (orderByDateDiff.Count(o => o.Diff == minDiff) == 1)
                                    {
                                        found = orderByDateDiff.Take(1).Select(o => o.Object).ToList();
                                    }
                                }
                                if (found.Count == 1)
                                {
                                    newMatches.Add((item, found.Single()));
                                    sieList.RemoveAt(sieIndex);
                                    sbcSameAmount.Remove(found.First());
                                }
                            }
                        }
                        if (!newMatches.Any())
                        {
                            break;
                        }
                        matches.AddRange(newMatches);
                    }
                }
            }

            var nonmatchedSBC = sbcByName.Values.SelectMany(o => o).Except(matches.Select(o => o.Item2));
            //Remove cancelled-out pairs (same everything but opposite amount):
            var cancelling = nonmatchedSBC.GroupBy(o => $"{o.CompanyName} {Math.Abs(o.Amount)} {o.DateRegistered?.ToSimpleDateString()} {o.DateFinalized?.ToSimpleDateString()}")
                             .Where(o => o.Count() == 2 && o.Sum(o => o.Amount) == 0).SelectMany(o => o);

            nonmatchedSBC = nonmatchedSBC.Except(cancelling);

            var nonmatched = nonmatchedSBC.Concat(sieByName.Values.SelectMany(o => o).Except(matches.Select(o => o.Item1)));

            var all = matches.Select(o => o.Item1).Concat(nonmatched);

            var sss = string.Join("\n",
                                  all
                                  .OrderBy(o => o.CompanyName).ThenBy(o => o.DateRegistered)
                                  .Select(o => $"{o.CompanyName}\t{o.Amount}\t{o.AccountId}\t{o.DateRegistered?.ToSimpleDateString()}\t{o.DateFinalized?.ToSimpleDateString()}\t{(nonmatched.Contains(o) ? "X" : "")}\t{((o is SBCVariant) ? "SBC" : "")}")
                                  );
        }
Exemple #39
0
        public override Intersection Intersect(Ray r)
        {
            // Determine if there is an intersection, and find out where.
            float A     = Vector3.Dot(r.D, r.D);
            float B     = 2f * Vector3.Dot(r.D, r.O - O);
            float C     = Vector3.Dot(r.O - O, r.O - O) - R * R;
            float discr = B * B - 4f * A * C;

            if (discr < 0)
            {
                return(null);           // negative discriminant, miss
            }
            float rootDiscr = (float)Math.Sqrt(discr);
            float q;

            if (B < 0)
            {
                q = -0.5f * (B - rootDiscr);
            }
            else
            {
                q = -0.5f * (B + rootDiscr);
            }
            float t0 = q / A;
            float t1 = C / q;

            if (t0 > t1)
            {
                Swap(ref t0, ref t1);
            }
            if (t0 < 0)
            {
                return(null);        // behind us, miss
            }
            // We need the point of intersection (x,y,z), and
            // the normal of the geometry at the point of intersection.
            // We also add the shape itself to reference the material data.
            var result = new Intersection
            {
                O      = r.PointAt(t0),
                Shape  = this,
                Normal = Vector3.Normalize(r.PointAt(t0) - O),
                T      = t0 // Distance from the camera to the point of intersection
                            // on the object.
            };

            // Calculate UV coordinates for texture mapping. Transforms spherical
            // coordinates to UV coordinates between [0,1]^2.
            var phit = r.PointAt(t0) - O;

            if (phit.X == 0f && phit.Y == 0f)
            {
                phit.X = 1e-5f * R;
            }
            float phi = (float)Math.Atan2(phit.Y, phit.X);

            if (phi < 0f)
            {
                phi += 2f * (float)Math.PI;
            }
            float u     = phi / PhiMax;
            float theta = (float)Math.Acos(Math.Clamp(phit.Z / R, -1f, 1f));
            float v     = (theta - ThetaMin) / (ThetaMax - ThetaMin);

            result.UV = new Vector2(u, v);

            return(result);
        }
Exemple #40
0
 public void SetIntersection(Intersection intersection)
 {
     RoadIntersection = intersection;
 }
Exemple #41
0
        public override Tuple NormalAtLocal(Tuple objectPoint, Intersection hit = null)
        {
            var objectNormal = Helper.CreateVector(objectPoint.X, objectPoint.Y, objectPoint.Z);

            return(objectNormal);
        }
Exemple #42
0
    ///<summary>
    ///Take care of the instructions that the car will take
    ///Se encarga de las direcciones que va a tomar el coche
    ///</summary>
    void OnMouseDown()
    {
        //Si esta baldosa tiene la flecha activada entonces permitimos que se pulse en ella
        bool       arrowActive = false;
        GameObject arrow       = this.gameObject.transform.GetChild(0).gameObject;

        if (arrow.activeInHierarchy)
        {
            arrowActive = true;
        }

        //No se permite pulsar una flecha si está el mapa abierto
        if (!car.mapOpened && arrowActive && !car.isMoving())
        {
            string       tagPosition = null;
            Intersection inter       = transform.parent.gameObject.GetComponent <Intersection>();
            inter.HideArrows();
            car.ResumeCar();
            //El coche ya no está en una interseción.
            car.intersection = false;

            switch (car.dir())
            {
            case CarMove.Direction.NE:

                switch (name)
                {
                case "NW":
                    tagPosition = "L";
                    break;

                case "NE":
                    tagPosition = "S";
                    break;

                case "SE":
                    tagPosition = "R";
                    break;
                }

                break;

            case CarMove.Direction.SE:

                switch (name)
                {
                case "SW":
                    tagPosition = "R";
                    break;

                case "SE":
                    tagPosition = "S";
                    break;

                case "NE":
                    tagPosition = "L";
                    break;
                }

                break;

            case CarMove.Direction.SW:

                switch (name)
                {
                case "SE":
                    tagPosition = "L";
                    break;

                case "SW":
                    tagPosition = "S";
                    break;

                case "NW":
                    tagPosition = "R";
                    break;
                }

                break;

            default:

                switch (name)
                {
                case "SW":
                    tagPosition = "L";
                    break;

                case "NW":
                    tagPosition = "S";
                    break;

                case "NE":
                    tagPosition = "R";
                    break;
                }

                break;
            }

            inter.ChangeTag(tagPosition, car.dir());
        }
    }
Exemple #43
0
 public abstract BSDF GetBSDF(ref Intersection intersection);
Exemple #44
0
            protected override void SolveInstance(IGH_DataAccess DA)
            {
                try {
                    //Input
                    Surface S = s;
                    //if (!DA.GetData(0, ref S)) { return; }
                    DA.GetData(0, ref S);
                    Point3d P = Point3d.Unset;

                    if (!DA.GetData(1, ref P))
                    {
                        P = S.PointAt(S.Domain(0).Mid, S.Domain(1).Mid);
                    }

                    double R = Rhino.RhinoMath.UnsetValue;
                    if (!DA.GetData(2, ref R))
                    {
                        return;
                    }

                    double A = Rhino.RhinoMath.UnsetValue;
                    if (!DA.GetData(3, ref A))
                    {
                        return;
                    }

                    int max = 0;
                    if (!DA.GetData(4, ref max))
                    {
                        return;
                    }

                    Boolean extend = false;
                    if (!DA.GetData(5, ref extend))
                    {
                        return;
                    }

                    if (R <= 0)
                    {
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Mesh edge length must be a positive, non-zero number.");
                        return;
                    }

                    Mesh cutter = new Mesh();
                    //DA.GetData(8, ref cutter);

                    Surface Sold = S;
                    Sold.SetDomain(0, new Interval(0, 1));
                    Sold.SetDomain(1, new Interval(0, 1));
                    PointCloud cornerPoints = new PointCloud(new Point3d[] { Sold.PointAt(0, 0), Sold.PointAt(0, 1), Sold.PointAt(1, 0), Sold.PointAt(1, 1) });


                    if (extend)   //Extend more and trim edges?
                    {
                        S = S.Extend(IsoStatus.North, R * 2, true);
                        S = S.Extend(IsoStatus.East, R * 2, true);
                        S = S.Extend(IsoStatus.South, R * 2, true);
                        S = S.Extend(IsoStatus.West, R * 2, true);
                    }

                    //int L = 0;
                    //int W = 0;
                    //DA.GetData(6, ref L);
                    //DA.GetData(7, ref W);

                    //----------------------------------------------------------------------------------------------------------//
                    //Solution

                    // starting point
                    double u0, v0;
                    S.ClosestPoint(P, out u0, out v0);

                    //Create plane on surface by point and surface normal, plane x,y axis are directions for the net
                    Plane plane = new Plane(S.PointAt(u0, v0), S.NormalAt(u0, v0));
                    plane.Rotate(Rhino.RhinoMath.ToRadians(A), S.NormalAt(u0, v0));
                    Vector3d[] dir = new Vector3d[] { plane.XAxis *R, plane.YAxis *R, plane.XAxis * -R, plane.YAxis * -R };

                    //Surface
                    Curve[] MyNakedEdges     = Sold.ToBrep().DuplicateNakedEdgeCurves(true, false);
                    Curve   SurfaceNakedEdge = Curve.JoinCurves(MyNakedEdges)[0];
                    Mesh[]  meshes           = new Mesh[] { new Mesh(), new Mesh(), new Mesh(), new Mesh() };

                    //----------------------------------------------------------------------------------------------------------//
                    //Create axis
                    // for each direction, walk out (and store list of points)

                    double           u, v;
                    List <Point3d>[] axis = new List <Point3d> [4];
                    List <Arc>[]     arcs = new List <Arc> [4];
                    polylines = new List <Polyline>();

                    for (int i = 0; i < 4; i++)
                    {
                        // set u and v to starting point
                        u = u0;
                        v = v0;
                        List <Point3d> pts        = new List <Point3d>();
                        List <Arc>     arcCurrent = new List <Arc>();


                        for (int j = 0; j < max + 1; j++)
                        {
                            Point3d pt = S.PointAt(u, v); // get point and normal for uv
                            pts.Add(pt);

                            Vector3d srfNormal = S.NormalAt(u, v) * R;

                            Arc arc = new Arc(pt + srfNormal, pt + dir[i], pt - srfNormal); // create forward facing arc and find intersection point with surface (as uv)
                            arcCurrent.Add(arc);
                            CurveIntersections isct = Intersection.CurveSurface(arc.ToNurbsCurve(), S, 0.01, 0.01);


                            if (isct.Count > 0)
                            {
                                isct[0].SurfacePointParameter(out u, out v);
                            }
                            else
                            {
                                break;
                            }

                            // adjust direction vector (new position - old position)
                            dir[i] = S.PointAt(u, v) - pt;
                        }

                        axis[i] = pts;
                        arcs[i] = arcCurrent;
                    }



                    //----------------------------------------------------------------------------------------------------------//
                    //Build up the mesh quads in between
                    Rhino.RhinoApp.ClearCommandHistoryWindow();

                    GH_PreviewUtil preview = new GH_PreviewUtil(GetValue("Animate", false));

                    Mesh         mesh                = new Mesh();                                                                                                                                                   // target mesh
                    Mesh[]       fourMeshes          = new Mesh[4];
                    List <int>[] faceID              = new List <int>[] { new List <int>(), new List <int>(), new List <int>(), new List <int>() };                                                                  //columns lengths
                    List <List <Polyline> >[] strips = new List <List <Polyline> >[] { new List <List <Polyline> >(), new List <List <Polyline> >(), new List <List <Polyline> >(), new List <List <Polyline> >() }; //columns lengths
                    //List<Polyline> cuts = new List<Polyline>();

                    for (int k = 0; k < 4; k++)   //Loop through each axis

                    {
                        Mesh qmesh = new Mesh();                                                         // local mesh for quadrant

                        Point3d[,] quad = new Point3d[axis[k].Count + 10, axis[(k + 1) % 4].Count + 10]; // 2d array of points
                        int[,] qindex   = new int[axis[k].Count + 10, axis[(k + 1) % 4].Count + 10];     // 2d array of points' indices in local mesh

                        int count = 0;

                        //Add 2nd axis particles
                        for (int i = 0; i < axis[(k + 1) % 4].Count; i++)
                        {
                            quad[0, i] = axis[(k + 1) % 4][i];        //store 2nd axis points in point array
                            qmesh.Vertices.Add(axis[(k + 1) % 4][i]); //also add 2nd axis points to mesh
                            qindex[0, i] = count++;                   //store indicies
                        }


                        for (int i = 1; i < quad.GetLength(0); i++)
                        {
                            if (i < axis[k].Count)              // add axis vertex
                            {
                                quad[i, 0] = axis[k][i];        //store 1st axis points in point array
                                qmesh.Vertices.Add(axis[k][i]); //also add 1st axis points to mesh
                                qindex[i, 0] = count++;         //store indicies
                            }


                            int counter = 0;

                            List <Polyline> currentStrip = new List <Polyline>();
                            // for each column attempt to locate a new vertex in the grid
                            for (int j = 1; j < quad.GetLength(1); j++)
                            {
                                // if quad[i - 1, j] doesn't exist, try to add it and continue (or else break the current row)
                                if (quad[i - 1, j] == new Point3d())
                                {
                                    if (j < 2)
                                    {
                                        break;
                                    }

                                    CurveIntersections isct = this.ArcIntersect(S, quad[i - 1, j - 1], quad[i - 1, j - 2], R);

                                    if (isct.Count > 0)
                                    {
                                        quad[i - 1, j] = isct[0].PointB;
                                        qmesh.Vertices.Add(quad[i - 1, j]);
                                        qindex[i - 1, j] = count++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                // if quad[i, j - 1] doesn't exist, try to create quad[i, j] by projection and skip mesh face creation
                                if (quad[i, j - 1] == new Point3d())
                                {
                                    if (i < 2)
                                    {
                                        break;
                                    }

                                    CurveIntersections isct = this.ArcIntersect(S, quad[i - 1, j], quad[i - 2, j], R);

                                    if (isct.Count > 0)
                                    {
                                        quad[i, j] = isct[0].PointB;
                                        qmesh.Vertices.Add(quad[i, j]);
                                        qindex[i, j] = count++;

                                        continue;
                                    }
                                }

                                // construct a sphere at each neighbouring vertex ([i,j-1] and [i-1,j]) and intersect

                                Sphere sph1 = new Sphere(quad[i, j - 1], R);
                                Sphere sph2 = new Sphere(quad[i - 1, j], R);
                                Circle cir;

                                if (Intersection.SphereSphere(sph1, sph2, out cir) == SphereSphereIntersection.Circle)
                                {
                                    CurveIntersections cin = Intersection.CurveSurface(NurbsCurve.CreateFromCircle(cir), S, 0.01, 0.01);// intersect circle with surface

                                    // attempt to find the new vertex (i.e not [i-1,j-1])

                                    foreach (IntersectionEvent ie in cin)
                                    {
                                        if ((ie.PointA - quad[i - 1, j - 1]).Length > 0.2 * R)  // compare with a tolerance, rather than exact comparison

                                        {
                                            quad[i, j] = ie.PointA;
                                            qmesh.Vertices.Add(quad[i, j]);
                                            qindex[i, j] = count++;

                                            Point3d[] facePt = new Point3d[] { quad[i, j], quad[i - 1, j], quad[i - 1, j - 1], quad[i, j - 1] };

                                            Sold.ClosestPoint(quad[i, j], out double u1, out double v1);
                                            Sold.ClosestPoint(quad[i - 1, j], out double u2, out double v2);
                                            Sold.ClosestPoint(quad[i - 1, j - 1], out double u3, out double v3);
                                            Sold.ClosestPoint(quad[i, j - 1], out double u4, out double v4);

                                            double tolerance = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance * 10;
                                            bool[] flag      = new bool[] {
                                                Sold.PointAt(u1, v1).DistanceTo(quad[i, j]) < tolerance,
                                                Sold.PointAt(u2, v2).DistanceTo(quad[i - 1, j]) < tolerance,
                                                Sold.PointAt(u3, v3).DistanceTo(quad[i - 1, j - 1]) < tolerance,
                                                Sold.PointAt(u4, v4).DistanceTo(quad[i, j - 1]) < tolerance
                                            };



                                            if (flag[0] && flag[1] && flag[2] && flag[3])
                                            {
                                                qmesh.Faces.AddFace(qindex[i, j], qindex[i - 1, j], qindex[i - 1, j - 1], qindex[i, j - 1]);// create quad-face
                                                currentStrip.Add(new Polyline()
                                                {
                                                    quad[i, j], quad[i - 1, j], quad[i - 1, j - 1], quad[i, j - 1], quad[i, j]
                                                });
                                                counter++;
                                            }
                                            else if (flag[0] || flag[1] || flag[2] || flag[3])
                                            {
                                                Polyline temp = new Polyline()
                                                {
                                                    quad[i, j], quad[i - 1, j], quad[i - 1, j - 1], quad[i, j - 1]
                                                };
                                                Polyline trimmedTemp = new Polyline();
                                                //temp = new Polyline() { quad[i, j], quad[i - 1, j], quad[i - 1, j - 1], quad[i, j - 1], quad[i, j] };

                                                double        t = R * 0.1;
                                                HashSet <int> intersectedSurfaceEdgeId = new HashSet <int>();


                                                for (int l = 0; l < 4; l++)
                                                {
                                                    //If point is ons surface
                                                    Sold.ClosestPoint(temp[l], out double cpu, out double cpv);
                                                    if (Sold.PointAt(cpu, cpv).DistanceTo(temp[l]) < Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance)
                                                    {
                                                        trimmedTemp.Add(temp[l]);
                                                    }


                                                    //Intersect line segment with closed brep
                                                    Line faceSegment = new Line(temp[l], temp[MathUtil.Wrap(l + 1, 4)]);

                                                    Point3d[] meshLinePts = Intersection.MeshLine(cutter, faceSegment, out int[] faceIds);
                                                    if (meshLinePts.Length > 0)
                                                    {
                                                        trimmedTemp.Add(meshLinePts[0]);
                                                    }
                                                }


                                                trimmedTemp.Close();
                                                //cuts.Add(trimmedTemp);
                                            }

                                            break;
                                        }
                                    }

                                    if (preview.Enabled)
                                    {
                                        preview.Clear();
                                        preview.AddMesh(mesh);
                                        preview.AddMesh(qmesh);
                                        preview.Redraw();
                                    }
                                } //if sphere intersection
                            }     //for j

                            if (currentStrip.Count > 0)
                            {
                                strips[k].Add(currentStrip);
                            }
                        }//for i



                        mesh.Append(qmesh);// add local mesh to target
                        fourMeshes[k] = qmesh;
                    }//for k



                    //----------------------------------------------------------------------------------------------------------//
                    //Output



                    mesh.Weld(Math.PI);
                    mesh.Compact();
                    mesh.Normals.ComputeNormals();

                    DA.SetData(0, mesh);
                    DA.SetDataTree(1, NGonsCore.GrasshopperUtil.IE2(axis, 0));

                    this.PreparePreview(mesh, DA.Iteration, null, true, null, mesh.GetEdges());
                    //DA.SetDataList(2, cuts);
                    //DA.SetDataTree(3, NGonsCore.GrasshopperUtil.IE4(patches.ToList(), 0));
                    //DA.SetDataList(4, fourMeshes);
                    //DA.SetDataTree(5, GrasshopperUtil.IE3(strips, 0));

                    preview.Clear();
                }catch (Exception e) {
                    GrasshopperUtil.Debug(e);
                }
            }
Exemple #45
0
        //public override bool FindIntersection(Ray ray, out Intersection intersect) {
        //    intersect = new Intersection();
        //    /* orientation of the ray with respect to the triangle's normal,
        //       also used to calculate output parameters*/
        //    float det = -(ray.Direction * this.normalNonNormalized);
        //    /* the non-culling branch */
        //    /* if determinant is near zero, ray is parallel to the plane of triangle */
        //    if ( det.NearZero()) {
        //        return false;
        //    }
        //    /* calculate vector from ray origin to this.vertex1 */
        //    Vector3D vect0 = this.vertex1 - ray.Origin;
        //    /* normal vector used to calculate u and v parameters */
        //    Vector3D nvect = ray.Direction ^ vect0;
        //    float inv_det = 1.0f / det;
        //    /* calculate vector from ray origin to this.vertex2*/
        //    Vector3D vect1 = this.vertex2 - ray.Origin;
        //    /* calculate v parameter and test bounds */
        //    float v = -(vect1 * nvect) * inv_det;
        //    if (v < 0.0f || v > 1.0f) {
        //        return false;
        //    }
        //    /* calculate vector from ray origin to this.vertex3*/
        //    vect1 = this.vertex3 - ray.Origin;
        //    /* calculate v parameter and test bounds */
        //    float u = (vect1 * nvect) * inv_det;
        //    if (u < 0.0f || u + v > 1.0f) {
        //        return false;
        //    }

        //    const double epsilon = 2E-2;
        //    float alpha = 1.0f - (u + v);
        //    if (this.Wireframed && (!u.NearZero(epsilon) && !v.NearZero(epsilon) && !alpha.NearZero(epsilon)))
        //    {
        //        return false;
        //    }

        //    /* calculate t, ray intersects triangle */
        //    float t = -(vect0 * this.normalNonNormalized) * inv_det;
        //    //if (t < 100)
        //    //    return false;
        //    // return 1;
        //    if (t >= MathUtil.Epsilon)
        //    {
        //        intersect.Normal = this.normal;
        //        intersect.TMin = t;

        //        intersect.HitPoint = ray.Origin + (t * ray.Direction);
        //        this.CurrentBarycentricCoordinate = new BarycentricCoordinate(alpha, u, v);
        //        intersect.HitPrimitive = this;
        //        if (this.material != null && this.material.IsTexturized) {
        //            //int widthTex = this.material.Texture.Width - 1;
        //            //int heightTex = this.material.Texture.Height - 1;
        //            //this.material.Color = this.material.Texture.GetPixel((int)(u * widthTex), (int)(v * heightTex));
        //            intersect.CurrentTextureCoordinate.U = u;
        //            intersect.CurrentTextureCoordinate.V = v;
        //        }
        //        return true;
        //    }
        //    return false;
        //}

        #endregion

        public override bool FindIntersection(Ray ray, out Intersection intersect)
        {
            intersect = new Intersection();
            float u, v;

            /* begin calculating determinant - also used to calculate U parameter */
            Vector3D pvec = ray.Direction ^ this.edge2;

            /* if determinant is near zero, ray lies in plane of triangle */
            float det = this.edge1 * pvec;

            /* calculate distance from vert0 to ray origin */
            Vector3D tvec    = ray.Origin - this.vertex1;
            float    inv_det = 1.0f / det;

            Vector3D qvec = tvec ^ this.edge1;

            if (det > MathUtil.Epsilon)
            {
                u = (tvec * pvec);
                if (u < 0.0 || u > det)
                {
                    return(false);
                }

                /* calculate V parameter and test bounds */
                v = (ray.Direction * qvec);
                if (v < 0.0 || u + v > det)
                {
                    return(false);
                }
            }
            else if (det < -MathUtil.Epsilon)
            {
                /* calculate U parameter and test bounds */
                u = (tvec * pvec);
                if (u > 0.0 || u < det)
                {
                    return(false);
                }

                /* calculate V parameter and test bounds */
                v = (ray.Direction * qvec);
                if (v > 0.0 || u + v < det)
                {
                    return(false);
                }
            }
            else
            {
                return(false);  /* ray is parallell to the plane of the triangle */
            }
            u *= inv_det;
            v *= inv_det;
            float alpha = 1.0f - (u + v);

            const double epsilon = 2.5E-2;

            if (this.Wireframed && (!u.NearZero(epsilon) && !v.NearZero(epsilon) && !alpha.NearZero(epsilon)))
            {
                return(false);
            }

            intersect.Normal = this.normal;
            intersect.TMin   = (edge2 * qvec) * inv_det;
            if (intersect.TMin >= MathUtil.Epsilon)
            {
                intersect.HitPoint = ray.Origin + (intersect.TMin * ray.Direction);
                this.CurrentBarycentricCoordinate = new BarycentricCoordinate(alpha, u, v);
                intersect.HitPrimitive            = this;
                if (this.material != null && this.material.IsTexturized)
                {
                    int widthTex  = this.material.Texture.Width - 1;
                    int heightTex = this.material.Texture.Height - 1;
                    this.material.DiffuseColor = this.material.Texture.GetPixel((int)(u * widthTex),
                                                                                (int)(v * heightTex));
                    intersect.CurrentTextureCoordinate.U = u;
                    intersect.CurrentTextureCoordinate.V = v;
                }
                return(true);
            }

            return(false);
        }
Exemple #46
0
 public abstract bool TryIntersect(Ray ray, ref Intersection intersection);
Exemple #47
0
    /// <summary>
    /// 判断碰撞盒是否可通行
    /// </summary>
    /// <param name="polygon"></param>
    /// <param name="character"></param>
    /// <param name="isPlayerStep">判定玩家的行走</param>
    /// <returns></returns>
    public bool isPassable(Intersection.Polygon polygon, GameCharacterBase character)
    {
        if (character.through)
        {
            return(true);
        }
        // 检测图块通行
        foreach (Intersection.Polygon mapCollider in this.mapInfo.passageColliders)
        {
            if (Intersection.polygonPolygon(mapCollider, polygon))
            {
                return(false);
            }
        }
        // 检测事件通行
        character.lastHit.Clear();
        foreach (GameEvent e in this.events)
        {
            Intersection.Polygon eventCollider = e.currCollider();
            if (e.through == false && Intersection.polygonPolygon(eventCollider, polygon))
            {
                if (character != null && character != e && !e.erased && !character.lastHit.Contains(e))
                {
                    character.lastHit.Add(e);
                }

                if (character.GetType() == typeof(GameEvent))
                {
                    GameEvent eChar = (GameEvent)character;
                    if (!e.erased && !e.through && e.priorityType == GameCharacterBase.PRIORITIES.SAME && e.isPageActive() && character != e &&
                        !eChar.erased && !eChar.through && eChar.priorityType == GameCharacterBase.PRIORITIES.SAME)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!e.erased && !e.through && e.priorityType == GameCharacterBase.PRIORITIES.SAME && e.isPageActive() && character != e)
                    {
                        return(false);
                    }
                }
            }
        }
        // 检查事件碰到主角
        if (character.GetType() == typeof(GameEvent))
        {
            Intersection.Polygon playerCollider = GameTemp.gamePlayer.currCollider();
            GameEvent            e = (GameEvent)character;
            if (e.through == false && Intersection.polygonPolygon(playerCollider, polygon))
            {
                if (e != null && !e.erased && !e.lastHit.Contains(GameTemp.gamePlayer))
                {
                    e.lastHit.Add(GameTemp.gamePlayer);
                    if (!GameTemp.gamePlayer.lastHit.Contains(e))
                    {
                        GameTemp.gamePlayer.lastHit.Add(e);                             // 给玩家碰撞数据加上本事件
                    }
                }
                if (!e.erased && !e.through && e.isPageActive() && e.priorityType == GameCharacterBase.PRIORITIES.SAME)
                {
                    return(false);
                }
            }
        }
        return(true);
    }
Exemple #48
0
        /// <summary>
        /// Retruns a Collction of Tiles inside a Cone based on the Range Specified
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="request"></param>
        /// <param name="callback"></param>
        public static void FindConeRange(this Tilemap grid, ConeRangeRequest request, System.Action <RangeResult> callback)
        {
            List <Tile>   coneTiles = new List <Tile>();
            List <ushort> distances = new List <ushort>();

            Intersection originIntersection = grid.GetNearestIntersection(request.origin, GetConeOriginDirection(request.origin, request.position));
            short        rangeInTiles       = (short)(request.range / 5);

            int   iCap = 0, jCap = 0;
            int   jStartIndex = 0, jEndIndex = 0;
            int   iOrigin = 0, jOrigin = 0;
            short iModifier = 0;

            //Get from a GridUtility called GetConeDirection
            Direction direction = GetConeDirection(request.origin, request.position);

            switch (direction)
            {
            case Direction.North:
                iOrigin = originIntersection.y;
                jOrigin = originIntersection.x;

                iCap = grid.Rows + 1;
                jCap = grid.Columns + 1;

                jStartIndex = jOrigin - rangeInTiles;
                jEndIndex   = jOrigin + rangeInTiles;

                iModifier = 1;
                break;

            case Direction.East:
                iOrigin = originIntersection.x;
                jOrigin = originIntersection.y;

                iCap = grid.Columns + 1;
                jCap = grid.Rows + 1;

                jStartIndex = jOrigin - rangeInTiles;
                jEndIndex   = jOrigin + rangeInTiles;

                iModifier = 1;
                break;

            case Direction.South:
                iOrigin = originIntersection.y;
                jOrigin = originIntersection.x;

                iCap = grid.Rows + 1;
                jCap = grid.Columns + 1;

                jStartIndex = jOrigin - rangeInTiles;
                jEndIndex   = jOrigin + rangeInTiles;

                iModifier = -1;
                break;

            case Direction.West:
                iOrigin = originIntersection.x;
                jOrigin = originIntersection.y;

                iCap = grid.Columns + 1;
                jCap = grid.Rows + 1;

                jStartIndex = jOrigin - rangeInTiles;
                jEndIndex   = jOrigin + rangeInTiles;

                iModifier = -1;
                break;

            case Direction.NorthWest:
                iOrigin = originIntersection.y;
                jOrigin = originIntersection.x;

                iCap = grid.Rows + 1;
                jCap = grid.Columns + 1;

                jStartIndex = jOrigin - rangeInTiles;
                jEndIndex   = jOrigin;

                iModifier = 1;
                break;

            case Direction.NorthEast:
                iOrigin = originIntersection.y;
                jOrigin = originIntersection.x;

                iCap = grid.Columns + 1;
                jCap = grid.Rows + 1;

                jStartIndex = jOrigin;
                jEndIndex   = jOrigin + rangeInTiles + 1;

                iModifier = 1;
                break;

            case Direction.SouthEast:
                iOrigin = originIntersection.y;
                jOrigin = originIntersection.x;

                iCap = grid.Rows + 1;
                jCap = grid.Columns + 1;

                jStartIndex = jOrigin;
                jEndIndex   = jOrigin + rangeInTiles + 1;

                iModifier = -1;
                break;

            case Direction.SouthWest:
                iOrigin = originIntersection.y;
                jOrigin = originIntersection.x;

                iCap = grid.Columns + 1;
                jCap = grid.Rows + 1;

                jStartIndex = jOrigin - rangeInTiles;
                jEndIndex   = jOrigin;

                iModifier = -1;
                break;
            }


            for (int i = iOrigin + iModifier, iterations = 0, distanceFromOrigin = 1;
                 iterations < rangeInTiles + 1; iterations++, i += iModifier, distanceFromOrigin++)
            {
                for (int j = jStartIndex; j < jEndIndex; j++)
                {
                    if (j >= 0 && i >= 0 && j < jCap && i < iCap)
                    {
                        Intersection currentIntersection   = grid.Intersections[j, i];
                        Intersection referenceIntersection = grid.Intersections[jOrigin, i];
                        bool         insideCone            = false;

                        switch (direction)
                        {
                        case Direction.North:
                            currentIntersection   = grid.Intersections[j, i];
                            referenceIntersection = grid.Intersections[jOrigin, i];
                            insideCone            = GridUtility.GetDistanceBetweenIntersections(currentIntersection, referenceIntersection)
                                                    <= (distanceFromOrigin * TemporaryConstants.AdjacentDistance);
                            break;

                        case Direction.East:
                            currentIntersection   = grid.Intersections[i, j];
                            referenceIntersection = grid.Intersections[i, jOrigin];
                            insideCone            = GridUtility.GetDistanceBetweenIntersections(currentIntersection, referenceIntersection)
                                                    <= (distanceFromOrigin * TemporaryConstants.AdjacentDistance);
                            break;

                        case Direction.South:
                            currentIntersection   = grid.Intersections[j, i];
                            referenceIntersection = grid.Intersections[jOrigin, i];
                            insideCone            = GridUtility.GetDistanceBetweenIntersections(currentIntersection, referenceIntersection)
                                                    <= (distanceFromOrigin * TemporaryConstants.AdjacentDistance);
                            break;

                        case Direction.West:
                            currentIntersection   = grid.Intersections[i, j];
                            referenceIntersection = grid.Intersections[i, jOrigin];
                            insideCone            = GridUtility.GetDistanceBetweenIntersections(currentIntersection, referenceIntersection)
                                                    <= (distanceFromOrigin * TemporaryConstants.AdjacentDistance);
                            break;

                        default:
                            currentIntersection   = grid.Intersections[j, i];
                            referenceIntersection = grid.Intersections[jOrigin, i];
                            insideCone            = true;
                            break;
                        }

                        if (GridUtility.GetDistanceBetweenIntersections(originIntersection, currentIntersection) <= request.range && insideCone)
                        {
                            coneTiles.Add(grid.GetEncompassedTile(currentIntersection, originIntersection));
                            distances.Add((ushort)GridUtility.GetDistanceBetweenIntersections(originIntersection, currentIntersection));
                        }
                    }
                }
            }

            ConeRange = coneTiles;
            callback(new ConeRangeResult(coneTiles.ToArray(), distances.ToArray(), request.callback));
        }
Exemple #49
0
 public void addIntersection(Intersection intersection)
 {
     linkedIntersections.Add(intersection.id);
 }
        //From http://jgt.akpeters.com/papers/GuigueDevillers03/ray_triangle_intersection.html
        public bool FindIntersection(Ray ray, out Intersection intersect)
        {
            intersect = new Intersection();
            Vector3D vect0, vect1, nvect;
            float    det, inv_det;

            vect0 = this.Vertex2.Position - this.Vertex1.Position;
            vect1 = this.Vertex3.Position - this.Vertex1.Position;
            Vector3D normalNonNormalized = vect0 ^ vect1;

            /* orientation of the ray with respect to the triangle's normal,
             * also used to calculate output parameters*/
            det = -(ray.Direction * normalNonNormalized);
#if TEST_CULL
            /* define TEST_CULL if culling is desired */
            if (det < MathUtil.Epsilon)
            {
                return(false);
            }

            /* calculate vector from ray origin to this.vertex1 */
            vect0 = this.Vertex1.Position - ray.Origin;
            /* vector used to calculate u and v parameters */
            nvect = ray.Direction ^ vect0;

            /* calculate vector from ray origin to this.vertex2*/
            vect1 = this.Vertex2.Position - ray.Origin;
            /* calculate unnormalized v parameter and test bounds */
            float v = -(vect1 * nvect);

            if (v < 0.0 || v > det)
            {
                return(false);
            }

            /* calculate vector from ray origin to this.vertex3*/
            vect1 = this.Vertex3.Position - ray.Origin;
            /* calculate unnormalized v parameter and test bounds */
            float u = vect1 * nvect;

            if (u < 0.0 || u + v > det)
            {
                return(false);
            }

            /* calculate unormalized t parameter */
            float t = -(vect0 * normalNonNormalized);

            inv_det = 1.0f / det;
            /* calculate u v t, ray intersects triangle */
            u = u * inv_det;
            v = v * inv_det;
            t = t * inv_det;
#else
            /* the non-culling branch */

            /* if determinant is near zero, ray is parallel to the plane of triangle */
            if (det.NearZero())
            {
                return(false);
            }

            /* calculate vector from ray origin to this.vertex1 */
            vect0 = this.Vertex1.Position - ray.Origin;

            /* normal vector used to calculate u and v parameters */
            nvect = ray.Direction ^ vect0;

            inv_det = 1.0f / det;
            /* calculate vector from ray origin to this.vertex2*/
            vect1 = this.Vertex2.Position - ray.Origin;

            /* calculate v parameter and test bounds */
            float v = -(vect1 * nvect) * inv_det;

            if (v < 0.0f || v > 1.0f)
            {
                return(false);
            }

            /* calculate vector from ray origin to this.vertex3*/
            vect1 = this.Vertex3.Position - ray.Origin;
            /* calculate v parameter and test bounds */
            float u = (vect1 * nvect) * inv_det;

            if (u < 0.0f || u + v > 1.0f)
            {
                return(false);
            }

            /* calculate t, ray intersects triangle */
            float t = -(vect0 * normalNonNormalized) * inv_det;
#endif

            //if (t < 100)
            //    return false;
            // return 1;

            //if (t < 100) //FIXME: the correct is t < 0, but dont work, why? tell me you! =P
            //{
            //    return false;
            //}
            if (t >= 0)
            {
                intersect.TMin     = t;
                intersect.Normal   = Vector3D.Normal(this.Vertex1.Position, this.Vertex2.Position, this.Vertex3.Position);
                intersect.HitPoint = ray.Origin + (t * ray.Direction);
                this.CurrentBarycentricCoordinate = new BarycentricCoordinate(1.0f - (u + v), u, v);
                intersect.HitPrimitive            = this;
                return(true);
            }
            return(false);
        }
Exemple #51
0
 public Piece GetPiece(Intersection intersection)
 {
     return(settlements.ContainsKey(intersection) ? settlements[intersection] : null);
 }
 public void AddIntersection(Intersection intersection)
 {
     Intersections.Add(intersection);
 }
Exemple #53
0
 public abstract Spectrum Li(Scene scene, RayDifferential ray, Sample sample, Random rng,
                             ref Intersection intersection, out Spectrum t);
Exemple #54
0
    IEnumerator ProceduralLocal()
    {
        msg.Stop(Job.StartProcedural);
        msg.Start(Job.ProceduralPreparation);
        SimpleClient.jobStatus[jobNumber] = msg;

        this.transform.position = TilePosition - new Vector3((float)TileManager.TileWidth * (float)TileManager.Scaling / 2f, 0f, (float)TileManager.TileWidth * (float)TileManager.Scaling / 2f);
        terrain = this.gameObject.GetOrAddComponent <Terrain>();
        tC      = this.gameObject.GetOrAddComponent <TerrainCollider>();

        Building.Clear();
        Intersection.Clear();
        Street.Clear();
        Water.Clear();
        River.Clear();
        Bridge.Clear();

        unusedWays.Clear();
        streets.Clear();

        streetPolygons.Clear();

        msg.Stop(Job.ProceduralPreparation);

        #region LOD0
        if (lOD == 0)
        {
            Console.AddMessage("Procedural lod 0");
            Debug.Log("Procedural lod 0");
            #region terrain
            TerrainData terrainData = new TerrainData();

            //HeightMap
            terrainData.heightmapResolution = 257;
            float[,] heights = new float[257, 257];
            for (int x = 0; x < heights.GetLength(0); x++)
            {
                for (int y = 0; y < heights.GetLength(1); y++)
                {
                    heights[x, y] = 1f;
                }
            }

            terrainData.SetHeights(0, 0, heights);
            terrainData.size = new Vector3((float)TileManager.TileWidth * (float)TileManager.Scaling, 10f, (float)TileManager.TileWidth * (float)TileManager.Scaling);

            ////SplatPrototypes
            //SplatPrototype[] splatPrototypes = new SplatPrototype[1];
            //splatPrototypes[0] = new SplatPrototype();
            ////splatPrototypes[0].texture = (Texture2D)Resources.Load("Textures/White1px");
            //splatPrototypes[0].texture = (Texture2D)Resources.Load("Textures/Terrain/Grass (Hill)");

            //terrainData.splatPrototypes = splatPrototypes;

            terrain.terrainData = terrainData;
            tC.terrainData      = terrainData;
            #endregion terrain
            #region mesh
            TileMesh.Clear();

            Vertex[] tileQuadVertices = new Vertex[4];
            tileQuadVertices[0] = new Vertex(new Vector3((float)(-TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(-TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);
            tileQuadVertices[1] = new Vertex(new Vector3((float)(-TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);
            tileQuadVertices[2] = new Vertex(new Vector3((float)(TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);
            tileQuadVertices[3] = new Vertex(new Vector3((float)(TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(-TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);

            new Quad(tileQuadVertices, TileMesh, MaterialManager.GetMaterial("diffuseBrown"));

            TileMesh.FillMeshDivideMaterialsKeepMeshStructure(transform, true);
            #endregion
            Debug.Log("Procedural lod 0 - Done");
        }
        #endregion

        #region LOD5
        if (lOD == 5)
        {
            msg.Start(Job.CreateTerrain);
            SimpleClient.jobStatus[jobNumber] = msg;

            #region terrain
            if (terrain.terrainData == null)
            {
                terrain.terrainData = new TerrainData();
            }
            //HeightMap
            terrain.terrainData.heightmapResolution = 257;
            terrain.terrainData.alphamapResolution  = 257;

            float height = 0f;

            terrain.terrainData.SetHeights(0, 0, SRTMHeightProvider.GetInterpolatedTerrain(this.Query.BoundingBox, out height));
            terrain.terrainData.size = new Vector3((float)TileManager.TileWidth * (float)TileManager.Scaling, height, (float)TileManager.TileWidth * (float)TileManager.Scaling);

            tC.terrainData = terrain.terrainData;

            msg.Stop(Job.CreateTerrain);
            #endregion terrain
            #region mesh
            msg.Start(Job.MeshPreparation);
            SimpleClient.jobStatus[jobNumber] = msg;
            TileMesh.Clear();

            if (BackgroundMesh != null)
            {
                BackgroundMesh.Clear();
            }
            else
            {
                BackgroundMesh = new ModularMesh(TileMesh, "BackgroundMesh");
            }

            if (BuildingMesh != null)
            {
                BuildingMesh.Clear();
            }
            else
            {
                BuildingMesh = new ModularMesh(TileMesh, "BuildingMesh");
            }

            if (StreetMesh != null)
            {
                StreetMesh.Clear();
            }
            else
            {
                StreetMesh = new ModularMesh(TileMesh, "StreetMesh");
            }

            if (OtherMesh != null)
            {
                OtherMesh.Clear();
            }
            else
            {
                OtherMesh = new ModularMesh(TileMesh, "OtherMesh");
            }

            msg.Stop(Job.MeshPreparation);

            msg.Start(Job.TileQuad);
            SimpleClient.jobStatus[jobNumber] = msg;

            Vertex[] tileQuadVertices = new Vertex[4];
            tileQuadVertices[0] = new Vertex(new Vector3((float)(-TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(-TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);
            tileQuadVertices[1] = new Vertex(new Vector3((float)(-TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);
            tileQuadVertices[2] = new Vertex(new Vector3((float)(TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);
            tileQuadVertices[3] = new Vertex(new Vector3((float)(TileManager.TileWidth * TileManager.Scaling / 2d), 0f, (float)(-TileManager.TileWidth * TileManager.Scaling / 2d)) + TilePosition);

            new Quad(tileQuadVertices, BackgroundMesh, MaterialManager.GetMaterial("diffuseBlack"));
            msg.Stop(Job.TileQuad);


            yield return(null);

            msg.Start(Job.River);
            SimpleClient.jobStatus[jobNumber] = msg;

            //Create Domain Objects
            ///Relations
            foreach (KeyValuePair <long, OSMRelation> kV in Query.OSM.relations)
            {
                OSMRelation relation = kV.Value;

                River.TryCreateFromOSM(relation, this);
                yield return(null);
            }
            msg.Stop(Job.River);

            msg.Start(Job.Ways);
            SimpleClient.jobStatus[jobNumber] = msg;

            ///Ways
            foreach (KeyValuePair <long, OSMWay> kV in Query.OSM.ways)
            {
                OSMWay way = kV.Value;

                if (!way.FirstInBounds(Query.BoundingBox, Query.OSM))
                {
                    continue;
                }

                if (!Building.TryCreateFromOSM(way, this))
                {
                    if (!Intersection.TryCreateFromOSM(way, this))
                    {
                        if (!Water.TryCreateFromOSM(way, this))
                        {
                        }
                    }
                }

                yield return(null);
            }
            msg.Stop(Job.Ways);

            //Nodes!?
            //foreach (KeyValuePair<long, OSMNode> kV in Query.OSM.nodes)
            //{
            //    OSMNode node = kV.Value;
            //    TrafficSignal.TryCreateFromOSM(node, this);
            //}

            //Debug.Log("CreateStreets");
            ////Create Streets (and Bridges)
            //Street.CreateStreets(this);



            //CreateTheMeshes
            //Debug.Log("CreateAllMeshes StreetMesh");
            //Street.CreateAllMeshes(StreetMesh);

            //Debug.Log("CreateAllMeshes StreetMesh Bridge");
            //Bridge.CreateAllMeshes(StreetMesh);
            //Debug.Log("CreateAllMeshes StreetMesh Intersection");
            //Intersection.CreateAllMeshes(StreetMesh);

            //Debug.Log("CreateAllMeshes StreetMesh Street");
            //Street.CreateAllMeshes(StreetMesh); // A second time, cause Intersections change streetproperties
            msg.Start(Job.CreateBuildingMesh);
            SimpleClient.jobStatus[jobNumber] = msg;

            Building.CreateAllMeshes(BuildingMesh);
            msg.Stop(Job.CreateBuildingMesh);
            //Debug.Log("CreateAllMeshes Water");
            //Water.CreateAllMeshes(OtherMesh);
            //Debug.Log("CreateAllMeshes TrafficSignal");
            //TrafficSignal.CreateAllMeshes(OtherMesh);

            //StreetPolygon currentStreetPolygon;
            //bool hasLeftPolygon = false;
            //bool hasRightPolygon = false;
            //for (int i = 0; i < streets.Count; i++)
            //{
            //    for (int j = 0; j < streetPolygons.Count; j++)
            //    {
            //        hasLeftPolygon = streetPolygons[j].IsLefthandPolygonOf(streets[i]);
            //        hasRightPolygon = streetPolygons[j].IsRighthandPolygonOf(streets[i]);
            //    }
            //    if (!hasLeftPolygon)
            //    {
            //        if (StreetPolygon.GetLefthandStreetPolygon(streets[i], out currentStreetPolygon))
            //            streetPolygons.Add(currentStreetPolygon);
            //    }
            //    if (!hasRightPolygon)
            //    {
            //        if (StreetPolygon.GetRighthandStreetPolygon(streets[i], out currentStreetPolygon))
            //            streetPolygons.Add(currentStreetPolygon);
            //    }

            //    hasLeftPolygon = false;
            //    hasRightPolygon = false;
            //}

            //for (int i = 0; i < streetPolygons.Count; i++)
            //{
            //    streetPolygons[i].Triangulate(StreetMesh , MaterialManager.GetMaterial("error"));
            //}


            msg.Start(Job.FillMeshDivideMaterials);
            SimpleClient.jobStatus[jobNumber] = msg;
            TileMesh.FillMeshDivideMaterialsKeepMeshStructure(transform, true);
            msg.Stop(Job.FillMeshDivideMaterials);
            #endregion
        }
        #endregion

        msg.Start(Job.GarbageCollection);
        SimpleClient.jobStatus[jobNumber] = msg;
        System.GC.Collect();
        msg.Stop(Job.GarbageCollection);

        yield return(null);

        msg.Start(Job.ProceduralDone);
        SimpleClient.jobStatus[jobNumber] = msg;
        OnProceduralDoneLocal();
        msg.Stop(Job.Worker);
        msg.Stop();

        yield return(true);
    }
Exemple #55
0
        public override bool FindIntersection(Ray ray, out Intersection intersect)
        {
            intersect = new Intersection();
            float        maxFrontDist = float.MinValue;
            float        minBackDist = float.MaxValue;
            HitPrimitive frontType = HitPrimitive.None, backType = HitPrimitive.None; // 0, 1, 2 = top, bottom, side
            // Start with the bounding planes
            float pdotn = (ray.Origin * this.centralAxis) - this.centerDotcentralAxis;
            float udotn = ray.Direction * this.centralAxis;

            if (pdotn > this.halfHeight)
            {
                if (udotn >= 0.0)
                {
                    return(false); // Above top plane pointing up
                }
                // Hits top from above
                maxFrontDist = (this.halfHeight - pdotn) / udotn;
                frontType    = HitPrimitive.TopPlane;
                minBackDist  = -(this.halfHeight + pdotn) / udotn;
                backType     = HitPrimitive.BottomPlane;
            }
            else if (pdotn < -this.halfHeight)
            {
                if (udotn <= 0.0)
                {
                    return(false); // Below bottom, pointing down
                }
                // Hits bottom plane from below
                maxFrontDist = -(this.halfHeight + pdotn) / udotn;
                frontType    = HitPrimitive.BottomPlane;
                minBackDist  = (this.halfHeight - pdotn) / udotn;
                backType     = HitPrimitive.TopPlane;
            }
            else if (udotn < 0.0)
            {
                // Inside, pointing down
                minBackDist = -(this.halfHeight + pdotn) / udotn;
                backType    = HitPrimitive.BottomPlane;
            }
            else if (udotn > 0.0)
            {
                // Inside, pointing up
                minBackDist = (this.halfHeight - pdotn) / udotn;
                backType    = HitPrimitive.TopPlane;
            }
            if (maxFrontDist < 0)
            {
                return(false);
            }
            // Now handle the cylinder sides
            Vector3D v = ray.Origin - this.center;
            float    pdotuA = v * this.axisA;
            float    pdotuB = v * this.axisB;
            float    udotuA = ray.Direction * this.axisA;
            float    udotuB = ray.Direction * this.axisB;
            float    C = pdotuA * pdotuA + pdotuB * pdotuB - 1.0f;
            float    B = (pdotuA * udotuA + pdotuB * udotuB);

            if (C >= 0.0 && B > 0.0)
            {
                return(false);    // Pointing away from the cylinder
            }
            B += B;               // Double B for final 2.0 factor
            float A = udotuA * udotuA + udotuB * udotuB;
            float alpha1, alpha2; // The roots, in order
            int   numRoots = EquationSolver.SolveQuadric(A, B, C, out alpha1, out alpha2);

            if (numRoots == 0)
            {
                return(false); // No intersection
            }
            if (alpha1 > maxFrontDist)
            {
                if (alpha1 > minBackDist)
                {
                    return(false);
                }
                maxFrontDist = alpha1;
                frontType    = HitPrimitive.Cylinder;
            }
            if (numRoots == 2 && alpha2 < minBackDist)
            {
                if (alpha2 < maxFrontDist)
                {
                    return(false);
                }
                minBackDist = alpha2;
                backType    = HitPrimitive.Cylinder;
            }
            // Put it all together:
            float        alpha;
            HitPrimitive hitSurface;

            if (maxFrontDist > 0.0)
            {
                intersect.HitFromInSide = true; // Hit from outside
                alpha      = maxFrontDist;
                hitSurface = frontType;
            }
            else
            {
                intersect.HitFromInSide = false; // Hit from inside
                alpha      = minBackDist;
                hitSurface = backType;
            }
            if (alpha < 0.01)
            {
                return(false);
            }
            intersect.TMin = alpha;
            intersect.TMax = alpha2;
            // Set v to the intersection point
            intersect.HitPoint     = ray.Origin + ray.Direction * alpha;
            intersect.HitPrimitive = this;
            // Now set v equal to returned position relative to the center
            v = intersect.HitPoint - this.center;
            float vdotuA = v * this.axisA;
            float vdotuB = v * this.axisB;
            float uCoord = 0;
            float vCoord = 0;

            switch (hitSurface)
            {
            case HitPrimitive.TopPlane:     // Top surface
                intersect.Normal = this.top.Normal;
                // Calculate U-V values for texture coordinates
                uCoord = 0.5f * (1.0f - vdotuA);
                vCoord = 0.5f * (1.0f + vdotuB);
                break;

            case HitPrimitive.BottomPlane:     // Bottom face
                intersect.Normal = this.bottom.Normal;
                // Calculate U-V values for texture coordinates
                uCoord = 0.5f * (1.0f + vdotuA);
                vCoord = 0.5f * (1.0f + vdotuB);
                break;

            case HitPrimitive.Cylinder:     // Cylinder's side
                intersect.Normal = ((vdotuA * this.axisA) + (vdotuB * this.axisB));
                intersect.Normal.Normalize();
                // Calculate u-v coordinates for texture mapping (in range[0,1]x[0,1])
                uCoord = (float)(Math.Atan2(vdotuB, vdotuA) / (Math.PI + Math.PI) + 0.5);
                vCoord = ((v * this.centralAxis) + this.halfHeight) * 1.0f / this.height;
                break;
            }
            if (this.material != null && this.material.IsTexturized)
            {
                //int widthTex = this.material.Texture.Width - 1;
                //int heightTex = this.material.Texture.Height - 1;
                //this.material.Color = this.material.Texture.GetPixel((int)(uCoord * widthTex), (int)(vCoord * heightTex));
                intersect.CurrentTextureCoordinate.U = uCoord;
                intersect.CurrentTextureCoordinate.V = vCoord;
            }
            return(true);
        }
Exemple #56
0
        public static List <Curve> BestSplitterCurves(List <Brep> zones, List <Curve> circ, Curve core)
        {
            int numZones      = zones.Count;
            int numCircCurves = circ.Count;

            List <Curve> splitterCurves = new List <Curve>();

            for (int i = 0; i < numZones; i++)
            {
                int validCircCurves = 0;

                List <bool>   intersects           = new List <bool>();
                List <double> intersectionInterval = new List <double>();

                //RhinoApp.WriteLine("---");

                for (int j = 0; j < numCircCurves; j++)
                {
                    if (Confirm.CurveRegionIntersection(circ[j], zones[i]) && circ[j].Degree == 1)
                    {
                        //RhinoApp.WriteLine("Region intersection exists.");

                        validCircCurves++;
                        intersects.Add(true);

                        CurveIntersections csx = Intersection.CurveSurface(circ[j], zones[i].Surfaces[0], 0.1, 0.1);

                        //RhinoApp.WriteLine("--{0} csx event(s). (Overlap: {1})", csx.Count, csx[0].OverlapA.ToString());

                        intersectionInterval.Add(csx[0].OverlapA.T1 - csx[0].OverlapB.T0);
                    }
                    else
                    {
                        //RhinoApp.WriteLine("Region intersection does not exist.");

                        intersects.Add(false);

                        intersectionInterval.Add(0);
                    }
                }

                if (validCircCurves == 0)
                {
                    //RhinoApp.WriteLine("No circulation options.");

                    Curve newSplitCurve = Select.GenerateSplitCurve(zones[i], core);

                    splitterCurves.Add(newSplitCurve);
                }
                if (validCircCurves == 1)
                {
                    //RhinoApp.WriteLine("Only one option.");
                    splitterCurves.Add(circ[intersects.IndexOf(true)]);
                }
                else if (validCircCurves > 1)
                {
                    //RhinoApp.WriteLine(validCircCurves.ToString() + " options.");
                    splitterCurves.Add(circ[intersectionInterval.IndexOf(intersectionInterval.Max())]);
                }

                intersects.Clear();
                intersectionInterval.Clear();
            }

            return(splitterCurves);
        }
 public IntersectionExitNode(int x, int y, Intersection intersection) : base(x, y)
 {
     this.intersection = intersection;
 }
 bool IllegalSpace(Intersection _intersection)
 {
     return(_intersection.occupant != null);
 }
Exemple #59
0
    internal void NextBullet(Game game, int bulletsshot)
    {
        float one    = 1;
        bool  left   = game.mouseLeft;
        bool  middle = game.mouseMiddle;
        bool  right  = game.mouseRight;

        bool IsNextShot = bulletsshot != 0;

        if (!game.leftpressedpicking)
        {
            if (game.mouseleftclick)
            {
                game.leftpressedpicking = true;
            }
            else
            {
                left = false;
            }
        }
        else
        {
            if (game.mouseleftdeclick)
            {
                game.leftpressedpicking = false;
                left = false;
            }
        }
        if (!left)
        {
            game.currentAttackedBlock = null;
        }

        Packet_Item item          = game.d_Inventory.RightHand[game.ActiveMaterial];
        bool        ispistol      = (item != null && game.blocktypes[item.BlockId].IsPistol);
        bool        ispistolshoot = ispistol && left;
        bool        isgrenade     = ispistol && game.blocktypes[item.BlockId].PistolType == Packet_PistolTypeEnum.Grenade;

        if (ispistol && isgrenade)
        {
            ispistolshoot = game.mouseleftdeclick;
        }
        //grenade cooking
        if (game.mouseleftclick)
        {
            game.grenadecookingstartMilliseconds = game.platform.TimeMillisecondsFromStart();
            if (ispistol && isgrenade)
            {
                if (game.blocktypes[item.BlockId].Sounds.ShootCount > 0)
                {
                    game.AudioPlay(game.platform.StringFormat("{0}.ogg", game.blocktypes[item.BlockId].Sounds.Shoot[0]));
                }
            }
        }
        float wait = ((one * (game.platform.TimeMillisecondsFromStart() - game.grenadecookingstartMilliseconds)) / 1000);

        if (isgrenade && left)
        {
            if (wait >= game.grenadetime && isgrenade && game.grenadecookingstartMilliseconds != 0)
            {
                ispistolshoot         = true;
                game.mouseleftdeclick = true;
            }
            else
            {
                return;
            }
        }
        else
        {
            game.grenadecookingstartMilliseconds = 0;
        }

        if (ispistol && game.mouserightclick && (game.platform.TimeMillisecondsFromStart() - game.lastironsightschangeMilliseconds) >= 500)
        {
            game.IronSights = !game.IronSights;
            game.lastironsightschangeMilliseconds = game.platform.TimeMillisecondsFromStart();
        }

        IntRef pick2count = new IntRef();
        Line3D pick       = new Line3D();

        GetPickingLine(game, pick, ispistolshoot);
        BlockPosSide[] pick2 = game.Pick(game.s, pick, pick2count);

        if (left)
        {
            game.handSetAttackDestroy = true;
        }
        else if (right)
        {
            game.handSetAttackBuild = true;
        }

        if (game.overheadcamera && pick2count.value > 0 && left)
        {
            //if not picked any object, and mouse button is pressed, then walk to destination.
            if (game.Follow == null)
            {
                //Only walk to destination when not following someone
                game.playerdestination = Vector3Ref.Create(pick2[0].blockPos[0], pick2[0].blockPos[1] + 1, pick2[0].blockPos[2]);
            }
        }
        bool pickdistanceok = (pick2count.value > 0); //&& (!ispistol);

        if (pickdistanceok)
        {
            if (game.Dist(pick2[0].blockPos[0] + one / 2, pick2[0].blockPos[1] + one / 2, pick2[0].blockPos[2] + one / 2,
                          pick.Start[0], pick.Start[1], pick.Start[2]) > CurrentPickDistance(game))
            {
                pickdistanceok = false;
            }
        }
        bool playertileempty = game.IsTileEmptyForPhysics(
            game.platform.FloatToInt(game.player.position.x),
            game.platform.FloatToInt(game.player.position.z),
            game.platform.FloatToInt(game.player.position.y + (one / 2)));
        bool playertileemptyclose = game.IsTileEmptyForPhysicsClose(
            game.platform.FloatToInt(game.player.position.x),
            game.platform.FloatToInt(game.player.position.z),
            game.platform.FloatToInt(game.player.position.y + (one / 2)));
        BlockPosSide pick0 = new BlockPosSide();

        if (pick2count.value > 0 &&
            ((pickdistanceok && (playertileempty || (playertileemptyclose))) ||
             game.overheadcamera)
            )
        {
            game.SelectedBlockPositionX = game.platform.FloatToInt(pick2[0].Current()[0]);
            game.SelectedBlockPositionY = game.platform.FloatToInt(pick2[0].Current()[1]);
            game.SelectedBlockPositionZ = game.platform.FloatToInt(pick2[0].Current()[2]);
            pick0 = pick2[0];
        }
        else
        {
            game.SelectedBlockPositionX = -1;
            game.SelectedBlockPositionY = -1;
            game.SelectedBlockPositionZ = -1;
            pick0.blockPos    = new float[3];
            pick0.blockPos[0] = -1;
            pick0.blockPos[1] = -1;
            pick0.blockPos[2] = -1;
        }
        PickEntity(game, pick, pick2, pick2count);
        if (game.cameratype == CameraType.Fpp || game.cameratype == CameraType.Tpp)
        {
            int ntileX = game.platform.FloatToInt(pick0.Current()[0]);
            int ntileY = game.platform.FloatToInt(pick0.Current()[1]);
            int ntileZ = game.platform.FloatToInt(pick0.Current()[2]);
            if (game.IsUsableBlock(game.map.GetBlock(ntileX, ntileZ, ntileY)))
            {
                game.currentAttackedBlock = Vector3IntRef.Create(ntileX, ntileZ, ntileY);
            }
        }
        if (game.GetFreeMouse())
        {
            if (pick2count.value > 0)
            {
                OnPick_(pick0);
            }
            return;
        }

        if ((one * (game.platform.TimeMillisecondsFromStart() - lastbuildMilliseconds) / 1000) >= BuildDelay(game) ||
            IsNextShot)
        {
            if (left && game.d_Inventory.RightHand[game.ActiveMaterial] == null)
            {
                game.SendPacketClient(ClientPackets.MonsterHit(game.platform.FloatToInt(2 + game.rnd.NextFloat() * 4)));
            }
            if (left && !fastclicking)
            {
                //todo animation
                fastclicking = false;
            }
            if ((left || right || middle) && (!isgrenade))
            {
                lastbuildMilliseconds = game.platform.TimeMillisecondsFromStart();
            }
            if (isgrenade && game.mouseleftdeclick)
            {
                lastbuildMilliseconds = game.platform.TimeMillisecondsFromStart();
            }
            if (game.reloadstartMilliseconds != 0)
            {
                PickingEnd(left, right, middle, ispistol);
                return;
            }
            if (ispistolshoot)
            {
                if ((!(game.LoadedAmmo[item.BlockId] > 0)) ||
                    (!(game.TotalAmmo[item.BlockId] > 0)))
                {
                    game.AudioPlay("Dry Fire Gun-SoundBible.com-2053652037.ogg");
                    PickingEnd(left, right, middle, ispistol);
                    return;
                }
            }
            if (ispistolshoot)
            {
                float toX = pick.End[0];
                float toY = pick.End[1];
                float toZ = pick.End[2];
                if (pick2count.value > 0)
                {
                    toX = pick2[0].blockPos[0];
                    toY = pick2[0].blockPos[1];
                    toZ = pick2[0].blockPos[2];
                }

                Packet_ClientShot shot = new Packet_ClientShot();
                shot.FromX     = game.SerializeFloat(pick.Start[0]);
                shot.FromY     = game.SerializeFloat(pick.Start[1]);
                shot.FromZ     = game.SerializeFloat(pick.Start[2]);
                shot.ToX       = game.SerializeFloat(toX);
                shot.ToY       = game.SerializeFloat(toY);
                shot.ToZ       = game.SerializeFloat(toZ);
                shot.HitPlayer = -1;

                for (int i = 0; i < game.entitiesCount; i++)
                {
                    if (game.entities[i] == null)
                    {
                        continue;
                    }
                    if (game.entities[i].drawModel == null)
                    {
                        continue;
                    }
                    Entity p_ = game.entities[i];
                    if (p_.networkPosition == null)
                    {
                        continue;
                    }
                    if (!p_.networkPosition.PositionLoaded)
                    {
                        continue;
                    }
                    float feetposX = p_.position.x;
                    float feetposY = p_.position.y;
                    float feetposZ = p_.position.z;
                    //var p = PlayerPositionSpawn;
                    Box3D bodybox  = new Box3D();
                    float headsize = (p_.drawModel.ModelHeight - p_.drawModel.eyeHeight) * 2; //0.4f;
                    float h        = p_.drawModel.ModelHeight - headsize;
                    float r        = one * 35 / 100;

                    bodybox.AddPoint(feetposX - r, feetposY + 0, feetposZ - r);
                    bodybox.AddPoint(feetposX - r, feetposY + 0, feetposZ + r);
                    bodybox.AddPoint(feetposX + r, feetposY + 0, feetposZ - r);
                    bodybox.AddPoint(feetposX + r, feetposY + 0, feetposZ + r);

                    bodybox.AddPoint(feetposX - r, feetposY + h, feetposZ - r);
                    bodybox.AddPoint(feetposX - r, feetposY + h, feetposZ + r);
                    bodybox.AddPoint(feetposX + r, feetposY + h, feetposZ - r);
                    bodybox.AddPoint(feetposX + r, feetposY + h, feetposZ + r);

                    Box3D headbox = new Box3D();

                    headbox.AddPoint(feetposX - r, feetposY + h, feetposZ - r);
                    headbox.AddPoint(feetposX - r, feetposY + h, feetposZ + r);
                    headbox.AddPoint(feetposX + r, feetposY + h, feetposZ - r);
                    headbox.AddPoint(feetposX + r, feetposY + h, feetposZ + r);

                    headbox.AddPoint(feetposX - r, feetposY + h + headsize, feetposZ - r);
                    headbox.AddPoint(feetposX - r, feetposY + h + headsize, feetposZ + r);
                    headbox.AddPoint(feetposX + r, feetposY + h + headsize, feetposZ - r);
                    headbox.AddPoint(feetposX + r, feetposY + h + headsize, feetposZ + r);

                    float[] p;
                    float   localeyeposX = game.EyesPosX();
                    float   localeyeposY = game.EyesPosY();
                    float   localeyeposZ = game.EyesPosZ();
                    p = Intersection.CheckLineBoxExact(pick, headbox);
                    if (p != null)
                    {
                        //do not allow to shoot through terrain
                        if (pick2count.value == 0 || (game.Dist(pick2[0].blockPos[0], pick2[0].blockPos[1], pick2[0].blockPos[2], localeyeposX, localeyeposY, localeyeposZ)
                                                      > game.Dist(p[0], p[1], p[2], localeyeposX, localeyeposY, localeyeposZ)))
                        {
                            if (!isgrenade)
                            {
                                Entity entity = new Entity();
                                Sprite sprite = new Sprite();
                                sprite.positionX = p[0];
                                sprite.positionY = p[1];
                                sprite.positionZ = p[2];
                                sprite.image     = "blood.png";
                                entity.sprite    = sprite;
                                entity.expires   = Expires.Create(one * 2 / 10);
                                game.EntityAddLocal(entity);
                            }
                            shot.HitPlayer = i;
                            shot.IsHitHead = 1;
                        }
                    }
                    else
                    {
                        p = Intersection.CheckLineBoxExact(pick, bodybox);
                        if (p != null)
                        {
                            //do not allow to shoot through terrain
                            if (pick2count.value == 0 || (game.Dist(pick2[0].blockPos[0], pick2[0].blockPos[1], pick2[0].blockPos[2], localeyeposX, localeyeposY, localeyeposZ)
                                                          > game.Dist(p[0], p[1], p[2], localeyeposX, localeyeposY, localeyeposZ)))
                            {
                                if (!isgrenade)
                                {
                                    Entity entity = new Entity();
                                    Sprite sprite = new Sprite();
                                    sprite.positionX = p[0];
                                    sprite.positionY = p[1];
                                    sprite.positionZ = p[2];
                                    sprite.image     = "blood.png";
                                    entity.sprite    = sprite;
                                    entity.expires   = Expires.Create(one * 2 / 10);
                                    game.EntityAddLocal(entity);
                                }
                                shot.HitPlayer = i;
                                shot.IsHitHead = 0;
                            }
                        }
                    }
                }
                shot.WeaponBlock = item.BlockId;
                game.LoadedAmmo[item.BlockId] = game.LoadedAmmo[item.BlockId] - 1;
                game.TotalAmmo[item.BlockId]  = game.TotalAmmo[item.BlockId] - 1;
                float projectilespeed = game.DeserializeFloat(game.blocktypes[item.BlockId].ProjectileSpeedFloat);
                if (projectilespeed == 0)
                {
                    {
                        Entity entity = game.CreateBulletEntity(
                            pick.Start[0], pick.Start[1], pick.Start[2],
                            toX, toY, toZ, 150);
                        game.EntityAddLocal(entity);
                    }
                }
                else
                {
                    float vX      = toX - pick.Start[0];
                    float vY      = toY - pick.Start[1];
                    float vZ      = toZ - pick.Start[2];
                    float vLength = game.Length(vX, vY, vZ);
                    vX /= vLength;
                    vY /= vLength;
                    vZ /= vLength;
                    vX *= projectilespeed;
                    vY *= projectilespeed;
                    vZ *= projectilespeed;
                    shot.ExplodesAfter = game.SerializeFloat(game.grenadetime - wait);

                    {
                        Entity grenadeEntity = new Entity();

                        Sprite sprite = new Sprite();
                        sprite.image          = "ChemicalGreen.png";
                        sprite.size           = 14;
                        sprite.animationcount = 0;
                        sprite.positionX      = pick.Start[0];
                        sprite.positionY      = pick.Start[1];
                        sprite.positionZ      = pick.Start[2];
                        grenadeEntity.sprite  = sprite;

                        Grenade_ projectile = new Grenade_();
                        projectile.velocityX    = vX;
                        projectile.velocityY    = vY;
                        projectile.velocityZ    = vZ;
                        projectile.block        = item.BlockId;
                        projectile.sourcePlayer = game.LocalPlayerId;

                        grenadeEntity.expires = Expires.Create(game.grenadetime - wait);

                        grenadeEntity.grenade = projectile;
                        game.EntityAddLocal(grenadeEntity);
                    }
                }
                Packet_Client packet = new Packet_Client();
                packet.Id   = Packet_ClientIdEnum.Shot;
                packet.Shot = shot;
                game.SendPacketClient(packet);

                if (game.blocktypes[item.BlockId].Sounds.ShootEndCount > 0)
                {
                    game.pistolcycle = game.rnd.Next() % game.blocktypes[item.BlockId].Sounds.ShootEndCount;
                    game.AudioPlay(game.platform.StringFormat("{0}.ogg", game.blocktypes[item.BlockId].Sounds.ShootEnd[game.pistolcycle]));
                }

                bulletsshot++;
                if (bulletsshot < game.DeserializeFloat(game.blocktypes[item.BlockId].BulletsPerShotFloat))
                {
                    NextBullet(game, bulletsshot);
                }

                //recoil
                game.player.position.rotx -= game.rnd.NextFloat() * game.CurrentRecoil();
                game.player.position.roty += game.rnd.NextFloat() * game.CurrentRecoil() * 2 - game.CurrentRecoil();

                PickingEnd(left, right, middle, ispistol);
                return;
            }
            if (ispistol && right)
            {
                PickingEnd(left, right, middle, ispistol);
                return;
            }
            if (pick2count.value > 0)
            {
                if (middle)
                {
                    int newtileX = game.platform.FloatToInt(pick0.Current()[0]);
                    int newtileY = game.platform.FloatToInt(pick0.Current()[1]);
                    int newtileZ = game.platform.FloatToInt(pick0.Current()[2]);
                    if (game.map.IsValidPos(newtileX, newtileZ, newtileY))
                    {
                        int  clonesource  = game.map.GetBlock(newtileX, newtileZ, newtileY);
                        int  clonesource2 = game.d_Data.WhenPlayerPlacesGetsConvertedTo()[clonesource];
                        bool gotoDone     = false;
                        //find this block in another right hand.
                        for (int i = 0; i < 10; i++)
                        {
                            if (game.d_Inventory.RightHand[i] != null &&
                                game.d_Inventory.RightHand[i].ItemClass == Packet_ItemClassEnum.Block &&
                                game.d_Inventory.RightHand[i].BlockId == clonesource2)
                            {
                                game.ActiveMaterial = i;
                                gotoDone            = true;
                            }
                        }
                        if (!gotoDone)
                        {
                            IntRef freehand = game.d_InventoryUtil.FreeHand(game.ActiveMaterial);
                            //find this block in inventory.
                            for (int i = 0; i < game.d_Inventory.ItemsCount; i++)
                            {
                                Packet_PositionItem k = game.d_Inventory.Items[i];
                                if (k == null)
                                {
                                    continue;
                                }
                                if (k.Value_.ItemClass == Packet_ItemClassEnum.Block &&
                                    k.Value_.BlockId == clonesource2)
                                {
                                    //free hand
                                    if (freehand != null)
                                    {
                                        game.WearItem(
                                            game.InventoryPositionMainArea(k.X, k.Y),
                                            game.InventoryPositionMaterialSelector(freehand.value));
                                        break;
                                    }
                                    //try to replace current slot
                                    if (game.d_Inventory.RightHand[game.ActiveMaterial] != null &&
                                        game.d_Inventory.RightHand[game.ActiveMaterial].ItemClass == Packet_ItemClassEnum.Block)
                                    {
                                        game.MoveToInventory(
                                            game.InventoryPositionMaterialSelector(game.ActiveMaterial));
                                        game.WearItem(
                                            game.InventoryPositionMainArea(k.X, k.Y),
                                            game.InventoryPositionMaterialSelector(game.ActiveMaterial));
                                    }
                                }
                            }
                        }
                        string[] sound = game.d_Data.CloneSound()[clonesource];
                        if (sound != null)            // && sound.Length > 0)
                        {
                            game.AudioPlay(sound[0]); //todo sound cycle
                        }
                    }
                }
                if (left || right)
                {
                    BlockPosSide tile = pick0;
                    int          newtileX;
                    int          newtileY;
                    int          newtileZ;
                    if (right)
                    {
                        newtileX = game.platform.FloatToInt(tile.Translated()[0]);
                        newtileY = game.platform.FloatToInt(tile.Translated()[1]);
                        newtileZ = game.platform.FloatToInt(tile.Translated()[2]);
                    }
                    else
                    {
                        newtileX = game.platform.FloatToInt(tile.Current()[0]);
                        newtileY = game.platform.FloatToInt(tile.Current()[1]);
                        newtileZ = game.platform.FloatToInt(tile.Current()[2]);
                    }
                    if (game.map.IsValidPos(newtileX, newtileZ, newtileY))
                    {
                        //Console.WriteLine(". newtile:" + newtile + " type: " + d_Map.GetBlock(newtileX, newtileZ, newtileY));
                        if (!(pick0.blockPos[0] == -1 &&
                              pick0.blockPos[1] == -1 &&
                              pick0.blockPos[2] == -1))
                        {
                            int blocktype;
                            if (left)
                            {
                                blocktype = game.map.GetBlock(newtileX, newtileZ, newtileY);
                            }
                            else
                            {
                                blocktype = ((game.BlockInHand() == null) ? 1 : game.BlockInHand().value);
                            }
                            if (left && blocktype == game.d_Data.BlockIdAdminium())
                            {
                                PickingEnd(left, right, middle, ispistol);
                                return;
                            }
                            string[] sound = left ? game.d_Data.BreakSound()[blocktype] : game.d_Data.BuildSound()[blocktype];
                            if (sound != null)            // && sound.Length > 0)
                            {
                                game.AudioPlay(sound[0]); //todo sound cycle
                            }
                        }
                        //normal attack
                        if (!right)
                        {
                            //attack
                            int posx = newtileX;
                            int posy = newtileZ;
                            int posz = newtileY;
                            game.currentAttackedBlock = Vector3IntRef.Create(posx, posy, posz);
                            if (!game.blockHealth.ContainsKey(posx, posy, posz))
                            {
                                game.blockHealth.Set(posx, posy, posz, game.GetCurrentBlockHealth(posx, posy, posz));
                            }
                            game.blockHealth.Set(posx, posy, posz, game.blockHealth.Get(posx, posy, posz) - game.WeaponAttackStrength());
                            float health = game.GetCurrentBlockHealth(posx, posy, posz);
                            if (health <= 0)
                            {
                                if (game.currentAttackedBlock != null)
                                {
                                    game.blockHealth.Remove(posx, posy, posz);
                                }
                                game.currentAttackedBlock = null;
                                OnPick(game, game.platform.FloatToInt(newtileX), game.platform.FloatToInt(newtileZ), game.platform.FloatToInt(newtileY),
                                       game.platform.FloatToInt(tile.Current()[0]), game.platform.FloatToInt(tile.Current()[2]), game.platform.FloatToInt(tile.Current()[1]),
                                       tile.collisionPos,
                                       right);
                            }
                            PickingEnd(left, right, middle, ispistol);
                            return;
                        }
                        if (!right)
                        {
                            game.particleEffectBlockBreak.StartParticleEffect(newtileX, newtileY, newtileZ);//must be before deletion - gets ground type.
                        }
                        if (!game.map.IsValidPos(newtileX, newtileZ, newtileY))
                        {
                            game.platform.ThrowException("");
                        }
                        OnPick(game, game.platform.FloatToInt(newtileX), game.platform.FloatToInt(newtileZ), game.platform.FloatToInt(newtileY),
                               game.platform.FloatToInt(tile.Current()[0]), game.platform.FloatToInt(tile.Current()[2]), game.platform.FloatToInt(tile.Current()[1]),
                               tile.collisionPos,
                               right);
                        //network.SendSetBlock(new Vector3((int)newtile.X, (int)newtile.Z, (int)newtile.Y),
                        //    right ? BlockSetMode.Create : BlockSetMode.Destroy, (byte)MaterialSlots[activematerial]);
                    }
                }
            }
        }
        PickingEnd(left, right, middle, ispistol);
    }
 public IntersectionExitNode(int x, int y, Intersection intersection, string name) : base(x, y, name)
 {
     this.intersection = intersection;
 }