Exemple #1
0
        public Tile(HeatPointList heatPoints, HeatmapSettings settings, Bounds bounds)
        {
            Bounds = bounds;

            Bounds heatMapBounds = new Bounds(bounds);
            heatMapBounds.TopLeftLat += settings.Size / 2 * this.DegreesPerPixelLat;
            heatMapBounds.TopLeftLng -= settings.Size / 2 * this.DegreesPerPixelLng;
            heatMapBounds.BottomRightLat -= settings.Size / 2 * this.DegreesPerPixelLat;
            heatMapBounds.BottomRightLng += settings.Size / 2 * this.DegreesPerPixelLng;

            HeatPointList pointsWithinBounds = new HeatPointList();
            foreach (HeatPoint hp in heatPoints)
            {
                if (heatMapBounds.Contains(hp)) pointsWithinBounds.Add(hp);
            }

            HeatMap = new HeatMap(pointsWithinBounds, settings, heatMapBounds);
        }
Exemple #2
0
    // Checks to see whether Bounds lilB are within Bounds bigB
    public static Vector3 BoundsInBoundsCheck(Bounds bigB, Bounds lilB, BoundsTest test = BoundsTest.onScreen)
    {
        // The behavior of this function is different based on the BoundsTest
        // that has been selected.
        // Get the center of lilB
        Vector3 pos = lilB.center;
        // Initialize the offset at [0,0,0]
        Vector3 off = Vector3.zero;

        switch (test)
        {
        // The center test determines what off (offset) would have to be applied
        // to lilB to move its center back inside bigB
        case BoundsTest.center:
            if (bigB.Contains(pos))
            {
                return(Vector3.zero);
            }
            if (pos.x > bigB.max.x)
            {
                off.x = pos.x - bigB.max.x;
            }
            else if (pos.x < bigB.min.x)
            {
                off.x = pos.x - bigB.min.x;
            }
            if (pos.y > bigB.max.y)
            {
                off.y = pos.y - bigB.max.y;
            }
            else if (pos.y < bigB.min.y)
            {
                off.y = pos.y - bigB.min.y;
            }
            if (pos.z > bigB.max.z)
            {
                off.z = pos.z - bigB.max.z;
            }
            else if (pos.z < bigB.min.z)
            {
                off.z = pos.z - bigB.min.z;
            }
            return(off);

        // The onScreen test determines what off would have to be applied to
        // keep all of lilB inside bigB
        case BoundsTest.onScreen:
            if (bigB.Contains(lilB.min) && bigB.Contains(lilB.max))
            {
                return(Vector3.zero);
            }
            if (lilB.max.x > bigB.max.x)
            {
                off.x = lilB.max.x - bigB.max.x;
            }
            else if (lilB.min.x < bigB.min.x)
            {
                off.x = lilB.min.x - bigB.min.x;
            }
            if (lilB.max.y > bigB.max.y)
            {
                off.y = lilB.max.y - bigB.max.y;
            }
            else if (lilB.min.y < bigB.min.y)
            {
                off.y = lilB.min.y - bigB.min.y;
            }
            if (lilB.max.z > bigB.max.z)
            {
                off.z = lilB.max.z - bigB.max.z;
            }
            else if (lilB.min.z < bigB.min.z)
            {
                off.z = lilB.min.z - bigB.min.z;
            }
            return(off);

        // The offScreen test determines what off would need to be applied to
        // move any tiny part of lilB inside of bigB
        case BoundsTest.offScreen:
            bool cMin = bigB.Contains(lilB.min);
            bool cMax = bigB.Contains(lilB.max);
            if (cMin || cMax)
            {
                return(Vector3.zero);
            }
            if (lilB.min.x > bigB.max.x)
            {
                off.x = lilB.min.x - bigB.max.x;
            }
            else if (lilB.max.x < bigB.min.x)
            {
                off.x = lilB.max.x - bigB.min.x;
            }
            if (lilB.min.y > bigB.max.y)
            {
                off.y = lilB.min.y - bigB.max.y;
            }
            else if (lilB.max.y < bigB.min.y)
            {
                off.y = lilB.max.y - bigB.min.y;
            }
            if (lilB.min.z > bigB.max.z)
            {
                off.z = lilB.min.z - bigB.max.z;
            }
            else if (lilB.max.z < bigB.min.z)
            {
                off.z = lilB.max.z - bigB.min.z;
            }
            return(off);
        }
        return(Vector3.zero);
    }
Exemple #3
0
        private void FindShieldedParts()
        {
            /*if (HighLogic.LoadedSceneIsEditor/* && FARAeroUtil.EditorAboutToAttach(false) &&
             *  !FARAeroUtil.CurEditorParts.Contains(part))
             *  return;*/

            ClearShieldedParts();
            UpdateShipPartsList();
            CalculateFairingBounds();

            Collider[] colliders = this.PartColliders;

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

                if (FARShieldedParts.Contains(p) || p == null || p == part || part.symmetryCounterparts.Contains(p))
                {
                    continue;
                }

                FARBaseAerodynamics     b = null;
                FARBasicDragModel       d = null;
                FARWingAerodynamicModel w = null;
                Vector3 relPos            = -part.transform.position;
                w = p.GetComponent <FARWingAerodynamicModel>();
                if ((object)w == null)
                {
                    d = p.GetComponent <FARBasicDragModel>();
                }
                if ((object)w == null && (object)d == null)
                {
                    continue;
                }
                //if (p.GetComponent<FARPayloadFairingModule>() != null)
                //    continue;
                if (w)
                {
                    b       = w as FARBaseAerodynamics;
                    relPos += w.WingCentroid();
                }
                else
                {
                    b       = d as FARBaseAerodynamics;
                    relPos += p.transform.TransformDirection(d.CenterOfDrag) + p.transform.position;       //No attach node shifting with this
                }

                relPos = this.part.transform.worldToLocalMatrix.MultiplyVector(relPos);

                Vector3 fairingCenter = fairingBounds.center;
                fairingCenter *= 0.5f;
                fairingCenter  = this.part.transform.localToWorldMatrix.MultiplyVector(fairingCenter);
                fairingCenter += this.part.transform.position;

                if (fairingBounds.Contains(relPos))
                {
                    Vector3 vecFromPToPFCenter;
                    Vector3 origin;
                    if (w)
                    {
                        origin = w.WingCentroid();
                    }
                    else
                    {
                        origin = p.transform.position;
                    }

                    vecFromPToPFCenter = fairingCenter - origin;

                    RaycastHit[] hits = Physics.RaycastAll(origin, vecFromPToPFCenter, vecFromPToPFCenter.magnitude, FARAeroUtil.RaycastMask);

                    bool outsideMesh = false;

                    for (int k = 0; k < hits.Length; k++)
                    {
                        if (colliders.Contains(hits[k].collider))
                        {
                            outsideMesh = true;
                            break;
                        }
                    }
                    if (outsideMesh)
                    {
                        continue;
                    }

                    FARShieldedParts.Add(p);
                    if (b)
                    {
                        b.ActivateShielding();
                        //print("Shielded: " + p.partInfo.title);
                    }
                    for (int k = 0; k < p.symmetryCounterparts.Count; k++)
                    {
                        Part q = p.symmetryCounterparts[k];

                        if (q == null)
                        {
                            continue;
                        }
                        FARShieldedParts.Add(q);
                        b = q.GetComponent <FARBaseAerodynamics>();
                        if (b)
                        {
                            b.ActivateShielding();
                            //print("Shielded: " + p.partInfo.title);
                        }
                    }
                }
            }
            partsShielded = FARShieldedParts.Count;
        }
    private void Update()
    {
        //if (!roadBounds.Contains(transform.position))   // 离开赛道GameOver
        //{// 无法形成多边形区域,因此即使离开赛道也会判定为没有离开
        //    Debug.Log("Game Over!");
        //    GetComponent<KartController>().enabled = false;
        //}
        // 每次更新判断一次赛车是否在赛道内
        insideRoad = false;
        roadBoard  = GameObject.FindGameObjectsWithTag("Road");
        foreach (GameObject road in roadBoard)
        {
            Bounds roadBounds = road.GetComponent <Collider2D>().bounds;
            if (roadBounds.Contains(transform.position))
            {
                insideRoad = true;
            }
        }
        if (!insideRoad)
        {
            Debug.Log("离开赛道!");
            GetComponent <KartController>().enabled = false;
            Time.timeScale = 0;
            fire.gameObject.SetActive(false);
        }

        if (insideRoad)
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                if (left || right)
                {
                    straight           = true;
                    left               = false;
                    right              = false;
                    transform.rotation = Quaternion.Euler(0, 0, 0);
                }
            }
            if (Input.GetKeyDown(KeyCode.A))
            {
                if (straight)
                {
                    left               = true;
                    straight           = false;
                    right              = false;
                    transform.rotation = Quaternion.Euler(0, 0, 90);
                }
            }
            if (Input.GetKeyDown(KeyCode.D))
            {
                if (straight)
                {
                    right              = true;
                    straight           = false;
                    left               = false;
                    transform.rotation = Quaternion.Euler(0, 0, -90);
                }
            }

            if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
            {     // 直行
                if (Input.GetKey(KeyCode.LeftShift))
                { // 加速
                    AccelUp();
                }
                else if (Input.GetKey(KeyCode.LeftControl))
                {// 减速
                    SlowUp();
                    Debug.Log("Slow");
                }
                else
                {// 起步
                    StartUp();
                }

                fire.gameObject.SetActive(true);
            }
            else
            {// 停车
                EndUp();

                fire.gameObject.SetActive(false);
            }

            if (straight)
            {
                rgb.velocity = new Vector2(0, velocity / velocityRejust);
            }
            if (left)
            {
                rgb.velocity = new Vector2(-velocity / velocityRejust, 0);
            }
            if (right)
            {
                rgb.velocity = new Vector2(velocity / velocityRejust, 0);
            }

            Debug.Log("当前速度为 " + velocity);
            Debug.Log("当前加速度为 " + acceleration);

            if (velocity > 0)
            {
                scorePoint++;
                score.text = "Score: " + scorePoint.ToString();
            }
        }
    }
Exemple #5
0
    // Checks to see if bounds lilb are within Bounds bigB
    public static Vector3 BoundsInBoundsCheck(Bounds bigB, Bounds lilB, BoundsTest test = BoundsTest.onScreen)
    {
        // behavior needs to be different depending on the test selected

        Vector3 pos = lilB.center;                      // use center for measurement
        Vector3 off = Vector3.zero;                     // offset is 0,0,0 to start

        switch (test)
        {
        // what is offset to move center of lilB back inside bigB
        case BoundsTest.center:
            // trivial case - we are already inside
            if (bigB.Contains(pos))
            {
                return(Vector3.zero);                    //no need to move
            }

            //otherwise adjust x,y,z components as needed
            if (pos.x > bigB.max.x)
            {
                off.x = pos.x - bigB.max.x;
            }
            else if (pos.x < bigB.min.x)
            {
                off.x = pos.x - bigB.min.x;
            }

            if (pos.y > bigB.max.y)
            {
                off.y = pos.y - bigB.max.y;
            }
            else if (pos.y < bigB.min.y)
            {
                off.y = pos.y - bigB.min.y;
            }

            if (pos.z > bigB.max.z)
            {
                off.z = pos.z - bigB.max.z;
            }
            else if (pos.z < bigB.min.z)
            {
                off.z = pos.z - bigB.min.z;
            }

            return(off);

        //-------------------------
        // what is the offset to keep ALL of lilB inside bigB
        case BoundsTest.onScreen:
            // trivial case - we are already inside
            if (bigB.Contains(lilB.max) && bigB.Contains(lilB.min))
            {
                return(Vector3.zero);                    //no need to move
            }

            if (lilB.max.x > bigB.max.x)
            {
                off.x = lilB.max.x - bigB.max.x;
            }
            else if (lilB.min.x < bigB.min.x)
            {
                off.x = lilB.min.x - bigB.min.x;
            }

            if (lilB.max.y > bigB.max.y)
            {
                off.y = lilB.max.y - bigB.max.y;
            }
            else if (lilB.min.y < bigB.min.y)
            {
                off.y = lilB.min.y - bigB.min.y;
            }

            if (lilB.max.z > bigB.max.z)
            {
                off.z = lilB.max.z - bigB.max.z;
            }
            else if (lilB.min.z < bigB.min.z)
            {
                off.z = lilB.min.z - bigB.min.z;
            }

            return(off);

        //-------------------------
        // what is the offset to keep ALL of lilB outside of bigB
        case BoundsTest.offScreen:
            bool cMin = bigB.Contains(lilB.min);
            bool cMax = bigB.Contains(lilB.max);

            if (cMin || cMax)
            {
                return(Vector3.zero);
            }


            if (lilB.min.x > bigB.max.x)
            {
                off.x = lilB.min.x - bigB.max.x;
            }
            else if (lilB.max.x < bigB.min.x)
            {
                off.x = lilB.max.x - bigB.min.x;
            }

            if (lilB.min.y > bigB.max.y)
            {
                off.y = lilB.min.y - bigB.max.y;
            }
            else if (lilB.max.y < bigB.min.y)
            {
                off.y = lilB.max.y - bigB.min.y;
            }

            if (lilB.min.z > bigB.max.z)
            {
                off.z = lilB.min.z - bigB.max.z;
            }
            else if (lilB.max.z < bigB.min.z)
            {
                off.z = lilB.max.z - bigB.min.z;
            }

            return(off);
        }                     // end switch BoundsTest

        return(Vector3.zero); // if we get here something went wrong
    }                         // end BoundsInBoundsCheck
Exemple #6
0
        MouseState ProcessMouse(MouseState mouse)
        {
            // Handle mouse buttons
            for (MouseButton i = 0; i < MouseButton.LastButton; i++)
            {
                if (mouse[i] && !previous_mouse[i])
                {
                    OnMouseDown(i);
                }

                if (!mouse[i] && previous_mouse[i])
                {
                    OnMouseUp(i);
                }
            }

            // Handle mouse movement
            {
                int x = mouse.X;
                int y = mouse.Y;

                // Make sure the mouse cannot leave the GameWindow when captured
                if (!CursorVisible)
                {
                    x = MathHelper.Clamp(mouse.X, Bounds.Left, Bounds.Right - 1);
                    y = MathHelper.Clamp(mouse.Y, Bounds.Top, Bounds.Bottom - 1);
                    if (x != mouse.X || y != mouse.Y)
                    {
                        Mouse.SetPosition(x, y);
                    }
                }

                if (x != previous_mouse.X || y != previous_mouse.Y)
                {
                    OnMouseMove(x, y);
                }
            }

            // Handle mouse scroll
            if (mouse.Scroll != previous_mouse.Scroll)
            {
                float dx = mouse.Scroll.X - previous_mouse.Scroll.X;
                float dy = mouse.Scroll.Y - previous_mouse.Scroll.Y;
                OnMouseWheel(dx, dy);
            }

            // Handle mouse focus
            // Note: focus follows mouse. Literally.
            bool cursor_in = Bounds.Contains(new Point(mouse.X, mouse.Y));

            if (!cursor_in && Focused)
            {
                OnMouseLeave(EventArgs.Empty);
                SetFocus(false);
            }
            else if (cursor_in && !Focused)
            {
                OnMouseEnter(EventArgs.Empty);
                SetFocus(true);
            }

            return(mouse);
        }
Exemple #7
0
 protected virtual bool TestBounds(Vector2 pos)
 {
     return(Bounds.Contains(pos));
 }
        public void BoundsCanNotContainAPoint()
        {
            b = new Bounds(Vector3.zero, Vector3.one);

            Assert.That(!b.Contains(new Vector3(2, 0, 0)));
        }
Exemple #9
0
    bool IsWithinBounds(Camera camera, Bounds viewportBounds, Vector3 position)
    {
        Vector3 viewportPoint = camera.WorldToViewportPoint(position);

        return(viewportBounds.Contains(viewportPoint));
    }
Exemple #10
0
    private IEnumerator DoMove(Vector3 direction)
    {
        if (isMoving)
        {
            yield break;
        }

        Vector3 startPos = transform.position;
        Vector3 goalPos  = startPos + direction * distancePerUnit;
        float   moveTime = (goalPos - startPos).magnitude / moveSpeed;

        Bounds selfBounds  = new Bounds();
        bool   initialized = false;

        foreach (Collider c in GetComponentsInChildren <Collider>())
        {
            if (initialized)
            {
                selfBounds.Encapsulate(c.bounds);
            }
            else
            {
                selfBounds  = c.bounds;
                initialized = true;
            }
        }
        selfBounds.center += direction * distancePerUnit;
        Bounds  areaBounds     = area.bounds;
        Vector3 minPoint       = new Vector3(selfBounds.min.x, areaBounds.center.y, selfBounds.min.z);
        Vector3 maxPoint       = new Vector3(selfBounds.max.x, areaBounds.center.y, selfBounds.max.z);
        bool    fullyContained = areaBounds.Contains(minPoint) && areaBounds.Contains(maxPoint);

        Debug.Log(areaBounds);
        if (!fullyContained)
        {
            yield break;
        }

        isMoving = true;

        audioSource.PlayOneShot(startMove);

        OnMove.Invoke();

        PushBody.FreezeAll();

        float progress = 0.0f;

        while (progress < 1.0f)
        {
            float x = Mathf.SmoothStep(startPos.x, goalPos.x, progress);
            float y = Mathf.SmoothStep(startPos.y, goalPos.y, progress);
            float z = Mathf.SmoothStep(startPos.z, goalPos.z, progress);
            _rb.MovePosition(new Vector3(x, y, z));
            progress += Time.deltaTime / moveTime;
            yield return(null);
        }

        isMoving = false;

        audioSource.PlayOneShot(endMove);

        PushBody.ThawAll();

        historianManager.Record();
    }
Exemple #11
0
        //検証メソッド
        public override Result Validate()
        {
            //初期化
            base.Validate();
            Bounds outBounds = new Bounds(new Vector3(0, 2.5f, -2.0f), new Vector3(4.0f, 5.0f, 4.0f));

            //検証ロジック

            Scene scene = SceneManager.GetSceneByPath(AssetDatabase.GUIDToAssetPath(options.sceneGuid));

            if (!scene.IsValid())
            {
                AddResultLog("無効なシーンです");
                return(SetResult(Result.FAIL));
            }
            bool   dirtFlag        = false;
            Bounds torelanceBounds = new Bounds(new Vector3(0, 0, 0), new Vector3(0.0001f, 0.0001f, 0.0001f));
            Bounds torelanceScale  = new Bounds(new Vector3(1.0f, 1.0f, 1.0f), new Vector3(0.0001f, 0.0001f, 0.0001f));

            // ルートオブジェクトの取得
            GameObject[] rootObjects = scene.GetRootGameObjects();
            foreach (var obj in rootObjects)
            {
                if (obj.name == options.baseFolder.name)
                {
                    if (!torelanceBounds.Contains(obj.transform.position))
                    {
                        AddResultLog(string.Format("ルートオブジェクトの位置は(0, 0, 0)にしてください。現在は(x, y, z) = ({0}, {1}, {2})となっています。",
                                                   obj.transform.position.x, obj.transform.position.y, obj.transform.position.z));
                        dirtFlag = true;
                    }
                    if (!torelanceBounds.Contains(obj.transform.rotation.eulerAngles))
                    {
                        AddResultLog(string.Format("ルートオブジェクトの回転は(0, 0, 0)にしてください。現在は(x, y, z) = ({0}, {1}, {2})となっています。",
                                                   obj.transform.rotation.eulerAngles.x, obj.transform.rotation.eulerAngles.y, obj.transform.rotation.eulerAngles.z));
                        dirtFlag = true;
                    }
                    if (!torelanceScale.Contains(obj.transform.localScale))
                    {
                        AddResultLog(string.Format("ルートオブジェクトのスケールは(0, 0, 0)にしてください。現在は(x, y, z) = ({0}, {1}, {2})となっています。",
                                                   obj.transform.localScale.x, obj.transform.localScale.y, obj.transform.localScale.z));
                        dirtFlag = true;
                    }
                    foreach (Transform child_tr in obj.transform)
                    {
                        var child = child_tr.gameObject;
                        if (child.name.ToLower() == "dynamic" || child.name.ToLower() == "static")
                        {
                            if (!torelanceBounds.Contains(child.transform.position))
                            {
                                AddResultLog(string.Format("ルート直下のオブジェクト{0}の位置は(0, 0, 0)にしてください。現在は(x, y, z) = ({1}, {2}, {3})となっています。",
                                                           child.name, child.transform.position.x, child.transform.position.y, child.transform.position.z));
                                dirtFlag = true;
                            }
                            if (!torelanceBounds.Contains(child.transform.rotation.eulerAngles))
                            {
                                AddResultLog(string.Format("ルート直下のオブジェクト{0}の回転は(0, 0, 0)にしてください。現在は(x, y, z) = ({1}, {2}, {3})となっています。",
                                                           child.name, child.transform.rotation.eulerAngles.x, child.transform.rotation.eulerAngles.y, child.transform.rotation.eulerAngles.z));
                                dirtFlag = true;
                            }
                            if (!torelanceScale.Contains(child.transform.localScale))
                            {
                                AddResultLog(string.Format("ルート直下のオブジェクト{0}のスケールは(0, 0, 0)にしてください。現在は(x, y, z) = ({1}, {2}, {3})となっています。",
                                                           child.name, child.transform.localScale.x, child.transform.localScale.y, child.transform.localScale.z));
                                dirtFlag = true;
                            }
                        }
                    }
                }
            }

            //検証結果を設定して返す(正常:Result.SUCESS 異常:Result.FAIL)
            return(SetResult(dirtFlag ? Result.FAIL : Result.SUCCESS));
        }
Exemple #12
0
        public void Update()
        {
            var ml = Game.InputControls.MouseLocation;
            if (!ml.HasValue)
                return;

            var size = Measure();
            var pos = new Vector2(Game.ViewportWidth - size.X, Game.ViewportHeight - size.Y) * new Vector2(0.5f, 0.5f);

            for (int i = 0; i < Items.Count; i++) {
                var item = Items[i];
                var itemSize = item.Measure(Game);
                var itemBounds = new Bounds(
                    pos, pos + itemSize
                );

                if (itemBounds.Contains(ml.Value))
                    SelectedIndex = i;

                pos.Y += itemSize.Y;
            }
        }
        public void IfAPointIntersectsTheBoundsItWillBeContained()
        {
            b = new Bounds(Vector3.zero, Vector3.one);

            Assert.That(b.Contains(new Vector3(0.5f, 0.5f, 0.5f)));
        }
Exemple #14
0
        public unsafe void Execute(int i)
        {
            float3 currentPos = Positions[i].Value;
            float3 currentDir = VehicleData[i].Forward;

            int laneCount, nextLane;

            //spawn new pos
            if (!BoundingBox.Contains(currentPos))
            {
                int nextSeg = rdGen.NextInt(0, RoadSegments.Length);

                float3     nextForward = RoadSegments[nextSeg].Direction;
                quaternion newRot      = quaternion.LookRotation(nextForward, new float3()
                {
                    x = 0, y = 1, z = 0
                });

                laneCount = RoadSegments[nextSeg].LaneNumber;
                nextLane  = 0;
                float laneOffset = (nextLane + 0.5f) * RoadSegments[nextSeg].LaneWidth;
                if (RoadSegments[nextSeg].IsOneWay == 1)
                {
                    laneOffset -= (laneCount / 2.0f) * RoadSegments[nextSeg].LaneWidth;
                }

                float nextPerct = 0;

                float3 nextPos = (1.0f - nextPerct) * RoadNodes[RoadSegments[nextSeg].StartNodeId].Position +
                                 (nextPerct) * RoadNodes[RoadSegments[nextSeg].EndNodeId].Position;
                nextPos += laneOffset * RoadSegments[nextSeg].RightDirection;

                VehicleData[i] = new VehicleData(
                    VehicleData[i].Id,
                    nextSeg,
                    VehicleData[i].Speed,
                    nextForward,
                    nextPerct,
                    1.0f,
                    nextPos,
                    nextLane,
                    50.0f
                    );

                BVHAABB newAABB = AABB[i];
                newAABB.Max += (nextPos - currentPos);
                newAABB.Min += (nextPos - currentPos);
                AABB[i]      = newAABB;

                Positions[i] = new Position()
                {
                    Value = nextPos
                };
                Rotations[i] = new Rotation()
                {
                    Value = newRot
                };
                return;
            }

            #region Redlight infront
            int    currentSeg                    = VehicleData[i].SegId;
            int    nextCrossing                  = VehicleData[i].Direction > 0.0f ? RoadSegments[currentSeg].EndNodeId : RoadSegments[currentSeg].StartNodeId;
            float3 nextCrossingPos               = RoadNodes[nextCrossing].Position;
            float  distanceToCrossing            = math.distance(currentPos, nextCrossingPos);
            int2   nextCrossingGreenlightConnect =
                RoadNodes[nextCrossing].ConnectionSegIds[RoadNodes[nextCrossing].ActiveConnection];
            if (currentSeg != nextCrossingGreenlightConnect.x && currentSeg != nextCrossingGreenlightConnect.y &&
                distanceToCrossing < 20.0f)
            {
                return;
            }
            #endregion

            #region SpeedVariation
            float prevDistanceAhead = VehicleData[i].HitDistAhead;
            float newDistanceAhead  = HitResult[i].FrontHitDistance;
            float distAheadDiff     = prevDistanceAhead - newDistanceAhead;
            int   hitResult         = HitResult[i].HitResultPacked;
            float maxSpeed          = RoadSegments[VehicleData[i].SegId].MaxSpeed;
            float newSpeed          = VehicleData[i].Speed;
            if (hitResult == 0 && newSpeed < maxSpeed)
            {
                newSpeed += 0.5f;
            }
            else if ((hitResult & 0x1) == 1 && (distAheadDiff > 0))
            {
                newSpeed -= ((distAheadDiff) / 20.0f);
            }

            if (newDistanceAhead < 5.0f)
            {
                newSpeed = 0.0f;
            }

            newSpeed = newSpeed > maxSpeed ? maxSpeed : newSpeed;
            newSpeed = newSpeed < 0 ? 0 : newSpeed;
            #endregion

            float stepLength  = newSpeed * DeltaTime;
            float segLength   = RoadSegments[VehicleData[i].SegId].Length;
            float stepPerc    = stepLength / segLength;
            float nextPosPerc = VehicleData[i].CurrentSegPos + stepPerc * VehicleData[i].Direction;


            #region switchLane

            laneCount = RoadSegments[VehicleData[i].SegId].LaneNumber;
            int currentLane = VehicleData[i].Lane;
            int laneSwitch  = rdGen.NextInt(-10, 10);
            laneSwitch = laneSwitch / 10;
            if (currentLane == 0 && laneSwitch == -1)
            {
                laneSwitch = 0;
            }
            if (currentLane == (laneCount - 1) && laneSwitch == 1)
            {
                laneSwitch = 0;
            }
            nextLane = VehicleData[i].Lane + laneSwitch;
            #endregion

            //great, still in this seg
            if (nextPosPerc < 1.0f && nextPosPerc > 0.0f)
            {
                //step forward
                float3 nextPos = currentPos + currentDir * stepLength;
                //offset lane
                nextPos += laneSwitch * VehicleData[i].Direction * RoadSegments[VehicleData[i].SegId].LaneWidth *
                           RoadSegments[VehicleData[i].SegId].RightDirection;
                VehicleData[i] = new VehicleData(
                    VehicleData[i].Id,
                    VehicleData[i].SegId,
                    newSpeed,
                    VehicleData[i].Forward,
                    nextPosPerc,
                    VehicleData[i].Direction,
                    nextPos,
                    nextLane,
                    newDistanceAhead
                    );

                BVHAABB newAABB = AABB[i];
                newAABB.Max += currentDir * stepLength;
                newAABB.Min += currentDir * stepLength;
                AABB[i]      = newAABB;

                Positions[i] = new Position()
                {
                    Value = nextPos
                };
            }
            //reach end node, find next seg
            else
            {
                //find next available segment
                int *_availableSeg = (int *)UnsafeUtility.Malloc(
                    5 * sizeof(int), sizeof(int), Allocator.Temp);
                int availableSegCount = 0;
                for (int k = 0; k < 3; k++)
                {
                    int seg1 = RoadNodes[nextCrossing].ConnectionSegIds[k].x;
                    int seg2 = RoadNodes[nextCrossing].ConnectionSegIds[k].y;
                    if (seg1 != -1 && seg1 != currentSeg && //not current seg, and next seg not one-way
                        !(RoadSegments[seg1].EndNodeId == nextCrossing && RoadSegments[seg1].IsOneWay == 1))
                    {
                        _availableSeg[availableSegCount++] = seg1;
                    }
                    if (seg2 != -1 && seg2 != currentSeg && //not current seg, and next seg not one-way
                        !(RoadSegments[seg2].EndNodeId == nextCrossing && RoadSegments[seg2].IsOneWay == 1))
                    {
                        _availableSeg[availableSegCount++] = seg2;
                    }
                }

                int   nextSeg = currentSeg;
                float dir     = 1.0f;
                if (availableSegCount > 0)//luckily we can proceed
                {
                    int selectSegId = rdGen.NextInt(0, availableSegCount);
                    nextSeg = _availableSeg[selectSegId];
                    dir     = RoadSegments[nextSeg].StartNodeId == nextCrossing ? 1.0f : -1.0f;
                }
                else//to the end, spawn a new pos
                {
                    nextSeg = rdGen.NextInt(0, RoadSegments.Length);
                }

                float3     nextForward = RoadSegments[nextSeg].Direction * dir;
                quaternion newRot      = quaternion.LookRotation(nextForward, new float3()
                {
                    x = 0, y = 1, z = 0
                });

                laneCount = RoadSegments[nextSeg].LaneNumber;
                nextLane  = nextLane < laneCount ? nextLane : laneCount - 1;
                float laneOffset = (nextLane + 0.5f) * RoadSegments[nextSeg].LaneWidth;
                if (RoadSegments[nextSeg].IsOneWay == 1)
                {
                    laneOffset -= (laneCount / 2.0f) * RoadSegments[nextSeg].LaneWidth;
                }

                float nextPerct = dir > 0.0f
                    ? (nextPosPerc > 0.0f ? nextPosPerc - 1.0f : -nextPosPerc)
                    : (nextPosPerc > 0.0f ? 2.0f - nextPosPerc : nextPosPerc + 1.0f);

                float3 nextPos = (1.0f - nextPerct) * RoadNodes[RoadSegments[nextSeg].StartNodeId].Position +
                                 (nextPerct) * RoadNodes[RoadSegments[nextSeg].EndNodeId].Position;
                nextPos += laneOffset * dir * RoadSegments[nextSeg].RightDirection;

                VehicleData[i] = new VehicleData(
                    VehicleData[i].Id,
                    nextSeg,
                    newSpeed,
                    nextForward,
                    nextPerct,
                    dir,
                    nextPos,
                    nextLane,
                    newDistanceAhead
                    );

                BVHAABB newAABB = AABB[i];
                newAABB.Max += (nextPos - currentPos);
                newAABB.Min += (nextPos - currentPos);
                AABB[i]      = newAABB;

                Positions[i] = new Position()
                {
                    Value = nextPos
                };
                Rotations[i] = new Rotation()
                {
                    Value = newRot
                };

                UnsafeUtility.Free(_availableSeg, Allocator.Temp);
                _availableSeg = null;
            }
        }
Exemple #15
0
        private void ConnectRegions()
        {
            // Find all of the tiles that can connect two (or more) regions.
            var connectorRegions = new Dictionary <Vector, HashSet <int> >();

            foreach (var pos in Bounds.Deflate())
            {
                // Can't already be part of a region.
                if (GetTile(pos) != TileType.Wall)
                {
                    continue;
                }

                var regions    = new HashSet <int>();
                var neighbours = Direction.Cardinal
                                 .Select(dir => pos + dir)
                                 .Where(p => Bounds.Contains(p));

                foreach (var neighbour in neighbours)
                {
                    regions.Add(regionMap[neighbour.X, neighbour.Y]);
                }
                if (regions.Count < 2)
                {
                    continue;
                }
                connectorRegions[pos] = regions;
            }

            var connectors = connectorRegions.Keys.ToList();

            // Keep track of which regions have been merged. This maps an original
            // region index to the one it has been merged to.
            var merged      = new Dictionary <int, int>();
            var openRegions = new HashSet <int>();

            for (var i = 0; i <= currentRegion; i++)
            {
                merged[i] = i;
                openRegions.Add(i);
            }

            // Keep connecting regions until we're down to one.
            while (openRegions.Count > 1)
            {
                var connector = connectors.PickRandom();
                if (connector == null)
                {
                    break;
                }

                // Carve the connection.
                AddJunction(connector);

                // Merge the connected regions. We'll pick one region (arbitrarily) and
                // map all of the other regions to its index.
                var mRegions = connectorRegions[connector]
                               .Select(region => merged[region]).ToList();
                var dest    = mRegions.First();
                var sources = mRegions.Skip(1).ToList();

                // Merge all of the affected regions. We have to look at *all* of the
                // regions because other regions may have previously been merged with
                // some of the ones we're merging now.
                for (var i = 0; i <= currentRegion; i++)
                {
                    if (sources.Contains(merged[i]))
                    {
                        merged[i] = dest;
                    }
                }

                // The sources are no longer in use.
                openRegions.RemoveWhere(i => sources.Contains(i));

                // Remove any connectors that aren't needed anymore.
                connectors.RemoveAll(pos => {
                    // Don't allow connectors right next to each other.
                    if ((connector - pos).Distance < 2)
                    {
                        return(true);
                    }

                    // If the connector no long spans different regions, we don't need it.
                    var regions = new HashSet <int>(connectorRegions[pos].Select(region => merged[region]));
                    if (regions.Count > 1)
                    {
                        return(false);
                    }

                    // This connecter isn't needed, but connect it occasionally so that the
                    // dungeon isn't singly-connected.
                    if (Randomizer.ChanceIn(extraConnectorChance))
                    {
                        AddJunction(pos);
                    }

                    return(true);
                });
            }
        }
 public bool Contains(int offsetX, int offsetY)
 {
     return(bounds.Contains(offsetX, offsetY));
 }
        /// <inheritdoc />
        protected override void OnLeftMouseButtonUp()
        {
            // Skip if was controlling mouse or mouse is not over the area
            if (_prevInput.IsControllingMouse || !Bounds.Contains(ref _viewMousePos))
            {
                return;
            }

            if (TransformGizmo.IsActive)
            {
                // Ensure player is not moving objects
                if (TransformGizmo.ActiveAxis != TransformGizmo.Axis.None)
                {
                    return;
                }
            }
            else
            {
                // For now just pick objects in transform gizmo mode
                return;
            }

            // Get mouse ray and try to hit any object
            var   ray             = MouseRay;
            float closest         = float.MaxValue;
            bool  selectColliders = (Task.Flags & ViewFlags.PhysicsDebug) == ViewFlags.PhysicsDebug;

            SceneGraphNode.RayCastData.FlagTypes rayCastFlags = SceneGraphNode.RayCastData.FlagTypes.None;
            if (!selectColliders)
            {
                rayCastFlags |= SceneGraphNode.RayCastData.FlagTypes.SkipColliders;
            }
            var hit = Editor.Instance.Scene.Root.RayCast(ref ray, ref closest, rayCastFlags);

            // Update selection
            var sceneEditing = Editor.Instance.SceneEditing;

            if (hit != null)
            {
                // For child actor nodes (mesh, link or sth) we need to select it's owning actor node first or any other child node (but not a child actor)
                if (hit is ActorChildNode actorChildNode)
                {
                    var  parentNode         = actorChildNode.ParentNode;
                    bool canChildBeSelected = sceneEditing.Selection.Contains(parentNode);
                    if (!canChildBeSelected)
                    {
                        for (int i = 0; i < parentNode.ChildNodes.Count; i++)
                        {
                            if (sceneEditing.Selection.Contains(parentNode.ChildNodes[i]))
                            {
                                canChildBeSelected = true;
                                break;
                            }
                        }
                    }

                    if (!canChildBeSelected)
                    {
                        // Select parent
                        hit = parentNode;
                    }
                }

                bool addRemove  = Root.GetKey(Keys.Control);
                bool isSelected = sceneEditing.Selection.Contains(hit);

                if (addRemove)
                {
                    if (isSelected)
                    {
                        sceneEditing.Deselect(hit);
                    }
                    else
                    {
                        sceneEditing.Select(hit, true);
                    }
                }
                else
                {
                    sceneEditing.Select(hit);
                }
            }
            else
            {
                sceneEditing.Deselect();
            }

            // Keep focus
            Focus();

            base.OnLeftMouseButtonUp();
        }
 public virtual bool FillContains(Point point) => Bounds.Contains(point);
Exemple #19
0
 public bool CheckPositionIsInsidePaddle(Vector2 position)
 {
     return(_bounds.Contains(position));
 }
Exemple #20
0
    public static Vector3 BoundsInBoundsCheck(Bounds bigB, Bounds lilB, BoundsTest test = BoundsTest.onScreen)
    {
        // Центр lilB
        Vector3 pos = lilB.center;

        // Создаём смещение
        Vector3 off = Vector3.zero;

        switch (test)
        {
        case BoundsTest.center:
            if (bigB.Contains(pos))
            {
                return(Vector3.zero);
            }
            if (pos.x > bigB.max.x)
            {
                off.x = pos.x - bigB.max.x;
            }
            else if (pos.x < bigB.min.x)
            {
                off.x = pos.x - bigB.min.x;
            }
            if (pos.y > bigB.max.y)
            {
                off.y = pos.y - bigB.max.y;
            }
            else if (pos.y < bigB.min.y)
            {
                off.y = pos.y - bigB.min.y;
            }
            if (pos.z > bigB.max.z)
            {
                off.z = pos.z - bigB.max.z;
            }
            else if (pos.z < bigB.min.z)
            {
                off.z = pos.z - bigB.min.z;
            }
            return(off);

        // Что нужно сделать, чтобы держать lilB внутри bigB
        case BoundsTest.onScreen:
            if (bigB.Contains(lilB.min) && bigB.Contains(lilB.max))
            {
                return(Vector3.zero);
            }
            if (lilB.max.x > bigB.max.x)
            {
                off.x = lilB.max.x - bigB.max.x;
            }
            else if (lilB.min.x < bigB.min.x)
            {
                off.x = lilB.min.x - bigB.min.x;
            }
            if (lilB.max.y > bigB.max.y)
            {
                off.y = lilB.max.y - bigB.max.y;
            }
            else if (lilB.min.y < bigB.min.y)
            {
                off.y = lilB.min.y - bigB.min.y;
            }
            if (lilB.max.z > bigB.max.z)
            {
                off.z = lilB.max.z - bigB.max.z;
            }
            else if (lilB.min.z < bigB.min.z)
            {
                off.z = lilB.min.z - bigB.min.z;
            }
            return(off);

        case BoundsTest.offScreen:
            bool cMin = bigB.Contains(lilB.min);
            bool cMax = bigB.Contains(lilB.max);
            if (cMin || cMax)
            {
                return(Vector3.zero);
            }
            if (lilB.min.x > bigB.max.x)
            {
                off.x = lilB.min.x - bigB.max.x;
            }
            else if (lilB.max.x < bigB.min.x)
            {
                off.x = lilB.max.x - bigB.min.x;
            }
            if (lilB.min.y > bigB.max.y)
            {
                off.y = lilB.min.y - bigB.max.y;
            }
            else if (lilB.max.y < bigB.min.y)
            {
                off.y = lilB.max.y - bigB.min.y;
            }
            if (lilB.min.z > bigB.max.z)
            {
                off.z = lilB.min.z - bigB.max.z;
            }
            else if (lilB.max.z < bigB.min.z)
            {
                off.z = lilB.max.z - bigB.min.z;
            }
            return(off);

        default:
            return(Vector3.zero);
        }
    }
Exemple #21
0
 public virtual bool Contains(PointF p)
 {
     return(Bounds.Contains(p));
 }
Exemple #22
0
    // Update is called once per frame
    void Update()
    {
        hasPrimary = primaryObject;            //If there is a primary object, hasPrimary is true

        if (primaryObject != null)             //Is there a primary object?
        {
            ObjectPanel.alpha          = 1;    //Sets the unit panel to be visible
            ObjectPanel.blocksRaycasts = true; //Sets the unit panel to block raycasts
            ObjectPanel.interactable   = true; //Sets the unit panel to be interactable
        }
        else
        {
            ObjectPanel.alpha          = 0;     //Sets the unit panel to be invisible
            ObjectPanel.blocksRaycasts = false; //Sets the unit panel to not block raycasts
            ObjectPanel.interactable   = false; //Sets the unit panel to be not interactable
        }

        //Did the player left click while being able to click the ground and while the move button is not active?
        if (Input.GetMouseButtonDown(0) && canClickGround && !AL.moveButtonActive)
        {
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            //Did the raycast hit something?
            if (Physics.Raycast(ray, out hit))
            {
                ObjectInfo OI = hit.collider.GetComponent <ObjectInfo>();

                //Is there anything currently selected?
                if (OI != null)
                {
                    //Is the player holding left shift?
                    if (Input.GetKey(KeyCode.LeftShift))
                    {
                        UpdateSelection(OI, !OI.isSelected); //Add the clicked object to selected units
                    }
                    else
                    {
                        //Replace selected units with the clicked object
                        ClearSelected();
                        UpdateSelection(OI, true);
                    }
                }
            }

            startPos    = Input.mousePosition; //Set the start position
            isSelecting = true;                //The player is now selecting
        }

        //Did the player release the left mouse button?
        if (Input.GetMouseButtonUp(0))
        {
            isSelecting = false;
        }

        //Toggle the selection box based on if the player is selecting
        selectionBox.gameObject.SetActive(isSelecting);

        //Is the player selecting?
        if (isSelecting)
        {
            //Define new bounds based on current selection box
            Bounds bounds = new Bounds();
            bounds.center = Vector3.Lerp(startPos, Input.mousePosition, 0.5f);
            bounds.size   = new Vector3(Mathf.Abs(startPos.x - Input.mousePosition.x), Mathf.Abs(startPos.y - Input.mousePosition.y), 0);

            //Adjust the selection bos image to match the bounds
            RT.position  = bounds.center;
            RT.sizeDelta = canvas.transform.InverseTransformVector(bounds.size);

            //For each selectable object
            foreach (ObjectInfo selectable in selectedObjects)
            {
                //If it's a unit owned by the player
                if (selectable.isUnit && selectable.isPlayerObject)
                {
                    Vector3 screenPos = Camera.main.WorldToScreenPoint(selectable.transform.position); //Get the unit's position on the screen
                    screenPos.z = 0;                                                                   //Set the screen position z to 0
                    UpdateSelection(selectable, (bounds.Contains(screenPos)));                         //Update selection based on if the selected object is inside selection box bounds
                }
            }
        }
    }
Exemple #23
0
        public static Bounds BoundsHandle(Bounds bounds, Quaternion rotation, CapFunction sideCapFunction, CapFunction pointCapFunction, Vector3?snappingSteps = null)
        {
            var  hotControl   = GUIUtility.hotControl;
            bool isControlHot = false;

            for (int i = 0; i < s_BoundsControlIds.Length; i++)
            {
                s_BoundsControlIds[i] = GUIUtility.GetControlID(s_BoundsHash, FocusType.Keyboard);
                s_BoundsAxisHot[i]    = s_BoundsControlIds[i] == hotControl;
                isControlHot          = isControlHot || s_BoundsAxisHot[i];
            }

            s_BoundsSlideDirs[0] = rotation * Vector3.right;
            s_BoundsSlideDirs[1] = rotation * Vector3.up;
            s_BoundsSlideDirs[2] = rotation * Vector3.forward;

            var min    = bounds.min;
            var max    = bounds.max;
            var center = bounds.center;

            s_BoundsValues[0] = min.x;
            s_BoundsValues[1] = min.y;
            s_BoundsValues[2] = min.z;

            s_BoundsValues[3] = max.x;
            s_BoundsValues[4] = max.y;
            s_BoundsValues[5] = max.z;


            s_BoundsVertices[0] = rotation * new Vector3(s_BoundsValues[0], s_BoundsValues[1], s_BoundsValues[2]);
            s_BoundsVertices[1] = rotation * new Vector3(s_BoundsValues[3], s_BoundsValues[1], s_BoundsValues[2]);
            s_BoundsVertices[2] = rotation * new Vector3(s_BoundsValues[3], s_BoundsValues[4], s_BoundsValues[2]);
            s_BoundsVertices[3] = rotation * new Vector3(s_BoundsValues[0], s_BoundsValues[4], s_BoundsValues[2]);

            s_BoundsVertices[4] = rotation * new Vector3(s_BoundsValues[0], s_BoundsValues[1], s_BoundsValues[5]);
            s_BoundsVertices[5] = rotation * new Vector3(s_BoundsValues[3], s_BoundsValues[1], s_BoundsValues[5]);
            s_BoundsVertices[6] = rotation * new Vector3(s_BoundsValues[3], s_BoundsValues[4], s_BoundsValues[5]);
            s_BoundsVertices[7] = rotation * new Vector3(s_BoundsValues[0], s_BoundsValues[4], s_BoundsValues[5]);


            s_BoundsSidePoint[0] = rotation * new Vector3(s_BoundsValues[0], center.y, center.z);
            s_BoundsSidePoint[1] = rotation * new Vector3(center.x, s_BoundsValues[1], center.z);
            s_BoundsSidePoint[2] = rotation * new Vector3(center.x, center.y, s_BoundsValues[2]);
            s_BoundsSidePoint[3] = rotation * new Vector3(s_BoundsValues[3], center.y, center.z);
            s_BoundsSidePoint[4] = rotation * new Vector3(center.x, s_BoundsValues[4], center.z);
            s_BoundsSidePoint[5] = rotation * new Vector3(center.x, center.y, s_BoundsValues[5]);

            // TODO: add handles in the corners of each quad on the bounds, with an offset from the vertex, to drag from there


            using (new SceneHandles.DrawingScope())
            { var prevDisabled = SceneHandles.disabled;

              var isStatic = (!Tools.hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects));


              for (int i = 0; i < s_BoundsAxisDisabled.Length; i++)
              {
                  s_BoundsAxisDisabled[i] = isStatic || prevDisabled || Snapping.AxisLocking[i % 3] || (isControlHot && !s_BoundsAxisHot[i]);
              }

              var camera               = Camera.current;
              var cameraLocalPos       = SceneHandles.inverseMatrix.MultiplyPoint(camera.transform.position);
              var cameraLocalForward   = SceneHandles.inverseMatrix.MultiplyVector(camera.transform.forward);
              var isCameraInsideBox    = bounds.Contains(cameraLocalPos);
              var isCameraOrthographic = camera.orthographic;


              var boundsColor    = SceneHandles.yAxisColor;
              var backfacedColor = new Color(boundsColor.r, boundsColor.g, boundsColor.b, boundsColor.a * SceneHandles.backfaceAlphaMultiplier);


              var prevGUIchanged = GUI.changed;

              bool haveChanged = false;

              var selectedAxes = Axes.None;

              // all sides of bounds
              int currentFocusControl = SceneHandleUtility.focusControl;
              for (int i = 0; i < s_BoundsValues.Length; i++)
              {
                  var id = s_BoundsControlIds[i];


                  GUI.changed = false;
                  var localPoint = s_BoundsSidePoint[i];
                  var handleSize = UnityEditor.HandleUtility.GetHandleSize(localPoint);
                  var pointSize  = handleSize * kPointScale;
                  var direction  = s_BoundsSlideDirs[i % 3];
                  var normal     = (i < 3) ? -direction : direction;
                  normal.x *= (bounds.size.x < 0) ? -1 : 1;
                  normal.y *= (bounds.size.y < 0) ? -1 : 1;
                  normal.z *= (bounds.size.z < 0) ? -1 : 1;

                  if (Event.current.type == EventType.Repaint)
                  {
                      s_BoundsBackfaced[i] = false;
                      if (!isCameraInsideBox)
                      {
                          var cosV = isCameraOrthographic ? Vector3.Dot(normal, -cameraLocalForward) :
                                     Vector3.Dot(normal, (cameraLocalPos - localPoint));
                          if (cosV < -0.0001f)
                          {
                              // TODO: do not set backfaced to true when side is infinitely thin
                              s_BoundsBackfaced[i] = !(isControlHot && !s_BoundsAxisHot[i % 3]);
                          }
                      }

                      var sideColor = (s_BoundsBackfaced[i] ? backfacedColor: boundsColor);
                      SceneHandles.color = SceneHandles.StateColor(sideColor, s_BoundsAxisDisabled[i], (currentFocusControl == id));

                      if (currentFocusControl == id)
                      {
                          var sceneView = SceneView.currentDrawingSceneView;
                          if (sceneView)
                          {
                              var rect = sceneView.position;
                              rect.min = Vector2.zero;
                              EditorGUIUtility.AddCursorRect(rect, SceneHandleUtility.GetCursorForDirection(localPoint, normal));
                          }
                          selectedAxes = s_BoundsAxes[i];
                      }

                      if (s_BoundsBackfaced[i])
                      {
                          pointSize *= backfaceSizeMultiplier;
                      }
                  }

                  var steps    = snappingSteps ?? Snapping.MoveSnappingSteps;
                  var newPoint = Slider1DHandle(id, (Axis)(i % 3), localPoint, normal, steps[i % 3], pointSize, sideCapFunction);
                  if (GUI.changed)
                  {
                      s_BoundsValues[i] += Vector3.Dot(direction, newPoint - localPoint);
                      haveChanged        = true;
                  }
              }

              // all edges of bounds
              for (int i = 0; i < s_BoundsEdgeIndices.GetLength(0); i++)
              {
                  var id = GUIUtility.GetControlID(s_BoundsHash, FocusType.Keyboard);

                  GUI.changed = false;
                  var index1 = s_BoundsEdgeIndices[i, 0];
                  var index2 = s_BoundsEdgeIndices[i, 1];
                  var point1 = s_BoundsVertices[index1];
                  var point2 = s_BoundsVertices[index2];

                  var midPoint = (point1 + point2) * 0.5f;

                  var offset1     = s_EdgeDirectionOffsets[i, 0];
                  var offset2     = s_EdgeDirectionOffsets[i, 1];
                  var offset3     = s_EdgeDirectionOffsets[i, 2];
                  var offset1_dir = offset1 % 3;
                  var offset2_dir = offset2 % 3;

                  if (Event.current.type == EventType.Repaint)
                  {
                      var highlight    = (currentFocusControl == id) || (currentFocusControl == s_BoundsControlIds[offset1]) || (currentFocusControl == s_BoundsControlIds[offset2]);
                      var edgeColor    = (s_BoundsBackfaced[offset1] && s_BoundsBackfaced[offset2]) ? backfacedColor : boundsColor;
                      var edgeDisabled = (s_BoundsAxisDisabled[offset1] && s_BoundsAxisDisabled[offset2]);
                      SceneHandles.color = SceneHandles.StateColor(edgeColor, edgeDisabled, highlight);

                      if (currentFocusControl == id)
                      {
                          selectedAxes = s_EdgeAxes[i];
                      }
                  }

                  // only use capFunction (render point) when in ortho mode & aligned with box or when side size is 0
                  bool isSideAlignedWithCamera = false;   // TODO: determine if aligned with camera direction & in ortho mode
                  bool showSidePoint           = !isSideAlignedWithCamera && ((point2 - point1).sqrMagnitude < kShowPointThreshold);

                  float   pointSize;
                  Vector3 offset;
                  if (showSidePoint)
                  {
                      pointSize = UnityEditor.HandleUtility.GetHandleSize(midPoint) * kPointScale;
                      offset    = Edge2DHandleOffset(id, point1, point2, midPoint, s_BoundsSlideDirs[offset3],
                                                     s_BoundsSlideDirs[offset1_dir],
                                                     s_BoundsSlideDirs[offset2_dir], pointSize, pointCapFunction, s_EdgeAxes[i], snappingSteps: snappingSteps);
                  }
                  else
                  {
                      offset = Edge2DHandleOffset(id, point1, point2, midPoint, s_BoundsSlideDirs[offset3],
                                                  s_BoundsSlideDirs[offset1_dir],
                                                  s_BoundsSlideDirs[offset2_dir], 0, null, s_EdgeAxes[i], snappingSteps: snappingSteps);
                  }

                  if (GUI.changed)
                  {
                      offset = Quaternion.Inverse(rotation) * offset;
                      if (Mathf.Abs(offset[offset1_dir]) > 0.000001f ||
                          Mathf.Abs(offset[offset2_dir]) > 0.000001f)
                      {
                          s_BoundsValues[offset1] += offset[offset1_dir];
                          s_BoundsValues[offset2] += offset[offset2_dir];
                          haveChanged              = true;
                      }
                      else
                      {
                          GUI.changed = false;
                      }
                  }
              }

              GUI.changed = prevGUIchanged || haveChanged;

              if (haveChanged)
              {
                  var size = bounds.size;

                  center.x = (s_BoundsValues[3] + s_BoundsValues[0]) * 0.5f;
                  size.x   = (s_BoundsValues[3] - s_BoundsValues[0]);

                  center.y = (s_BoundsValues[4] + s_BoundsValues[1]) * 0.5f;
                  size.y   = (s_BoundsValues[4] - s_BoundsValues[1]);

                  center.z = (s_BoundsValues[5] + s_BoundsValues[2]) * 0.5f;
                  size.z   = (s_BoundsValues[5] - s_BoundsValues[2]);

                  bounds.center = center;
                  bounds.size   = size;
              }

              // TODO: paint XZ intersection with grid plane + 'shadow'

              SceneHandles.disabled = prevDisabled; }

            return(bounds);
        }
 public static bool Contains(this Bounds b1, Bounds b2)
 {
     return(b1.Contains(b2.min) && b1.Contains(b2.max));
 }
Exemple #25
0
        public static void findShieldedPartsCylinder(Part basePart, Bounds fairingRenderBounds, List <Part> shieldedParts, float topY, float bottomY, float topRadius, float bottomRadius)
        {
            float height        = topY - bottomY;
            float largestRadius = topRadius > bottomRadius ? topRadius : bottomRadius;

            Vector3 lookupCenterLocal  = new Vector3(0, bottomY + (height * 0.5f), 0);
            Vector3 lookupTopLocal     = new Vector3(0, topY, 0);
            Vector3 lookupBottomLocal  = new Vector3(0, bottomY, 0);
            Vector3 lookupCenterGlobal = basePart.transform.TransformPoint(lookupCenterLocal);

            Ray lookupRay = new Ray(lookupBottomLocal, new Vector3(0, 1, 0));

            List <Part> partsFound = new List <Part>();

            Collider[] foundColliders = Physics.OverlapSphere(lookupCenterGlobal, height * 1.5f, 1);
            foreach (Collider col in foundColliders)
            {
                Part pt = col.gameObject.GetComponentUpwards <Part>();
                if (pt != null && pt != basePart && pt.vessel == basePart.vessel && !partsFound.Contains(pt))
                {
                    partsFound.Add(pt);
                }
            }

            Bounds[] otherPartBounds;
            Vector3  otherPartCenterLocal;

            float partYPos;
            float partYPercent;
            float partYRadius;
            float radiusOffset = topRadius - bottomRadius;

            foreach (Part pt in partsFound)
            {
                //check basic render bounds for containment

                //TODO this check misses the case where the fairing is long/tall, containing a wide part; it will report that the wide part can fit inside
                //of the fairing, due to the relative size of their colliders
                otherPartBounds = pt.GetRendererBounds();
                if (PartGeometryUtil.MergeBounds(otherPartBounds, pt.transform).size.sqrMagnitude > fairingRenderBounds.size.sqrMagnitude)
                {
                    continue;
                }

                Vector3 otherPartCenter = pt.partTransform.TransformPoint(PartGeometryUtil.FindBoundsCentroid(otherPartBounds, pt.transform));
                if (!fairingRenderBounds.Contains(otherPartCenter))
                {
                    continue;
                }

                //check part bounds center point against conic projection of the fairing
                otherPartCenterLocal = basePart.transform.InverseTransformPoint(otherPartCenter);

                //check vs top and bottom of the shielded area
                if (otherPartCenterLocal.y > lookupTopLocal.y || otherPartCenterLocal.y < lookupBottomLocal.y)
                {
                    continue;
                }

                //quick check vs cylinder radius
                float distFromLine = SSTUUtils.distanceFromLine(lookupRay, otherPartCenterLocal);
                if (distFromLine > largestRadius)
                {
                    continue;
                }

                //more precise check vs radius of the cone at that Y position
                partYPos     = otherPartCenterLocal.y - lookupBottomLocal.y;
                partYPercent = partYPos / height;
                partYRadius  = partYPercent * radiusOffset;
                if (distFromLine > (partYRadius + bottomRadius))
                {
                    continue;
                }
                shieldedParts.Add(pt);
            }
        }
Exemple #26
0
    // Tests to see whether lilB is inside bigB
    public static Vector3 BoundsInBoundsCheck(Bounds bigB, Bounds lilB, BoundsTest test = BoundsTest.onScreen)
    {
        // Get the center of lilB
        Vector3 pos = lilB.center;

        // Initialize the offset at [0,0,0]
        Vector3 off = Vector3.zero;

        switch (test)
        {
        // The center test determines what off (offset) would have to be applied to lilB to move its center back inside bigB
        case BoundsTest.center:
            // if the center is contained, return Vector3.zero
            if (bigB.Contains(pos))
            {
                return(Vector3.zero);
            }
            // if not contained, find the offset
            if (pos.x > bigB.max.x)
            {
                off.x = pos.x - bigB.max.x;
            }
            else if (pos.x < bigB.min.x)
            {
                off.x = pos.x - bigB.min.x;
            }
            if (pos.y > bigB.max.y)
            {
                off.y = pos.y - bigB.max.y;
            }
            else if (pos.y < bigB.min.y)
            {
                off.y = pos.y - bigB.min.y;
            }
            if (pos.z > bigB.max.z)
            {
                off.z = pos.z - bigB.max.z;
            }
            else if (pos.z < bigB.min.z)
            {
                off.z = pos.z - bigB.min.z;
            }
            return(off);

        // The onScreen test determines what off would have to be applied to keep all of lilB inside bigB
        case BoundsTest.onScreen:
            // find whether bigB contains all of lilB
            if (bigB.Contains(lilB.min) && bigB.Contains(lilB.max))
            {
                return(Vector3.zero);
            }
            // if not, find the offset
            if (lilB.max.x > bigB.max.x)
            {
                off.x = lilB.max.x - bigB.max.x;
            }
            else if (lilB.min.x < bigB.min.x)
            {
                off.x = lilB.min.x - bigB.min.x;
            }
            if (lilB.max.y > bigB.max.y)
            {
                off.y = lilB.max.y - bigB.max.y;
            }
            else if (lilB.min.y < bigB.min.y)
            {
                off.y = lilB.min.y - bigB.min.y;
            }
            if (lilB.max.z > bigB.max.z)
            {
                off.z = lilB.max.z - bigB.max.z;
            }
            else if (lilB.min.z < bigB.min.z)
            {
                off.z = lilB.min.z - bigB.min.z;
            }
            return(off);

        // The offScreen test determines what off would need to be applied to move any tiny part of lilB inside of bigB
        case BoundsTest.offScreen:
            // find whether bigB contains any of lilB
            bool cMin = bigB.Contains(lilB.min);
            bool cMax = bigB.Contains(lilB.max);
            if (cMin || cMax)
            {
                return(Vector3.zero);
            }
            // if not, find the offset
            if (lilB.min.x > bigB.max.x)
            {
                off.x = lilB.min.x - bigB.max.x;
            }
            else if (lilB.max.x < bigB.min.x)
            {
                off.x = lilB.max.x - bigB.min.x;
            }
            if (lilB.min.y > bigB.max.y)
            {
                off.y = lilB.min.y - bigB.max.y;
            }
            else if (lilB.max.y < bigB.min.y)
            {
                off.y = lilB.max.y - bigB.min.y;
            }
            if (lilB.min.z > bigB.max.z)
            {
                off.z = lilB.min.z - bigB.max.z;
            }
            else if (lilB.max.z < bigB.min.z)
            {
                off.z = lilB.max.z - bigB.min.z;
            }
            return(off);
        }

        return(Vector3.zero);
    }
Exemple #27
0
        public void Update(MouseState mouse, KeyboardState keyboard, KeyboardState previousKeyboard)
        {
            if (mouse.LeftButton == ButtonState.Pressed)
            {
                if (Bounds.Contains(mouse.Position))
                {
                    isClicked = true;
                }
                else
                {
                    isClicked = false;
                }
            }

            if (isClicked)
            {
                if (keyboard.IsKeyDown(Keys.D0) && previousKeyboard.IsKeyUp(Keys.D0))
                {
                    currentWord = currentWord.Insert(cursorIndex, "0");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D1) && previousKeyboard.IsKeyUp(Keys.D1))
                {
                    currentWord = currentWord.Insert(cursorIndex, "1");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D2) && previousKeyboard.IsKeyUp(Keys.D2))
                {
                    currentWord = currentWord.Insert(cursorIndex, "2");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D3) && previousKeyboard.IsKeyUp(Keys.D3))
                {
                    currentWord = currentWord.Insert(cursorIndex, "3");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D4) && previousKeyboard.IsKeyUp(Keys.D4))
                {
                    currentWord = currentWord.Insert(cursorIndex, "4");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D5) && previousKeyboard.IsKeyUp(Keys.D5))
                {
                    currentWord = currentWord.Insert(cursorIndex, "5");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D6) && previousKeyboard.IsKeyUp(Keys.D6))
                {
                    currentWord = currentWord.Insert(cursorIndex, "6");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D7) && previousKeyboard.IsKeyUp(Keys.D7))
                {
                    currentWord = currentWord.Insert(cursorIndex, "7");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D8) && previousKeyboard.IsKeyUp(Keys.D8))
                {
                    currentWord = currentWord.Insert(cursorIndex, "8");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.D9) && previousKeyboard.IsKeyUp(Keys.D9))
                {
                    currentWord = currentWord.Insert(cursorIndex, "9");
                    cursorIndex++;
                }
                else if (keyboard.IsKeyDown(Keys.Back) && previousKeyboard.IsKeyUp(Keys.Back) && cursorIndex > 0)
                {
                    currentWord = currentWord.Remove(cursorIndex - 1, 1);
                    if (cursorIndex != 0)
                    {
                        cursorIndex--;
                    }
                }
                else if (keyboard.IsKeyDown(Keys.Left) && previousKeyboard.IsKeyUp(Keys.Left) && cursorIndex > 0)
                {
                    cursorIndex--;
                }
                else if (keyboard.IsKeyDown(Keys.Right) && previousKeyboard.IsKeyUp(Keys.Right) && cursorIndex < currentWord.Length)
                {
                    cursorIndex++;
                }
                if (currentWord == "")
                {
                    reset();
                }
                else
                {
                    Scale = font.MeasureString(currentWord);
                }
            }
        }
Exemple #28
0
 public virtual bool Contains(int x, int y)
 {
     return(Bounds.Contains(x, y));
 }
 public static bool ContainBounds(this Bounds bounds, Bounds target)
 {
     return(bounds.Contains(target.min) && bounds.Contains(target.max));
 }
    void PopulateCellCandidates()
    {
        Profiler.BeginSample("Populate Candidates");

        ms_random = new System.Random(1235798);

        var detailPrototypes = terrainTemplate.detailPrototypes;

        var spriteSamplesInCell = Mathf.RoundToInt(cellSize * cellMaxSpriteDensity);

        spriteSamplesInCell *= spriteSamplesInCell;

        var meshSamplesInCell = Mathf.RoundToInt(cellSize * cellMaxMeshDensity);

        meshSamplesInCell *= meshSamplesInCell;

        var meshBuilder  = new MeshBuilder();
        var meshBuilder2 = new MeshBuilder();

        var maxInstancesInPatch = Mathf.CeilToInt(spriteSamplesInCell * m_patchesInCellSide);
        var patches             = new int[m_patchesInCellSide, m_patchesInCellSide, 1 + maxInstancesInPatch];

        var boundsCorner = m_bounds.center - m_bounds.extents;

        for (int cellIdx = 0; cellIdx < m_phatCells.Count;)
        {
            Profiler.BeginSample("Cell");
            var phatCell = m_phatCells[cellIdx];

            var cellOffset = new Vector3(phatCell.x * cellSize, 0f, phatCell.z * cellSize);
            var cellCorner = boundsCorner + cellOffset;

            float minY = float.MaxValue, maxY = float.MinValue;

            foreach (var pj in phatCell.pjobs)
            {
                Profiler.BeginSample("Paintjob");

                var pjCorner  = pj.transform.position - pj.alignedSize * 0.5f;
                var pjSizeRcp = new Vector3(1f / pj.alignedSize.x, 1f, 1f / pj.alignedSize.z);

                for (int s = 0, sidx = 0; s < spriteSamplesInCell; ++s)
                {
                    for (int l = 0, ln = pj.detailLayerCount; l < ln; ++l)
                    {
                        var detailLayer = detailPrototypes[l];
                        if (detailLayer.usePrototypeMesh)
                        {
                            continue;
                        }

                        var subCellSampleRand   = RandX0Z_ZO;
                        var subCellSampleOffset = subCellSampleRand * cellSize;
                        var subCellSamplePos    = cellCorner + subCellSampleOffset;

                        var patchRelativePos = Vector3.Scale(subCellSamplePos - pjCorner, pjSizeRcp);

                        if (patchRelativePos.x < 0f || patchRelativePos.x > 1f || patchRelativePos.z < 0f || patchRelativePos.z > 1f)
                        {
                            continue;
                        }

                        var patchDimension = Mathf.RoundToInt(Mathf.Sqrt(pj.detailLayerElements));
                        var patchOffset    = Mathf.Clamp(Mathf.RoundToInt(patchDimension * patchRelativePos.x), 0, patchDimension);
                        patchOffset += Mathf.RoundToInt(patchDimension * Mathf.Round(patchDimension * patchRelativePos.z));
                        patchOffset  = Mathf.Clamp(patchOffset, 0, pj.detailLayerElements - 1);

                        if (pj.maskData[patchOffset] <= 0f)
                        {
                            continue;
                        }

                        int totalLayersValue = 0;
                        for (int lc = 0, lcn = pj.detailLayerCount; lc < lcn; ++lc)
                        {
                            var layerValue2 = pj.detailData[lc * pj.detailLayerElements + patchOffset];
                            totalLayersValue += layerValue2;
                        }
                        float totalLayersScale = Mathf.Clamp01(totalLayersValue / 4f);

                        var heightY  = (pj.heightData[patchOffset] - 0.5f) * pj.alignedSize.y + pj.transform.position.y;
                        var placePos = new Vector3(subCellSamplePos.x, heightY, subCellSamplePos.z);
//					for(int l = 0, ln = pj.detailLayerCount; l < ln; ++l) {
//						var detailLayer = detailPrototypes[l];
//						if(detailLayer.usePrototypeMesh)
//							continue;

                        var layerValue = pj.detailData[l * pj.detailLayerElements + patchOffset];
                        if (layerValue > 0)
                        {
                            // TODO: check density vs probability

                            var subPlacePos = placePos;
                            var spriteColB  = SampleColormap(subPlacePos);
                            var healthCol   = Color.Lerp(detailLayer.dryColor, detailLayer.healthyColor, healthyToDryRatio);                          // Mathf.Clamp01(0.5f + ssn / (float)maxInstances));
                            var spriteColT  = Color.Lerp(spriteColB, healthCol, groundToTopColorRatio);

                            var darkenBase = Mathf.Lerp(darkenBaseMaxMin.x, darkenBaseMaxMin.y, totalLayersScale);
                            //spriteColB.r *= darkenBase;
                            //spriteColB.g *= darkenBase;
                            //spriteColB.b *= darkenBase;
                            spriteColB.a = darkenBase;

                            //if(darkenBase < darkenBaseMaxMin.y)
                            if (totalLayersScale < 0f || totalLayersScale > 1f)
                            {
                                Debug.LogWarningFormat("SuperDark: {0}  {1}  {2}", darkenBase, totalLayersValue, totalLayersScale);
                            }

                            var spriteWidth  = Mathf.Lerp(detailLayer.minWidth, detailLayer.maxWidth, RandVal_ZO);
                            var spriteHeight = Mathf.Lerp(detailLayer.minHeight, detailLayer.maxHeight, RandVal_ZO);
                            var spriteBB     = detailLayer.renderMode == DetailRenderMode.GrassBillboard;
                            var spriteRot    = /*spriteBB ? Quaternion.identity :*/ RandYaw_PM;
                            var vtxStart     = meshBuilder.PushSprite(growthAtlasMappings[l], spriteWidth, spriteHeight, subPlacePos, spriteRot, spriteColB, spriteColT, spriteBB, sidx++);

                            var patchIdxX    = Mathf.FloorToInt(subCellSampleRand.x * m_patchesInCellSide);
                            var patchIdxZ    = Mathf.FloorToInt(subCellSampleRand.z * m_patchesInCellSide);
                            var patchIdxNext = 1 + patches[patchIdxX, patchIdxZ, 0];
                            patches[patchIdxX, patchIdxZ, patchIdxNext] = vtxStart;
                            patches[patchIdxX, patchIdxZ, 0]            = patchIdxNext;

                            minY = Mathf.Min(minY, subPlacePos.y);
                            maxY = Mathf.Max(maxY, subPlacePos.y + spriteHeight);
                        }
                    }
                }

                for (int s = 0, sidx = 0; s < meshSamplesInCell; ++s)
                {
                    for (int l = 0, ln = pj.detailLayerCount; l < ln; ++l)
                    {
                        var detailLayer = detailPrototypes[l];
                        if (!detailLayer.usePrototypeMesh)
                        {
                            continue;
                        }
                        var subCellSampleRand   = RandX0Z_ZO;
                        var subCellSampleOffset = subCellSampleRand * cellSize;
                        var subCellSamplePos    = cellCorner + subCellSampleOffset;

                        var patchRelativePos = Vector3.Scale(subCellSamplePos - pjCorner, pjSizeRcp);

                        if (patchRelativePos.x < 0f || patchRelativePos.x > 1f || patchRelativePos.z < 0f || patchRelativePos.z > 1f)
                        {
                            continue;
                        }

                        var patchDimension = Mathf.RoundToInt(Mathf.Sqrt(pj.detailLayerElements));
                        var patchOffset    = Mathf.Clamp(Mathf.RoundToInt(patchDimension * patchRelativePos.x), 0, patchDimension);
                        patchOffset += Mathf.RoundToInt(patchDimension * Mathf.Round(patchDimension * patchRelativePos.z));
                        patchOffset  = Mathf.Clamp(patchOffset, 0, pj.detailLayerElements - 1);

                        if (pj.maskData[patchOffset] <= 0f)
                        {
                            continue;
                        }

                        int totalLayersValue = 0;
                        for (int lc = 0, lcn = pj.detailLayerCount; lc < lcn; ++lc)
                        {
                            var layerValue2 = pj.detailData[lc * pj.detailLayerElements + patchOffset];
                            totalLayersValue += layerValue2;
                        }
                        float totalLayersScale = Mathf.Clamp01(totalLayersValue / 4f);

                        var heightY  = (pj.heightData[patchOffset] - 0.5f) * pj.alignedSize.y + pj.transform.position.y;
                        var placePos = new Vector3(subCellSamplePos.x, heightY, subCellSamplePos.z);
//					for(int l = 0, ln = pj.detailLayerCount; l < ln; ++l) {
//						var detailLayer = detailPrototypes[l];
//						if(!detailLayer.usePrototypeMesh)
//							continue;

                        var layerValue = pj.detailData[l * pj.detailLayerElements + patchOffset];
                        if (layerValue > 0)
                        {
                            // TODO: check density vs probability

                            var meshScale = new Vector3(
                                Mathf.Lerp(detailLayer.minWidth, detailLayer.minWidth, RandVal_ZO),
                                Mathf.Lerp(detailLayer.minHeight, detailLayer.maxHeight, RandVal_ZO),
                                Mathf.Lerp(detailLayer.minWidth, detailLayer.minWidth, RandVal_ZO)
                                );

                            var subPlacePos = placePos;
                            var spriteColB  = SampleColormap(subPlacePos);
                            var healthCol   = Color.Lerp(detailLayer.dryColor, detailLayer.healthyColor, healthyToDryRatio);                          // Mathf.Clamp01(0.5f + ssn / (float)maxInstances));
                            var spriteColT  = Color.Lerp(spriteColB, healthCol, groundToTopColorRatio);

                            var darkenBase = Mathf.Lerp(darkenBaseMaxMin.x, darkenBaseMaxMin.y, totalLayersScale);
                            //spriteColB.r *= darkenBase;
                            //spriteColB.g *= darkenBase;
                            //spriteColB.b *= darkenBase;
                            spriteColB.a = darkenBase;

                            //if((layerValue / 16f) < (Random.value - 0.35f))
                            meshBuilder2.PushMesh(
                                detailLayer.prototype.GetComponent <MeshFilter>().sharedMesh,
                                growthAtlasMappings[l],
                                subPlacePos,
                                RandYaw_PM,
                                meshScale,
                                RandVal_ZO * 0.42f,
                                spriteColB,
                                spriteColT,
                                sidx++
                                );
                        }
                    }
                }

                var embedBounds = new Bounds(
                    cellCorner + new Vector3(cellSize * 0.5f, 0f, cellSize * 0.5f),
                    new Vector3(cellSize, 100f, cellSize)
                    );

                var embedInstanceIdx = 0;
                foreach (var ei in capturedInstances)
                {
                    var embedPos = ei.transform.position;

                    if (/*!ei.enabled ||*/ !embedBounds.Contains(embedPos))
                    {
                        continue;
                    }

                    //public float darkenBaseMesh = 0.3f;
                    //public float meshBaseToGroundRatio = 0.3f;

                    var spriteColB = SampleColormap(embedPos);
                    var spriteColT = Color.Lerp(spriteColB, Color.white, 0.3f);

                    var darkenBase = 0.3f;                     //Mathf.Lerp(0.6f, 0.15f, totalLayersScale);
                    spriteColB.a = darkenBase;

                    var atlasName  = ei.sharedMaterial.mainTexture.name;
                    var atlasIndex = 0;

                    for (; atlasIndex < growthAtlasMappingNames.Length; ++atlasIndex)
                    {
                        if (growthAtlasMappingNames[atlasIndex] == atlasName)
                        {
                            break;
                        }
                    }

                    meshBuilder2.PushMesh(ei.GetComponent <MeshFilter>().sharedMesh, growthAtlasMappings[atlasIndex],
                                          embedPos, ei.transform.rotation, ei.transform.localScale,
                                          0f, spriteColB, spriteColT, embedInstanceIdx++
                                          );

                    //ei.enabled = false;
                }

                Profiler.EndSample();
            }

            if (!meshBuilder.IsEmpty || !meshBuilder2.IsEmpty)
            {
                //Debug.Log(string.Format("x: {0} z: {1} camD: {2} scaledSpriteDensity: {3},  scaledMeshDensity: {4}, scaledMaxSprites: {5}, scaledMaxMeshes: {6}", cell.x, cell.z, cellDistance, cellScaledSpriteDensity, cellScaledMeshDensity, subCellMaxSpriteInstances, subCellMaxMeshInstances));
                //Debug.LogFormat("x: {0} z: {1}", phatCell.x, phatCell.z);
                var dbgName = string.Format("Cell {0}x{1}: ", phatCell.x, phatCell.z);

                phatCell.bounds.SetMinMax(new Vector3(cellCorner.x, minY, cellCorner.z), new Vector3(cellCorner.x + cellSize, maxY, cellCorner.z + cellSize));
                phatCell.patches = meshBuilder.SortPatches(patches);

                if (!meshBuilder.IsEmpty)
                {
                    phatCell.mesh    = meshBuilder.Realize(dbgName + "Sprites");
                    phatCell.indices = phatCell.mesh.triangles;
                }

                if (!meshBuilder2.IsEmpty)
                {
                    phatCell.mesh2 = meshBuilder2.Realize(dbgName + "Meshes");
                }

                meshBuilder.Reset();
                meshBuilder2.Reset();

                for (int pz = 0, pzn = patches.GetLength(1); pz < pzn; ++pz)
                {
                    for (int px = 0, pxn = patches.GetLength(0); px < pxn; ++px)
                    {
                        patches[px, pz, 0] = 0;
                    }
                }

                ++cellIdx;
            }
            else
            {
                //Debug.LogFormat("Culling empty cell at {0}, {1}", phatCell.x, phatCell.z);
                m_phatCells[cellIdx] = m_phatCells[m_phatCells.Count - 1];
                m_phatCells.RemoveAt(m_phatCells.Count - 1);
            }

            Profiler.EndSample();
        }

        Profiler.EndSample();
    }
Exemple #31
0
 public virtual void onHover(Point mousePosition)
 {
     BackgroundColor = Bounds.Contains(mousePosition) ? Color.Gray : Color.White;
 }
Exemple #32
0
 public bool IsPointInsideWorld(Vector3Int point)
 {
     return(worldBounds.Contains(point));
 }
Exemple #33
0
    // Checks to see whether Bounds lilB are within Bound bigB
    public static Vector3 BoundsInBoundsCheck(Bounds bigB, Bounds lilB, BoundsTest test = BoundsTest.onScreen)
    {
        // The behaviour of the function will change based on the BoundsTest

        // Get the centre of the lilB
        Vector3 posLilBCenter = lilB.center;

        // Initialize the offset
        Vector3 off = Vector3.zero;

        // Switch between three cases, is centre within the bigB? is all of lilB within? is any of lilB within?
        switch (test)
        {
        case BoundsTest.centre:
            // The centre test determine what off would have to be applied to lilB to move the its center back into BigB
            if (bigB.Contains(posLilBCenter))
            {
                return(Vector3.zero);
            }

            if (posLilBCenter.x > bigB.max.x)
            {
                off.x = posLilBCenter.x - bigB.max.x;
            }
            else if (posLilBCenter.x < bigB.min.x)
            {
                off.x = posLilBCenter.x - bigB.min.x;
            }

            if (posLilBCenter.y > bigB.max.y)
            {
                off.y = posLilBCenter.y - bigB.max.y;
            }
            else if (posLilBCenter.y < bigB.min.y)
            {
                off.y = posLilBCenter.y - bigB.min.y;
            }

            if (posLilBCenter.z > bigB.max.z)
            {
                off.z = posLilBCenter.z - bigB.max.z;
            }
            else if (posLilBCenter.z < bigB.min.z)
            {
                off.z = posLilBCenter.z - bigB.min.z;
            }

            return(off);



        case BoundsTest.onScreen:
            // The on screen test determine what off would have to be applied to lilB to keep all of lilB inside bigB
            if (bigB.Contains(lilB.max) && bigB.Contains(lilB.min))
            {
                return(Vector3.zero);
            }

            if (lilB.max.x > bigB.max.x)
            {
                off.x = lilB.max.x - bigB.max.x;
            }
            else if (lilB.min.x < bigB.min.x)
            {
                off.x = lilB.min.x - bigB.min.x;
            }

            if (lilB.max.y > bigB.max.y)
            {
                off.y = lilB.max.y - bigB.max.y;
            }
            else if (lilB.min.y < bigB.min.y)
            {
                off.y = lilB.min.y - bigB.min.y;
            }

            if (lilB.max.z > bigB.max.z)
            {
                off.z = lilB.max.z - bigB.max.z;
            }
            else if (lilB.min.z < bigB.min.z)
            {
                off.z = lilB.min.z - bigB.min.z;
            }

            return(off);

        case BoundsTest.offScreen:
            // the off screen test deternmine what off would need to be applied to move any tiny part of lilB inside of bigB
            if (bigB.Contains(lilB.max) || bigB.Contains(lilB.min))
            {
                return(Vector3.zero);
            }

            if (lilB.min.x > bigB.max.x)
            {
                off.x = lilB.min.x - bigB.max.x;
            }
            else if (lilB.max.x < bigB.min.x)
            {
                off.x = lilB.max.x - bigB.min.x;
            }

            if (lilB.min.y > bigB.max.y)
            {
                off.y = lilB.min.y - bigB.max.y;
            }
            else if (lilB.max.y < bigB.min.y)
            {
                off.y = lilB.max.y - bigB.min.y;
            }

            if (lilB.min.z > bigB.max.z)
            {
                off.z = lilB.min.z - bigB.max.z;
            }
            else if (lilB.max.z < bigB.min.z)
            {
                off.z = lilB.max.z - bigB.min.z;
            }

            return(off);
        }
        return(Vector3.zero);
    }
Exemple #34
0
    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < activeSwarm.Count; i++)
        {
            Vector3 tarPos = tarPositions[i];
            //Debug.Log(Time.time + " activeSwarm[i].transform.position " + activeSwarm[i].transform.position + " " + tarPositions[i]);
            if (Mathf.Abs(Vector3.Distance(activeSwarm[i].transform.position, tarPositions[i])) < reachedTarPosThreshold ||
                Mathf.Abs(Vector3.Distance(center.transform.position, lastCenter)) > changeTarPosThreshold)
            {
                float angle  = Random.Range(0, 360f) * Mathf.Deg2Rad;
                float radius = Random.Range(minRadius, maxRadius);
                float x      = Mathf.Cos(angle) * radius;
                float y      = Mathf.Sin(angle) * radius;
                tarPos = new Vector3(center.transform.position.x + x, center.transform.position.y + y, center.transform.position.z);

                tarPositions[i] = tarPos;
                radii[i]        = radius;
                //Debug.Log(Time.time + " new tarPos " + tarPositions[i]);
            }

            Vector3 moveDir = tarPos - activeSwarm[i].transform.position;
            moveDir.Normalize();
            activeSwarm[i].transform.position += moveDir * Time.deltaTime * 2;

            if (moveDir.x > 0)
            {
                if (activeSwarm[i].transform.localScale.x < 0)
                {
                    activeSwarm[i].transform.localScale = new Vector3(-activeSwarm[i].transform.localScale.x, activeSwarm[i].transform.localScale.y, activeSwarm[i].transform.localScale.z);
                }
            }
            else
            {
                if (activeSwarm[i].transform.localScale.x > 0)
                {
                    activeSwarm[i].transform.localScale = new Vector3(-activeSwarm[i].transform.localScale.x, activeSwarm[i].transform.localScale.y, activeSwarm[i].transform.localScale.z);
                }
            }

            //Validate position and target position
            for (int j = 0; j < activeSwarm.Count; j++)
            {
                if (i != j &&
                    activeSwarm[i].GetComponent <BoxCollider2D>().bounds.Intersects(activeSwarm[j].GetComponent <BoxCollider2D>().bounds))
                {
                    Bounds testBounds = new Bounds(activeSwarm[i].GetComponent <BoxCollider2D>().bounds.center,
                                                   new Vector3(activeSwarm[i].GetComponent <BoxCollider2D>().bounds.size.x + activeSwarm[j].GetComponent <BoxCollider2D>().bounds.size.x,
                                                               activeSwarm[i].GetComponent <BoxCollider2D>().bounds.size.y + activeSwarm[j].GetComponent <BoxCollider2D>().bounds.size.y,
                                                               activeSwarm[i].GetComponent <BoxCollider2D>().bounds.size.z + activeSwarm[j].GetComponent <BoxCollider2D>().bounds.size.z));
                    if (testBounds.Contains(tarPositions[i]))
                    {
                        float radius     = radii[i];
                        bool  validPoint = false;
                        while (!validPoint)
                        {
                            bool    invalidPoint = false;
                            float   angle        = Random.Range(0, 360f) * Mathf.Deg2Rad;
                            float   x            = Mathf.Cos(angle) * radius;
                            float   y            = Mathf.Sin(angle) * radius;
                            Vector3 tarPos2      = new Vector3(center.transform.position.x + x, center.transform.position.y + y, center.transform.position.z);

                            for (int k = 0; k < activeSwarm.Count && !validPoint; k++)
                            {
                                testBounds = new Bounds(activeSwarm[i].GetComponent <BoxCollider2D>().bounds.center,
                                                        new Vector3(activeSwarm[i].GetComponent <BoxCollider2D>().bounds.size.x + activeSwarm[k].GetComponent <BoxCollider2D>().bounds.size.x,
                                                                    activeSwarm[i].GetComponent <BoxCollider2D>().bounds.size.y + activeSwarm[k].GetComponent <BoxCollider2D>().bounds.size.y,
                                                                    activeSwarm[i].GetComponent <BoxCollider2D>().bounds.size.z + activeSwarm[k].GetComponent <BoxCollider2D>().bounds.size.z));
                                if (testBounds.Contains(tarPos2))
                                {
                                    invalidPoint = true;
                                }
                            }

                            if (!invalidPoint)
                            {
                                validPoint      = true;
                                radii[i]        = radius;
                                tarPositions[i] = tarPos2;
                            }
                            else
                            {
                                radius += .1f;
                            }
                        }
                    }
                    break;
                }
            }
        }

        lastCenter = center.transform.position;
    }
        public void BoundsCanContainAPoint()
        {
            b = new Bounds(Vector3.zero, Vector3.one);

            Assert.That(b.Contains(Vector3.zero));
        }