Exemple #1
0
        public void ErrorTest()
        {
            int  counter = 0;
            bool error   = false;
            var  subject = new Subject <string>();

            subject
            .Select(str => int.Parse(str))
            .Subscribe(
                x => { Debug.Log(x); counter++; },
                ex => { Debug.LogWarning("例外が発生しました:" + ex.Message); error = true; },
                () => Debug.Log("OnCOmpleted"));

            subject.OnNext("1");
            subject.OnNext("2");

            // int.Parseに失敗して例外が発生する
            subject.OnNext("Three");

            Assert.IsTrue(error, "エラーが発行されたのでカウンタが1");

            // OnErrorメッセージ発生により購読は終了済み
            subject.OnNext("4");

            Assert.AreNotEqual(counter, 3, "終了しているのでカウントされない");

            // ただしSubject自体が例外出したわけじゃないのでSubjectは正常稼働中
            // そのため再購読すれば利用ができる
            counter = 0;

            subject.Subscribe(
                x => { Debug.Log(x); counter = 1; },
                () => Debug.Log("Completed"));

            subject.OnNext("Hellor");
            subject.OnCompleted();
            subject.Dispose();

            Assert.AreEqual(1, counter, "再購読したらカウントが 1 になった");
        }
        public void ReadOnlyTransformEqualsSame()
        {
            var transform1 = _transform.AsReadOnly();

            Assert.IsTrue(transform1 == _transform);
            Assert.IsFalse(transform1 != _transform);
            Assert.IsTrue(transform1.Equals(_transform));
            Assert.IsFalse(ReferenceEquals(transform1, _transform));

            var transform2 = transform1;

            Assert.IsTrue(transform1 == transform2);
            Assert.IsFalse(transform1 != transform2);
            Assert.IsTrue(transform1.Equals(transform2));
            Assert.IsTrue(ReferenceEquals(transform1, transform2));

            transform2 = _transform.AsReadOnly();
            Assert.IsTrue(transform1 == transform2);
            Assert.IsFalse(transform1 != transform2);
            Assert.IsTrue(transform1.Equals(transform2));
            Assert.IsFalse(ReferenceEquals(transform1, transform2));
        }
Exemple #3
0
        public unsafe void RigidBodyCastRayTest()
        {
            Physics.RigidBody rigidbody = Unity.Physics.RigidBody.Zero;

            const float size         = 1.0f;
            const float convexRadius = 0.0f;

            var rayStartOK = new float3(-10, -10, -10);
            var rayEndOK   = new float3(10, 10, 10);

            var rayStartFail = new float3(-10, 10, -10);
            var rayEndFail   = new float3(10, 10, 10);

            rigidbody.Collider = (Collider *)BoxCollider.Create(float3.zero, quaternion.identity, new float3(size), convexRadius).GetUnsafePtr();

            var raycastInput = new RaycastInput();
            var closestHit   = new RaycastHit();
            var allHits      = new NativeList <RaycastHit>(Allocator.Temp);

            // OK case : Ray hits the box collider
            float3 rayDir = rayEndOK - rayStartOK;

            raycastInput.Ray.Origin    = rayStartOK;
            raycastInput.Ray.Direction = rayDir;
            raycastInput.Filter        = CollisionFilter.Default;

            Assert.IsTrue(rigidbody.CastRay(raycastInput));
            Assert.IsTrue(rigidbody.CastRay(raycastInput, out closestHit));
            Assert.IsTrue(rigidbody.CastRay(raycastInput, ref allHits));

            // Fail Case : wrong direction
            rayDir = rayEndFail - rayStartFail;
            raycastInput.Ray.Origin    = rayStartFail;
            raycastInput.Ray.Direction = rayDir;

            Assert.IsFalse(rigidbody.CastRay(raycastInput));
            Assert.IsFalse(rigidbody.CastRay(raycastInput, out closestHit));
            Assert.IsFalse(rigidbody.CastRay(raycastInput, ref allHits));
        }
        public void PriorityQueueTestSimple()
        {
            var q = new ObservablePriorityStack <TestDialog>();

            var testDialogs = BuildTestDialogList();

            foreach (var testDialog in testDialogs)
            {
                q.Enqueue(testDialog);
            }

            var target = new[] { 5, 2, 4, 3, 6, 1 };
            var result = new int[6];

            var i = 0;

            while (q.Count > 0)
            {
                var d = q.Dequeue();
                result[i] = d.Content;
                i++;
            }

            string Expected()
            {
                var str = "Expected: " + target[0];

                for (int k = 1; k < target.Length; k++)
                {
                    str = str + ", " + target[k];
                }
                return(str);
            }

            for (int j = 0; j < target.Length; j++)
            {
                Assert.IsTrue(result[j] == target[j], Expected());
            }
        }
        public IEnumerator UnitMovementTestWithEnumeratorPasses()
        {
            SceneManager.LoadScene("UnitMovementTest");
            yield return(null);

            var movement = Object.FindObjectOfType <UnitMovementController>();
            var points   = Object.FindObjectOfType <PointSet>().Points;

            foreach (var currentPoint in points)
            {
                movement.MoveToPoint(currentPoint.transform.position);
                yield return(new WaitForSeconds(2.0f));

                while (movement.CurrentSpeed > 0.0001f)
                {
                    yield return(new WaitForEndOfFrame());
                }

                float distance = Vector3.Distance(movement.transform.position.Flat(), currentPoint.position.Flat());
                Assert.IsTrue(distance < 0.01f, $"Distance is {distance}");
            }
        }
        public void ResLoaderTest()
        {
            ResFactory.AddResCreator <TestResCreator>();

            // 测试
            var resLoader = ResLoader.Allocate();

            var resSearchKeys = ResSearchKeys.Allocate("test://icon_texture", null, typeof(Texture2D));

            var iconTextureRes = resLoader.LoadResSync(resSearchKeys);

            Assert.IsTrue(iconTextureRes is TestRes);
            Assert.AreEqual(1, iconTextureRes.RefCount);
            Assert.AreEqual(ResState.Ready, iconTextureRes.State);

            resLoader.Recycle2Cache();

            Assert.AreEqual(0, iconTextureRes.RefCount);
            Assert.AreEqual(ResState.Waiting, iconTextureRes.State);

            resLoader = null;
        }
Exemple #7
0
        public unsafe void RigidBodyCastColliderTest()
        {
            Physics.RigidBody rigidbody = Unity.Physics.RigidBody.Zero;

            const float size         = 1.0f;
            const float convexRadius = 1.0f;

            var rayStartOK = new float3(-10, -10, -10);
            var rayEndOK   = new float3(10, 10, 10);

            var rayStartFail = new float3(-10, 10, -10);
            var rayEndFail   = new float3(10, 10, 10);

            rigidbody.Collider = (Collider *)BoxCollider.Create(float3.zero, quaternion.identity, new float3(size), convexRadius).GetUnsafePtr();

            var colliderCastInput = new ColliderCastInput();
            var closestHit        = new ColliderCastHit();
            var allHits           = new NativeList <ColliderCastHit>(Allocator.Temp);

            // OK case : Sphere hits the box collider
            float3 rayDir = rayEndOK - rayStartOK;

            colliderCastInput.Position  = rayStartOK;
            colliderCastInput.Direction = rayDir;
            colliderCastInput.Collider  = (Collider *)SphereCollider.Create(float3.zero, convexRadius).GetUnsafePtr();

            Assert.IsTrue(rigidbody.CastCollider(colliderCastInput));
            Assert.IsTrue(rigidbody.CastCollider(colliderCastInput, out closestHit));
            Assert.IsTrue(rigidbody.CastCollider(colliderCastInput, ref allHits));

            // Fail case : wrong direction
            rayDir = rayEndFail - rayStartFail;
            colliderCastInput.Position  = rayStartFail;
            colliderCastInput.Direction = rayDir;

            Assert.IsFalse(rigidbody.CastCollider(colliderCastInput));
            Assert.IsFalse(rigidbody.CastCollider(colliderCastInput, out closestHit));
            Assert.IsFalse(rigidbody.CastCollider(colliderCastInput, ref allHits));
        }
        public void DisableFeatureSetDisabledFeatures()
        {
            OpenXRFeatureSetManager.InitializeFeatureSets(true);
            var extInfo = FeatureHelpersInternal.GetAllFeatureInfo(BuildTargetGroup.Standalone);

            foreach (var ext in extInfo.Features)
            {
                Assert.IsFalse(ext.Feature.enabled);
            }


            var foundFeatureSet = OpenXRFeatureSetManager.GetFeatureSetInfoWithId(BuildTargetGroup.Standalone, k_TestFeatureSetId);

            Assert.IsNotNull(foundFeatureSet);
            foundFeatureSet.isEnabled  = true;
            foundFeatureSet.wasChanged = true;
            OpenXRFeatureSetManager.SetFeaturesFromEnabledFeatureSets(BuildTargetGroup.Standalone);

            foreach (var ext in extInfo.Features)
            {
                if (String.Compare(ext.Attribute.FeatureId, MicrosoftHandInteraction.featureId, true) == 0)
                {
                    Assert.IsTrue(ext.Feature.enabled);
                }
                else
                {
                    Assert.IsFalse(ext.Feature.enabled);
                }
            }

            foundFeatureSet.isEnabled  = false;
            foundFeatureSet.wasChanged = true;
            OpenXRFeatureSetManager.SetFeaturesFromEnabledFeatureSets(BuildTargetGroup.Standalone);

            foreach (var ext in extInfo.Features)
            {
                Assert.IsFalse(ext.Feature.enabled);
            }
        }
        public void FoundExpectedFeatureSets()
        {
            string[] expectedFeatuerSets = new string[] {
                k_TestFeatureSetId,
                KnownFeatureSetsContent.s_MicrosoftFeatureSetId,
#if USE_MOCK_FEATURE_SET
                "com.unity.openxr.featureset.mockruntime",
#endif //USE_MOCK_FEATURE_SET
            };

            var featureSets = OpenXRFeatureSetManager.FeatureSetsForBuildTarget(BuildTargetGroup.Standalone);
            Assert.IsNotNull(featureSets);
            Assert.AreEqual(expectedFeatuerSets.Length, featureSets.Count);

            foreach (var featureSet in featureSets)
            {
                if (Array.IndexOf(expectedFeatuerSets, featureSet.featureSetId) == -1)
                {
                    Assert.IsTrue(false, $"Found unexpected feature set id {featureSet.featureSetId}!");
                }
            }
        }
Exemple #10
0
        private bool RemoveChunk()
        {
            // Wait until all generic tasks are processed
            if (Interlocked.CompareExchange(ref m_genericWorkItemsLeftToProcess, 0, 0) != 0)
            {
                Assert.IsTrue(false);
                return(false);
            }

            // If chunk was generated we need to wait for other states with higher priority to finish first
            if (m_completedTasks.Check(ChunkState.Generate))
            {
                // Blueprints and FinalizeData need to finish first
                if (!m_completedTasks.Check(
#if ENABLE_BLUEPRINTS
                        ChunkState.GenerateBlueprints |
#endif
                        ChunkState.FinalizeData
                        ))
                {
                    return(false);
                }

                // With streaming enabled we have to wait for serialization to finish as well
                if (EngineSettings.WorldConfig.Streaming && !m_completedTasks.Check(ChunkState.Serialize))
                {
                    return(false);
                }
            }
            else
            // No work on chunk started yet. Reset its' state completely
            {
                m_pendingTasks   = m_pendingTasks.Reset();
                m_completedTasks = m_completedTasks.Reset();
            }

            m_completedTasks = m_completedTasks.Set(CurrStateRemoveChunk);
            return(true);
        }
Exemple #11
0
 public void ExpandCapacityTest()
 {
     using (var bv = new BitVector(1)) {
         for (int i = 2; i <= 1024; ++i)
         {
             int prev = bv.Capacity;
             for (int j = 0; j < bv.Capacity; ++j)
             {
                 bv.Set(j);
             }
             bv.Capacity = i;
             for (int j = 0; j < prev; ++j)
             {
                 Assert.IsTrue(bv.Check(j));
             }
             for (int j = prev; j < i; ++j)
             {
                 Assert.IsFalse(bv.Check(j));
             }
         }
     }
 }
Exemple #12
0
        public unsafe void RigidBodyCalculateDistanceTest()
        {
            const float size         = 1.0f;
            const float convexRadius = 0.0f;
            const float sphereRadius = 1.0f;

            var queryPos = new float3(-10, -10, -10);

            BlobAssetReference <Collider> boxCollider    = BoxCollider.Create(float3.zero, quaternion.identity, new float3(size), convexRadius);
            BlobAssetReference <Collider> sphereCollider = SphereCollider.Create(float3.zero, sphereRadius);

            var rigidBody = new Physics.RigidBody
            {
                WorldFromBody = RigidTransform.identity,
                Collider      = (Collider *)boxCollider.GetUnsafePtr()
            };

            var colliderDistanceInput = new ColliderDistanceInput
            {
                Collider  = (Collider *)sphereCollider.GetUnsafePtr(),
                Transform = new RigidTransform(quaternion.identity, queryPos)
            };

            var closestHit = new DistanceHit();
            var allHits    = new NativeList <DistanceHit>(Allocator.Temp);

            // OK case : with enough max distance
            colliderDistanceInput.MaxDistance = 10000.0f;
            Assert.IsTrue(rigidBody.CalculateDistance(colliderDistanceInput));
            Assert.IsTrue(rigidBody.CalculateDistance(colliderDistanceInput, out closestHit));
            Assert.IsTrue(rigidBody.CalculateDistance(colliderDistanceInput, ref allHits));

            // Fail case : not enough max distance
            colliderDistanceInput.MaxDistance = 1;
            Assert.IsFalse(rigidBody.CalculateDistance(colliderDistanceInput));
            Assert.IsFalse(rigidBody.CalculateDistance(colliderDistanceInput, out closestHit));
            Assert.IsFalse(rigidBody.CalculateDistance(colliderDistanceInput, ref allHits));
        }
Exemple #13
0
        public IEnumerator OneClip_EndTransition()
        {
            var AnimatorPlayableGameObject = new AnimatorPlayableGameObject();

            float endTransitionTime = 0.0625f;
            float clipTime          = 0.25f;

            AnimatorPlayableGameObject.PlaySequencedAnimation(0, new SequencedAnimationInput()
            {
                isInfinite           = false,
                BeginTransitionTime  = 0f,
                EndTransitionTime    = endTransitionTime,
                UniqueAnimationClips = new List <UniqueAnimationClipInput>()
                {
                    new UniqueAnimationClipInput()
                    {
                        AnimationClip = CreateClip(clipTime)
                    }
                }
            });

            yield return(null);

            yield return(new WaitForSeconds(clipTime));

            Assert.IsTrue(AnimatorPlayableGameObject.AnimatorPlayableObject.AllAnimationLayersCurrentlyPlaying.Count == 1);
            Assert.IsTrue(AnimatorPlayableGameObject.AnimatorPlayableObject.AnimationLayerMixerPlayable.GetInputCount() == 1);
            var SequencedAnimationLayer = AnimatorPlayableGameObject.AnimatorPlayableObject.AllAnimationLayersCurrentlyPlaying[0] as SequencedAnimationLayer;

            Assert.IsTrue(SequencedAnimationLayer.AnimationMixerPlayable.GetInputWeight(0) == 1f);
            yield return(null);

            Assert.IsTrue(AnimatorPlayableGameObject.AnimatorPlayableObject.AnimationLayerMixerPlayable.GetInputWeight(0) < 1f);
            yield return(new WaitForSeconds(endTransitionTime));

            Assert.IsTrue(AnimatorPlayableGameObject.AnimatorPlayableObject.AllAnimationLayersCurrentlyPlaying.Count == 0);
            Assert.IsTrue(AnimatorPlayableGameObject.AnimatorPlayableObject.AnimationLayerMixerPlayable.GetInputCount() == 0);
        }
        public void EnumerableTest()
        {
            var buffer   = BuildBuffer();
            var expected = new int[BufferSize];
            var index    = 0;

            for (var i = BufferSize / 2; i < BufferSize; i++)
            {
                expected[index++] = i;
            }

            for (var i = 0; i < BufferSize / 2; i++)
            {
                expected[index++] = i;
            }

            var actual = buffer.ToArray();

            Assert.IsTrue(
                expected.SequenceEqual(actual),
                $"Expected: [{string.Join(", ", expected)}] but got [{string.Join(", ", actual)}]"
                );
        }
        private IEnumerator VerifyCompressionSupport(string url)
        {
            yield return(new WaitForEndOfFrame());

            var request = (HttpWebRequest)WebRequest.Create(url);

            request.AutomaticDecompression = DecompressionMethods.GZip;
            var result = request.BeginGetResponse(null, null);

            yield return(new WaitForIAsyncResult(result));

            NAssert.DoesNotThrow(() =>
            {
                using (var response = (HttpWebResponse)request.EndGetResponse(result))
                {
                    Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Unexpected HTTP response code");
                    var encoding = response.ContentEncoding.ToLower();
                    Assert.IsTrue(encoding.Contains("gzip"),
                                  string.Format("Expected: {0}, Actual: {1}", "gzip", encoding));
                }
            });
            yield return(new WaitForEndOfFrame());
        }
Exemple #16
0
        public void EvaluateShadowVisibility()
        {
            // Arrange
            var profile = new CullingControllerProfile();

            profile.shadowMapProjectionSizeThreshold = 6;
            profile.shadowRendererSizeThreshold      = 20;
            profile.shadowDistanceThreshold          = 15;

            // Act
            var nearTest          = CullingControllerUtils.TestRendererShadowRule(profile, 1, 5, 10);
            var nearButSmallTexel = CullingControllerUtils.TestRendererShadowRule(profile, 1, 5, 1);
            var farAndBigEnough   = CullingControllerUtils.TestRendererShadowRule(profile, 30, 30, 30);
            var farAndSmall       = CullingControllerUtils.TestRendererShadowRule(profile, 10, 30, 30);
            var farAndSmallTexel  = CullingControllerUtils.TestRendererShadowRule(profile, 10, 30, 1);

            // Assert
            Assert.IsTrue(nearTest);
            Assert.IsTrue(farAndBigEnough);
            Assert.IsFalse(nearButSmallTexel);
            Assert.IsFalse(farAndSmall);
            Assert.IsFalse(farAndSmallTexel);
        }
        public unsafe void RigidBodyCalculateDistancePointTest()
        {
            Physics.RigidBody rigidbody = Unity.Physics.RigidBody.Zero;

            const float size         = 1.0f;
            const float convexRadius = 0.0f;

            var queryPos = new float3(-10, -10, -10);

            rigidbody.Collider = (Collider *)BoxCollider.Create(new BoxGeometry
            {
                Center      = float3.zero,
                Orientation = quaternion.identity,
                Size        = size,
                BevelRadius = convexRadius
            }).GetUnsafePtr();

            var pointDistanceInput = new PointDistanceInput();

            pointDistanceInput.Position = queryPos;
            pointDistanceInput.Filter   = CollisionFilter.Default;

            var closestHit = new DistanceHit();
            var allHits    = new NativeList <DistanceHit>(Allocator.Temp);

            // OK case : with enough max distance
            pointDistanceInput.MaxDistance = 10000.0f;
            Assert.IsTrue(rigidbody.CalculateDistance(pointDistanceInput));
            Assert.IsTrue(rigidbody.CalculateDistance(pointDistanceInput, out closestHit));
            Assert.IsTrue(rigidbody.CalculateDistance(pointDistanceInput, ref allHits));

            // Fail case : not enough max distance
            pointDistanceInput.MaxDistance = 1;
            Assert.IsFalse(rigidbody.CalculateDistance(pointDistanceInput));
            Assert.IsFalse(rigidbody.CalculateDistance(pointDistanceInput, out closestHit));
            Assert.IsFalse(rigidbody.CalculateDistance(pointDistanceInput, ref allHits));
        }
        public unsafe void BuildTreeAndOverlap([Values(2, 10, 33, 100)] int elementCount)
        {
            elementCount *= 2;
            int numNodes = elementCount / 3 * 2 + 4;
            var points   = new NativeArray <PointAndIndex>(elementCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
            var aabbs    = new NativeArray <Aabb>(elementCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
            var filters  = new NativeArray <CollisionFilter>(elementCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory);

            InitInputWithCopyArrays(points, aabbs, filters);

            var nodes = new NativeArray <Node>(numNodes, Allocator.Temp, NativeArrayOptions.UninitializedMemory);

            var bvh = new BoundingVolumeHierarchy(nodes);

            bvh.Build(points, aabbs, out int numNodesOut);
            bvh.CheckIntegrity();

            var buffer = new PairBuffer {
                Pairs = new List <BodyIndexPair>()
            };

            buffer.MaxId = elementCount - 1;

            Node *nodesPtr = (Node *)nodes.GetUnsafePtr();

            BoundingVolumeHierarchy.TreeOverlap(ref buffer, nodesPtr, nodesPtr);

            int numCollidingPairs = buffer.Pairs.Count;

            Debug.Log($"Num colliding pairs: {buffer.Pairs.Count}");
            Assert.IsTrue(elementCount / 2 == numCollidingPairs);

            filters.Dispose();
            points.Dispose();
            aabbs.Dispose();
            nodes.Dispose();
        }
        public IEnumerator TestJoystickRotation()
        {
            InstantiateJoystick(out JoystickController joystick, out Transform grabber);
            Assert.IsNotNull(joystick);
            Assert.IsNotNull(grabber);

            yield return(null);

            // Switch the joystick mode to 'rotate'.
            joystick.Mode = JoystickMode.Rotate;

            // Instantiate large object and set as target.
            var targetObject = GameObject.CreatePrimitive(PrimitiveType.Cube);

            targetObject.transform.localScale = 7.0f * Vector3.one;
            joystick.TargetObject             = targetObject;

            Quaternion startRotation, endRotation;

            // Capture the starting rotation of the target object.
            startRotation = targetObject.transform.rotation;

            // Tilt the joystick to the right.
            joystick.StartDrag();
            grabber.localPosition += 2.5f * Vector3.right;

            // Wait a short while, then capture once again the rotation of the target object.
            yield return(new WaitForSecondsRealtime(1.5f));

            endRotation = targetObject.transform.rotation;

            // Untilt the joystick.
            grabber.localPosition += 2.5f * Vector3.left;
            joystick.StopDrag();

            Assert.IsTrue(Quaternion.Angle(startRotation, endRotation) > 0.0f);
        }
Exemple #20
0
        public void WhenDispatchRestartGameSignal_RestartGallow()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <RestartGameSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var isEnabledObserver = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsGallowPartVisible.Clear();
            var gallowImageProperty = _inGameViewModel.SubscribeGallowImage();
            var inGamePresenter     = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            gallowImageProperty.Subscribe(isEnabledObserver);
            gallowImageProperty.Value             = true;
            _inGameViewModel.NextGallowPartToShow = 2;

            Assert.AreNotEqual(0, _inGameViewModel.NextGallowPartToShow);
            Assert.IsTrue(gallowImageProperty.Value);
            callback(new RestartGameSignal());

            Assert.AreEqual(0, _inGameViewModel.NextGallowPartToShow);
            isEnabledObserver.Received().OnNext(false);
        }
Exemple #21
0
        public void TestSort3d()
        {
            SurfaceConstraintInfo plane1 = CreateConstraint(ColliderKey.Empty, float3.zero, new float3(0, 1, 0), 1, 0, 0, false, float3.zero);
            SurfaceConstraintInfo plane2 = CreateConstraint(ColliderKey.Empty, float3.zero, new float3(0, 1, 0), 1, 1, 0, false, float3.zero);
            SurfaceConstraintInfo plane3 = CreateConstraint(ColliderKey.Empty, float3.zero, new float3(0, 1, 0), 1, 2, 0, false, float3.zero);

            // Leftmost plane should have smallest priority after the sort
            Sort3d(ref plane1, ref plane2, ref plane3);
            Assert.IsTrue(plane1.Priority < plane2.Priority &&
                          plane2.Priority < plane3.Priority);

            // Leftmost plane should have smallest priority after the sort
            Sort3d(ref plane1, ref plane3, ref plane2);
            Assert.IsTrue(plane1.Priority < plane3.Priority &&
                          plane3.Priority < plane2.Priority);

            // Leftmost plane should have smallest priority after the sort
            Sort3d(ref plane2, ref plane1, ref plane3);
            Assert.IsTrue(plane2.Priority < plane1.Priority &&
                          plane1.Priority < plane3.Priority);

            // Leftmost plane should have smallest priority after the sort
            Sort3d(ref plane2, ref plane3, ref plane1);
            Assert.IsTrue(plane2.Priority < plane3.Priority &&
                          plane3.Priority < plane1.Priority);

            // Leftmost plane should have smallest priority after the sort
            Sort3d(ref plane3, ref plane1, ref plane2);
            Assert.IsTrue(plane3.Priority < plane1.Priority &&
                          plane1.Priority < plane2.Priority);

            // Leftmost plane should have smallest priority after the sort
            Sort3d(ref plane3, ref plane2, ref plane1);
            Assert.IsTrue(plane3.Priority < plane2.Priority &&
                          plane2.Priority < plane1.Priority);
        }
Exemple #22
0
        public void TileData_HasFlag()
        {
            _tileData.Initialize();

            // HasFlagのチェック
            _tileData.AddFlag(TileFlag.Wall);

            Assert.IsTrue(_tileData.HasFlag(TileFlag.Wall), "Wall指定でtrueになる");
            Assert.IsFalse(_tileData.HasFlag(TileFlag.StepUp), "StepUpはAddしてないのでFalse");
            Assert.IsFalse(_tileData.HasFlag(TileFlag.StepDown), "StepDownはAddしてないのでFalse");

            // StepUpをAddしたらWallもStepUpもTrueになる
            _tileData.AddFlag(TileFlag.StepUp);

            Assert.IsTrue(_tileData.HasFlag(TileFlag.Wall), "Wallはtrueのまま");
            Assert.IsTrue(_tileData.HasFlag(TileFlag.StepUp), "StepUpがAddされたのでTrue");
            Assert.IsFalse(_tileData.HasFlag(TileFlag.StepDown), "StepDownはAddされてないのでFlase");

            // Initializeしたらフラグも初期化される
            _tileData.Initialize();

            Assert.AreEqual(_tileData.Flag, TileFlag.None, "InitializeしたらNoneになる");
            Assert.IsFalse(_tileData.HasFlag(TileFlag.Wall), "InitializeしたらWallもFalseになる");
        }
        public virtual void BeforeTest()
        {
            // Make sure we are not running
            if (OpenXRLoaderBase.Instance != null)
            {
                StopAndShutdown();
            }

            // Cache off the features before we start
            savedFeatures = (OpenXRFeature[])OpenXRSettings.Instance.features.Clone();

            // Disable all features to make sure the feature list is clean before tests start.
            DisableAllFeatures();

            // Enable the mock runtime and reset it back to default state
            Assert.IsTrue(EnableMockRuntime());
            MockRuntime.ResetDefaults();
            OpenXRRuntime.ClearEvents();
            OpenXRRestarter.Instance.ResetCallbacks();

#pragma warning disable CS0618
            loader = XRGeneralSettings.Instance?.Manager?.loaders[0] as OpenXRLoader;
#pragma warning restore CS0618
        }
        public IEnumerator MoveToAreaWithEnumeratorPasses()
        {
            GameObject targetObj = new GameObject();

            targetObj.AddComponent <Target>();
            targetObj.transform.position = new Vector3(5, 5, 5);

            yield return(null);

            GameObject managerObj = new GameObject();
            var        manager    = managerObj.AddComponent <ObjectiveManager>();
            var        objective  = managerObj.AddComponent <MoveToArea>();

            manager.AddObjective(objective);
            managerObj.transform.position = Vector3.zero;

            Assert.IsFalse(objective.IsCompleted());
            Assert.AreEqual(manager.Objectives.Count, 1);
            yield return(new WaitForSeconds(1f));

            managerObj.transform.position = targetObj.transform.position;
            Assert.IsTrue(objective.IsCompleted());
            yield return(null);
        }
Exemple #25
0
        public void TestLeftHandedUsdMeshImport(BasisTransformation basisTransformation)
        {
            // set the baked mesh according to the basis transformation
            Object bakedLeftHandedMesh = null;

            switch (basisTransformation)
            {
            case BasisTransformation.SlowAndSafe:
                bakedLeftHandedMesh = bakedLeftHandedCube_slowAndSafe;
                break;

            case BasisTransformation.SlowAndSafeAsFBX:
                bakedLeftHandedMesh = bakedLeftHandedCube_slowAndSafeAsFbx;
                break;

            case BasisTransformation.None:
            case BasisTransformation.FastWithNegativeScale:
                // When comparing the mesh, importing with FastWithNegativeScale and None
                // will give the same result.
                bakedLeftHandedMesh = bakedLeftHandedCube_none;
                break;

            default:
                throw new System.NotImplementedException();
            }

            var rightHandedUsdRoot = LoadUSD(withCameraUsd, basisTransformation);

            Assert.IsNotNull(rightHandedUsdRoot);

            // Compare import of Left handed USD to right handed USD
            var leftHandedUsdRoot = LoadUSD(leftHandedWithCameraUsd, basisTransformation);

            Assert.IsNotNull(leftHandedUsdRoot);

            // check that the mesh does not match the right handed one
            var usdCube = rightHandedUsdRoot.transform.Find("group2/group1/pCube1");

            Assert.IsNotNull(usdCube);
            var leftHandedUsdCube = leftHandedUsdRoot.transform.Find("group2/group1/pCube1");

            Assert.IsNotNull(leftHandedUsdCube);

            var cubeMesh           = usdCube.GetComponent <MeshFilter>().sharedMesh;
            var leftHandedCubeMesh = leftHandedUsdCube.GetComponent <MeshFilter>().sharedMesh;

            // The two files are different handedness (different winding order of vertices), therefore the triangles
            // will be different, the vertices will remain the same and the normals will be flipped.
            NUnit.Framework.Assert.That(leftHandedCubeMesh.vertices.Length, Is.EqualTo(cubeMesh.vertices.Length));
            for (int i = 0; i < cubeMesh.vertices.Length; i++)
            {
                Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.vertices[i], cubeMesh.vertices[i]),
                              string.Format("Vertex at index {0} of left and right handed cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}",
                                            i, cubeMesh.vertices[i], leftHandedCubeMesh.vertices[i]));
            }
            NUnit.Framework.Assert.That(cubeMesh.triangles, Is.Not.EqualTo(leftHandedCubeMesh.triangles));

            NUnit.Framework.Assert.That(leftHandedCubeMesh.normals.Length, Is.EqualTo(cubeMesh.normals.Length));
            for (int i = 0; i < cubeMesh.normals.Length; i++)
            {
                // check that normals are flipped
                Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.normals[i], -cubeMesh.normals[i]),
                              string.Format("Normal at index {0} of left and right handed cube mesh are not equal, expected equal\nExpected:{1}\nActual:{2}",
                                            i, -cubeMesh.normals[i], leftHandedCubeMesh.normals[i]));
            }

            // Check that the imported left handed cube matches the baked cube.
            var bakedCubeMesh = bakedLeftHandedMesh as Mesh;

            Assert.IsNotNull(bakedCubeMesh);

            NUnit.Framework.Assert.That(leftHandedCubeMesh.vertices.Length, Is.EqualTo(bakedCubeMesh.vertices.Length));
            for (int i = 0; i < bakedCubeMesh.vertices.Length; i++)
            {
                Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.vertices[i], bakedCubeMesh.vertices[i]),
                              string.Format("Vertex at index {0} of left handed and baked cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}",
                                            i, bakedCubeMesh.vertices[i], leftHandedCubeMesh.vertices[i]));
            }
            NUnit.Framework.Assert.That(bakedCubeMesh.triangles, Is.EqualTo(leftHandedCubeMesh.triangles));

            NUnit.Framework.Assert.That(leftHandedCubeMesh.normals.Length, Is.EqualTo(bakedCubeMesh.normals.Length));
            for (int i = 0; i < bakedCubeMesh.normals.Length; i++)
            {
                Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.normals[i], bakedCubeMesh.normals[i]),
                              string.Format("Normal at index {0} of left handed and baked cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}",
                                            i, bakedCubeMesh.normals[i], leftHandedCubeMesh.normals[i]));
            }
        }
Exemple #26
0
 public static void AreEqual(double a, double b, double delta = 0.0)
 {
     Assert.IsTrue(math.abs(a - b) < delta);
 }
 /// <summary>
 /// Assert whether this range is valid
 /// </summary>
 /// <exception cref="ArgumentException"></exception>
 public void Validate()
 {
     Assert.IsTrue(minimum <= maximum);
 }
        public void DisableSharedFeaturesLeaveOthersFeaturesEnabled()
        {
            string[] allFeatureIds = new string[] {
                MicrosoftHandInteraction.featureId,
                EyeGazeInteraction.featureId,
                MicrosoftMotionControllerProfile.featureId,
            };

            string[] otherFeatureIds = new string[] {
                MicrosoftMotionControllerProfile.featureId,
            };

            OpenXRFeatureSetManager.InitializeFeatureSets(true);
            var extInfo = FeatureHelpersInternal.GetAllFeatureInfo(BuildTargetGroup.WSA);

            foreach (var ext in extInfo.Features)
            {
                Assert.IsFalse(ext.Feature.enabled);
                if (Array.IndexOf(otherFeatureIds, ext.Attribute.FeatureId) > -1)
                {
                    ext.Feature.enabled = true;
                }
            }

            var featureSetToEnable = OpenXRFeatureSetManager.GetFeatureSetInfoWithId(BuildTargetGroup.WSA, k_TestFeatureSetIdTwo);

            featureSetToEnable.isEnabled  = true;
            featureSetToEnable.wasChanged = true;
            OpenXRFeatureSetManager.SetFeaturesFromEnabledFeatureSets(BuildTargetGroup.WSA);

            foreach (var ext in extInfo.Features)
            {
                if (Array.IndexOf(allFeatureIds, ext.Attribute.FeatureId) >= 0)
                {
                    Assert.IsTrue(ext.Feature.enabled);
                }
                else
                {
                    Assert.IsFalse(ext.Feature.enabled);
                }
            }

            var featureSetToDisable = OpenXRFeatureSetManager.GetFeatureSetInfoWithId(BuildTargetGroup.WSA, k_TestFeatureSetIdTwo);

            Assert.IsNotNull(featureSetToDisable);
            featureSetToDisable.isEnabled  = false;
            featureSetToDisable.wasChanged = true;
            OpenXRFeatureSetManager.SetFeaturesFromEnabledFeatureSets(BuildTargetGroup.WSA);

            foreach (var ext in extInfo.Features)
            {
                if (Array.IndexOf(otherFeatureIds, ext.Attribute.FeatureId) >= 0)
                {
                    Assert.IsTrue(ext.Feature.enabled);
                }
                else
                {
                    Assert.IsFalse(ext.Feature.enabled);
                }
            }
        }
        private void Export(AssetInfo asset, Entity entity, BuildPipeline.BuildContext context)
        {
            // Get asset exporter
            var assetExporter = m_AssetExporters.Values.FirstOrDefault(x => x.CanExport(asset.Object));

            if (assetExporter == null)
            {
                return; // Assets without asset exporter do not need to export anything
            }

            // Get asset path
            var assetPath = UnityEditor.AssetDatabase.GetAssetPath(asset.Object);

            if (string.IsNullOrEmpty(assetPath))
            {
                assetPath = string.Empty;
            }

            // Compute asset export file path
            Assert.IsTrue(EntityManager.HasComponent <EntityGuid>(entity));
            var assetGuid  = WorldManager.GetEntityGuid(entity);
            var outputFile = context.DataDirectory.GetFile(assetGuid.ToString("N"));

            // Compute asset export hash
            var exportHash = assetExporter.GetExportHash(asset.Object);

            if (exportHash == Guid.Empty)
            {
                throw new InvalidOperationException($"{assetExporter.GetType().FullName} did not provide a valid asset export hash.");
            }

            // Retrieve exported files from manifest
            IEnumerable <FileInfo> exportedFiles = null;
            var manifestFile = new FileInfo(outputFile.FullName + ".manifest");

            if (manifestFile.Exists)
            {
                try
                {
                    var manifest = JsonSerialization.Deserialize <BuildManifest.Entry>(manifestFile.FullName);
                    if (manifest != null &&
                        manifest.AssetPath == assetPath &&
                        manifest.AssetGuid == assetGuid &&
                        manifest.ExportVersion == assetExporter.ExportVersion &&
                        manifest.ExportHash == exportHash)
                    {
                        // Verify that all files exists
                        var files = manifest.ExportedFiles.Select(x => new FileInfo(x));
                        if (files.Where(file => file.Exists).Count() == manifest.ExportedFiles.Count)
                        {
                            exportedFiles = files;
                        }
                    }
                }
                catch (InvalidJsonException)
                {
                    // Manifest file couldn't be read, format might have changed
                }
            }

            // Export asset if export files are not found
            var didExport = false;

            if (exportedFiles == null)
            {
                exportedFiles = assetExporter.Export(outputFile, asset.Object);
                didExport     = exportedFiles != null && exportedFiles.Count() > 0;
            }

            // Update manifest
            var entry = context.Manifest.Add(assetGuid, assetPath, exportedFiles, assetExporter.ExportVersion, exportHash);

            if (entry != null && didExport)
            {
                manifestFile.WriteAllText(JsonSerialization.Serialize(entry));
            }
        }
Exemple #30
0
        public IEnumerator ProximityOnScaleHandles()
        {
            var boundsControl = InstantiateSceneAndDefaultBoundsControl();

            yield return(VerifyInitialBoundsCorrect(boundsControl));

            // 1. test no proximity scaling active per default
            ScaleHandlesConfiguration scaleHandleConfig = boundsControl.ScaleHandlesConfiguration;
            Vector3 defaultHandleSize = Vector3.one * scaleHandleConfig.HandleSize;

            Vector3 initialHandPosition = new Vector3(0, 0, 0f);
            // this is specific to scale handles
            Transform scaleHandle           = boundsControl.gameObject.transform.Find("rigRoot/corner_3");
            Transform proximityScaledVisual = scaleHandle.GetChild(0)?.GetChild(0);
            var       frontRightCornerPos   = scaleHandle.position; // front right corner is corner

            Assert.IsNotNull(proximityScaledVisual, "Couldn't get visual gameobject for scale handle");
            Assert.IsTrue(proximityScaledVisual.name == "visuals", "scale visual has unexpected name");

            yield return(null);

            // verify no proximity scaling applied per default
            Assert.AreEqual(proximityScaledVisual.localScale, defaultHandleSize, "Handle was scaled even though proximity effect wasn't active");
            TestHand hand         = new TestHand(Handedness.Left);
            Vector3  initialScale = boundsControl.transform.localScale;

            // Hands grab object at initial position
            yield return(hand.Show(initialHandPosition));

            yield return(hand.SetGesture(ArticulatedHandPose.GestureId.OpenSteadyGrabPoint));

            yield return(hand.MoveTo(frontRightCornerPos));

            yield return(null);

            // we're in poximity scaling range - check if proximity scaling wasn't applied
            Assert.AreEqual(proximityScaledVisual.localScale, defaultHandleSize, "Handle was scaled even though proximity effect wasn't active");

            //// reset hand
            yield return(hand.MoveTo(initialHandPosition));

            // 2. enable proximity scaling and test defaults
            ProximityEffectConfiguration proximityConfig = boundsControl.HandleProximityEffectConfiguration;

            proximityConfig.ProximityEffectActive = true;
            proximityConfig.CloseGrowRate         = 1.0f;
            proximityConfig.MediumGrowRate        = 1.0f;
            proximityConfig.FarGrowRate           = 1.0f;
            boundsControl.CreateRig();
            yield return(null); // wait so rig gameobjects get recreated

            yield return(TestCurrentProximityConfiguration(boundsControl, hand, "Defaults"));

            // reset hand
            yield return(hand.MoveTo(initialHandPosition));

            // 3. now test custom configuration is applied during runtime
            proximityConfig.CloseScale  = 4.0f;
            proximityConfig.MediumScale = 3.0f;
            proximityConfig.FarScale    = 2.0f;

            proximityConfig.ObjectMediumProximity = 0.2f;
            proximityConfig.ObjectCloseProximity  = 0.1f;

            boundsControl.CreateRig();
            yield return(null); // wait so rig gameobjects get recreated

            yield return(TestCurrentProximityConfiguration(boundsControl, hand, "Custom runtime config max"));
        }