コード例 #1
0
    protected override void OnUpdate()
    {
        Entity grid;

        using (var tmp = mGridQuery.ToEntityArray(Allocator.TempJob))
            grid = tmp.Length > 0 ? tmp[0] : Entity.Null;

        Debug.Assert(grid != Entity.Null);

        var cellSize      = EntityManager.GetComponentData <CGridCellSize>(grid).Value;
        var cellCount     = EntityManager.GetComponentData <CGridCellCount>(grid).Value;
        var gridPos       = EntityManager.GetComponentData <CGridPos>(grid).Value;
        var stackHeights  = EntityManager.GetBuffer <BStackHeights>(grid);
        var floorStart    = -Settings.Instance.FieldSize.y * 0.5f;
        var resourcesSize = Settings.Instance.ResourceSize;

        var ecb = mCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();

        Entities
        .WithAll <TResource>()
        .WithNone <CHeldBy, CStackHeight>()
        .ForEach((Entity e, int entityInQueryIndex, ref Translation translation, ref CVelocity velocity, in CGridIndex idx) =>
        {
            var cellStackIdx = idx.Value.y * cellCount.x + idx.Value.x;
            var stackHeight  = stackHeights[cellStackIdx].Value;
            var floorHeight  = floorStart + (stackHeight + 0.5f) * resourcesSize;

            if (translation.Value.y < floorHeight)
            {
                if (floorHeight + resourcesSize < -floorStart)
                {
                    translation.Value = new float3(translation.Value.xz, floorHeight).xzy;
                    velocity.Value    = float3.zero;
                    ecb.AddComponent(entityInQueryIndex, e, new CStackHeight {
                        Value = stackHeight++
                    });
                    stackHeights[cellStackIdx] = new BStackHeights {
                        Value = stackHeight
                    };
                }
                else
                {
                    ecb.DestroyEntity(entityInQueryIndex, e);
                }
            }
        })
        .Schedule();
        mCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
コード例 #2
0
        /// <summary>
        /// Determines if the target application is running on the target device.
        /// </summary>
        /// <param name="appInfo">Optional cached <see cref="Microsoft.MixedReality.Toolkit.WindowsDevicePortal.ApplicationInfo"/>.</param>
        /// <returns>True, if the application is running.</returns>
        public static async Task <bool> IsAppRunningAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogError($"{packageName} not installed.");
                return(false);
            }

            var response = await Rest.GetAsync(string.Format(ProcessQuery, FinalizeUrl(targetDevice.IP)), targetDevice.Authorization);

            if (response.Successful)
            {
                var processList = JsonUtility.FromJson <ProcessList>(response.ResponseBody);
                for (int i = 0; i < processList.Processes.Length; ++i)
                {
                    if (processList.Processes[i].ImageName.Contains(appInfo.Name))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
            {
                return(await IsAppRunningAsync(packageName, targetDevice, appInfo));
            }

            Debug.LogError($"{response.ResponseBody}");
            return(false);
        }
コード例 #3
0
        /// <summary>
        /// Uninstalls the target application on the target device
        /// </summary>
        /// <param name="appInfo">Optional cached <see cref="Microsoft.MixedReality.Toolkit.WindowsDevicePortal.ApplicationInfo"/>.</param>
        /// <returns>True, if uninstall was a success.</returns>
        public static async Task <bool> UninstallAppAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return(false);
            }

            Debug.Log($"Attempting to uninstall {packageName} on {targetDevice.MachineName}...");

            string query    = $"{string.Format(InstallQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(appInfo.PackageFullName)}";
            var    response = await Rest.DeleteAsync(query, targetDevice.Authorization);

            if (response.Successful)
            {
                Debug.Log($"Successfully uninstalled {packageName} on {targetDevice.MachineName}.");
            }
            else
            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return(await UninstallAppAsync(packageName, targetDevice));
                }

                Debug.LogError($"Failed to uninstall {packageName} on {targetDevice.MachineName}");
                Debug.LogError(response.ResponseBody);
                return(false);
            }

            return(true);
        }
コード例 #4
0
        public void RegisterDeadSheep(Sheep deadSheep, Player fromPlayer)
        {
            Debug.Assert(!deadSheep.IsAlive);

            KilledSheep += 1;

            SoundPlayer.Instance.Play(Sound.SheepHit, deadSheep.AudioSource);

            if (Master.Instance.CurrentDifficulty == Difficulty.Easy)
            {
                WakeUpSheep(fromPlayer);
            }

            int sheepAlive = 0;

            foreach (Sheep sheep in _sheep)
            {
                if (sheep.IsAlive)
                {
                    sheepAlive += 1;
                }
            }

            if (sheepAlive > 0)
            {
                Coin    coin    = Instantiate(_coinPrefab, deadSheep.transform.position, Quaternion.identity);
                Vector2 coinVec = (coin.transform.position - fromPlayer.transform.position).normalized;

                coin.Rigidbody.AddForce(coinVec * Random.Range(3f, 10f), ForceMode2D.Impulse);
            }

            if (sheepAlive == 0)
            {
                _levelTime.Stop();
                _levelDone = true;
                MainWindow.Instance.RunTimelineLevelWon();
            }
        }
コード例 #5
0
    protected override void Awake()
    {
        base.Awake();
        _mainCamera = Camera.main;

        _offsetOnPullToCamera = GalaxyExplorerManager.ForcePullToCamFixedDistance;

        _manipulationHandler = ManipulationHandler ? ManipulationHandler : GetComponentInChildren <ManipulationHandler>();
        Debug.Assert(_manipulationHandler != null, "Force Solver failed to find a manipulation handler");
        _attractionCollider = AttractionCollider ? AttractionCollider : GetComponentInChildren <Collider>();
        Debug.Assert(_attractionCollider != null, "Force Solver failed to find a attraction collider");

        _manipulationHandler.OnManipulationEnded.AddListener(OnManipulationEnd);

        if (ControllerTracker == null)
        {
            Debug.LogWarning(gameObject.name + " ForceSolver no controller tracker transform supplied will instantiate locally");
            var controllerTrackerObject = new GameObject(gameObject.name + " ForceSolver autogenerated controller tracker");
            ControllerTracker = controllerTrackerObject.AddComponent <ControllerTransformTracker>();
        }

        ControllerTracker.AllTrackingLost += OnControllersLost;
    }
コード例 #6
0
        /// <summary>
        /// Decompose the polygon into several smaller non-concave polygon.
        /// If the polygon is already convex, it will return the original polygon, unless it is over MaxPolygonVertices.
        /// </summary>
        public static Vector2[][] ConvexPartition(List <Vector2> vertices)
        {
            Debug.Assert(vertices.Count > 3);

            if (!IsCounterClockWise(vertices))
            {
                vertices.Reverse();
            }

            var result = TriangulatePolygon(vertices);

            if (result == null)
            {
                return(null);
            }
            var returnValue = new Vector2[result.Count][];

            for (int i = 0; i < result.Count; i++)
            {
                returnValue[i] = result[i].ToArray();
            }
            return(returnValue);
        }
コード例 #7
0
        /// <summary>Deletes a file.</summary>
        public static bool DeleteFile(string filePath)
        {
            Debug.Assert(!String.IsNullOrEmpty(filePath));

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                return(true);
            }
            catch (Exception e)
            {
                string warningInfo = ("[mod.io] Failed to delete file."
                                      + "\nFile: " + filePath + "\n\n");

                Debug.LogWarning(warningInfo
                                 + Utility.GenerateExceptionDebugString(e));
            }

            return(false);
        }
コード例 #8
0
        internal bool AttachToParentAt(ref IDManager hierarchyIDLookup, NativeList <CompactHierarchy> hierarchies, ref IDManager nodeIDLookup, NativeList <CompactNodeID> nodes, CompactNodeID parentID, int index, CompactNodeID compactNodeID)
        {
            Debug.Assert(IsCreated);

            if (index < 0)
            {
                Debug.LogError("The index must be positive");
                return(false);
            }
            var parentIndex = HierarchyIndexOfInternal(parentID);

            if (parentIndex == -1)
            {
                throw new ArgumentException(nameof(parentID), $"{nameof(parentID)} is invalid");
            }

            if (!IsValidCompactNodeID(compactNodeID))
            {
                return(false);
            }

            return(AttachInternal(ref hierarchyIDLookup, hierarchies, ref nodeIDLookup, nodes, parentID, parentIndex, index, compactNodeID));
        }
コード例 #9
0
        public void RegisterDeadPlayer(Player deadPlayer)
        {
            Debug.Assert(!deadPlayer.IsAlive);

            SoundPlayer.Instance.Play(Sound.PlayerHit, deadPlayer.AudioSource);

            int playersAlive = 0;

            foreach (Player player in _players)
            {
                if (player.IsAlive)
                {
                    playersAlive += 1;
                }
            }

            if (playersAlive == 0)
            {
                _levelTime.Stop();
                _levelDone = true;
                MainWindow.Instance.RunTimelineLevelFailed();
            }
        }
コード例 #10
0
        public NodeID GetNodeIDNoErrors(CompactNodeID compactNodeID)
        {
            int nodeIndex;

            Debug.Assert(IsCreated);
            if (compactNodeID == CompactNodeID.Invalid)
            {
                return(NodeID.Invalid);
            }

            nodeIndex = HierarchyIndexOfInternalNoErrors(compactNodeID);
            if (nodeIndex == -1)
            {
                return(NodeID.Invalid);
            }

            if (nodeIndex < 0 || nodeIndex >= compactNodes.Length)
            {
                return(NodeID.Invalid);
            }

            return(compactNodes[nodeIndex].nodeID);
        }
コード例 #11
0
        private int AddLeaf(int parent, ItemEntry item)
        {
            Debug.Assert(parent >= 0);
            Debug.Assert(parent % NodeSize == 0);
            Debug.Assert(parent < nodeCount * NodeSize);
            Debug.Assert(leafCount >= 0);
            Debug.Assert(leafCount <= leafs.Length);

            if (leafCount == leafs.Length)
            {
                // Grow the array to accomodate more leafs
                var newLeafs = new OctreeLeaf[leafs.Length * 2];
                leafs.CopyTo(newLeafs, 0);
                leafs = newLeafs;
            }

            ItemEntry[] leafContent;
            var         cache = ContentCache[0];

            if (cache.Count > 0)
            {
                // Extract the item container from the cache
                leafContent = cache[cache.Count - 1];
                cache.RemoveAt(cache.Count - 1);
            }
            else
            {
                // Cache is empty, create a new container
                leafContent = new ItemEntry[DefaultLeafCapacity];
            }

            leafContent[0]   = item;
            leafs[leafCount] = new OctreeLeaf(parent, leafContent, 1);
            leafCount++;

            return(-leafCount);  // Leafs have negative indexing starting at -1
        }
コード例 #12
0
    public static JSONObj Create <T>(T val)
    {
        JSONObj obj = new JSONObj();

        switch (System.Type.GetTypeCode(val.GetType()))
        {
        case System.TypeCode.Byte:
        case System.TypeCode.SByte:
        case System.TypeCode.UInt16:
        case System.TypeCode.UInt32:
        case System.TypeCode.Int16:
        case System.TypeCode.Int32:
        case System.TypeCode.Int64:
            obj = JSONObj.Create(System.Convert.ToInt64(val));
            break;

        case System.TypeCode.Decimal:
        case System.TypeCode.Double:
        case System.TypeCode.Single:
            obj = JSONObj.Create(System.Convert.ToSingle(val));
            break;

        case System.TypeCode.Boolean:
            obj = JSONObj.Create(System.Convert.ToBoolean(val));
            break;

        case System.TypeCode.UInt64:
            Debug.Assert(true, "UInt64 unsupported");
            break;

        default:
            obj = JSONObj.CreateStringObject(val.ToString());
            break;
        }

        return(obj);
    }
コード例 #13
0
        /// Upload a file to Drive. Make sure mimetype and parents are specified.
        public async Task UploadFileAsync(DriveData.File file, Stream dataStream,
                                          CancellationToken token, IProgress <long> progress = null)
        {
            Debug.Assert(file.Parents != null);
            Debug.Assert(dataStream.CanSeek);
            var uploader = m_DriveService.Files.Create(file, dataStream, file.MimeType);

            if (progress != null)
            {
                uploader.ProgressChanged += (p) => progress.Report(p.BytesSent);
            }
            long position = dataStream.Position;
            var  result   = await Retry(() => {
                dataStream.Seek(position, SeekOrigin.Begin);
                return(uploader.UploadAsync(token));
            });

            if (result.Status != UploadStatus.Completed && !token.IsCancellationRequested)
            {
                Debug.LogException(new DriveSync.DataTransferError("Google Drive new file upload failed.",
                                                                   result.Exception));
            }
            await RefreshFreeSpaceAsync(token);
        }
コード例 #14
0
        void CompleteTrackedRequests(bool allRequests = false)
        {
            int value;

            foreach (var kv in _requestsInFlight)
            {
                var req = kv.Key;
                var age = _frameCount - kv.Value;

                if (allRequests || AsyncRequest.maxAsyncRequestFrameAge > 0)
                {
                    if (req.started && !req.completed && age >= AsyncRequest.maxAsyncRequestFrameAge)
                    {
                        req.Complete();
                        Debug.Assert(req.completed == true);
                    }
                }

                if (req.completed)
                {
                    _requestsInFlight.TryRemove(req, out value);
                }
            }
        }
コード例 #15
0
        /// <summary>Reads an entire file and parses the JSON Object it contains.</summary>
        public static bool TryReadJsonObjectFile <T>(string filePath, out T jsonObject)
        {
            Debug.Assert(!String.IsNullOrEmpty(filePath));

            if (File.Exists(filePath))
            {
                try
                {
                    jsonObject = JsonConvert.DeserializeObject <T>(File.ReadAllText(filePath));
                    return(true);
                }
                catch (Exception e)
                {
                    string warningInfo = ("[mod.io] Failed to read json object from file."
                                          + "\nFile: " + filePath + "\n\n");

                    Debug.LogWarning(warningInfo
                                     + Utility.GenerateExceptionDebugString(e));
                }
            }

            jsonObject = default(T);
            return(false);
        }
コード例 #16
0
        /// <summary>Deletes a directory.</summary>
        public static bool DeleteDirectory(string directoryPath)
        {
            Debug.Assert(!String.IsNullOrEmpty(directoryPath));

            try
            {
                if (Directory.Exists(directoryPath))
                {
                    Directory.Delete(directoryPath, true);
                }

                return(true);
            }
            catch (Exception e)
            {
                string warningInfo = ("[mod.io] Failed to delete directory."
                                      + "\nDirectory: " + directoryPath + "\n\n");

                Debug.LogWarning(warningInfo
                                 + Utility.GenerateExceptionDebugString(e));
            }

            return(false);
        }
コード例 #17
0
        public VertexProgram(string varCompiledShaderPath)
        {
            UDebug.Assert(File.Exists(varCompiledShaderPath));

            var tempContent = File.ReadAllLines(varCompiledShaderPath);

            for (int i = 0; i < tempContent.Length; ++i)
            {
                var tempInfo = tempContent[i];
                if (!tempInfo.StartsWith(VertexTagStr, false, CultureInfo.InvariantCulture))
                {
                    continue;
                }

                var tempPlatform = tempInfo.Substring(VertexTagStr.Length, tempInfo.Length - VertexTagStr.Length - 1).Replace("\"", string.Empty);
                if (!_DisCompiledFun.TryGetValue(tempPlatform, out var tempDisFun))
                {
                    UDebug.LogWarningFormat("[VertexProgram] not support :[{0}]", tempPlatform);
                }

                i = tempDisFun(tempContent, i, out var tempCompiledPlatform, out var tempChannel);
                //_DisAssembly.Add();
            }
        }
コード例 #18
0
        public int AllocateRange(int length)
        {
            if (length < 0)
            {
                throw new ArgumentException("Length cannot be negative");
            }
            if (length == 0)
            {
                return(-1);
            }

            // TODO: have some way to quickly find a free section with a given size without going through ALL free sections

            // Since we alternate between free and allocated sections, we can quickly find all free sections by skipping the allocated sections
            for (int sectionIndex = firstElementFree ? 0 : 1; sectionIndex < sections.Length; sectionIndex += 2)
            {
                Debug.Assert(IsSectionFree(sectionIndex));

                var section = sections[sectionIndex];
                if (length > section.length)
                {
                    continue;
                }

                SetRange(sectionIndex, section.start, length, false);
                return(section.start);
            }

            // Create a new range at the end
            var lastSection = (sections.Length == 0) ? new Section {
            } : sections[sections.Length - 1];
            var offset      = lastSection.start + lastSection.length;

            SetRange(sections.Length, offset, length, false);
            return(offset);
        }
コード例 #19
0
        /// <summary>
        /// Launches the target application on the target device.
        /// </summary>
        /// <param name="appInfo">Optional cached <see cref="Microsoft.MixedReality.Toolkit.WindowsDevicePortal.ApplicationInfo"/>.</param>
        /// <returns>True, if application was successfully launched and is currently running on the target device.</returns>
        public static async Task <bool> LaunchAppAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return(false);
            }

            string query    = $"{string.Format(AppQuery, FinalizeUrl(targetDevice.IP))}?appid={UnityWebRequest.EscapeURL(appInfo.PackageRelativeId.EncodeTo64())}&package={UnityWebRequest.EscapeURL(appInfo.PackageFullName)}";
            var    response = await RestHelpers.Rest.PostAsync(query, targetDevice.Authorization, readResponseData : true, certificateHandler : DevicePortalCertificateHandler, disposeCertificateHandlerOnDispose : false);

            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return(await LaunchAppAsync(packageName, targetDevice));
                }

                Debug.LogError($"{response.ResponseCode}|{await response.GetResponseBody()}");
                return(false);
            }

            while (!await IsAppRunningAsync(packageName, targetDevice, appInfo))
            {
                await new WaitForSeconds(1f);
            }

            return(true);
        }
        /// <summary>
        /// Stops the target application on the target device.
        /// </summary>
        /// <param name="appInfo">Optional cached <see cref="Microsoft.MixedReality.Toolkit.WindowsDevicePortal.ApplicationInfo"/>.</param>
        /// <returns>true, if application was successfully stopped.</returns>
        public static async Task <bool> StopAppAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return(false);
            }

            string   query    = $"{string.Format(AppQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(appInfo.PackageFullName.EncodeTo64())}";
            Response response = await Rest.DeleteAsync(query, targetDevice.Authorization);

            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return(await StopAppAsync(packageName, targetDevice));
                }

                Debug.LogError(response.ResponseBody);
                return(false);
            }

            while (!await IsAppRunningAsync(packageName, targetDevice, appInfo))
            {
                await new WaitForSeconds(1f);
            }

            return(true);
        }
コード例 #21
0
        /// <summary>Loads an entire binary file as a byte array.</summary>
        public static bool TryLoadBinaryFile(string filePath, out byte[] output)
        {
            Debug.Assert(!String.IsNullOrEmpty(filePath));

            if (File.Exists(filePath))
            {
                try
                {
                    output = File.ReadAllBytes(filePath);
                    return(true);
                }
                catch (Exception e)
                {
                    string warningInfo = ("[mod.io] Failed to read binary file."
                                          + "\nFile: " + filePath + "\n\n");

                    Debug.LogWarning(warningInfo
                                     + Utility.GenerateExceptionDebugString(e));
                }
            }

            output = null;
            return(false);
        }
コード例 #22
0
        /// <summary>
        /// Adds capabilities according to the values in the buildInfo to the manifest file.
        /// </summary>
        /// <param name="buildInfo">An IBuildInfo containing a valid OutputDirectory and all capabilities</param>
        public static void AddCapabilities(IBuildInfo buildInfo, XElement rootElement = null)
        {
            var manifestFilePath = GetManifestFilePath(buildInfo);

            if (manifestFilePath == null)
            {
                throw new FileNotFoundException("Unable to find manifest file");
            }

            rootElement = rootElement ?? XElement.Load(manifestFilePath);
            var uwpBuildInfo = buildInfo as UwpBuildInfo;

            Debug.Assert(uwpBuildInfo != null);

            // Here, ResearchModeCapability must come first, in order to avoid schema errors
            // See https://docs.microsoft.com/windows/uwp/packaging/app-capability-declarations#restricted-capabilities
            if (uwpBuildInfo.ResearchModeCapabilityEnabled
#if !UNITY_2021_2_OR_NEWER
                && EditorUserBuildSettings.wsaSubtarget == WSASubtarget.HoloLens
#endif // !UNITY_2021_2_OR_NEWER
                )
            {
                AddResearchModeCapability(rootElement);
            }

            if (uwpBuildInfo.DeviceCapabilities != null)
            {
                AddCapabilities(rootElement, uwpBuildInfo.DeviceCapabilities);
            }
            if (uwpBuildInfo.GazeInputCapabilityEnabled)
            {
                AddGazeInputCapability(rootElement);
            }

            rootElement.Save(manifestFilePath);
        }
コード例 #23
0
        public static bool RestoreNugetPackages(string nugetPath, string storePath)
        {
            Debug.Assert(File.Exists(nugetPath));
            Debug.Assert(Directory.Exists(storePath));

            var nugetPInfo = new ProcessStartInfo
            {
                FileName        = nugetPath,
                CreateNoWindow  = true,
                UseShellExecute = false,
                Arguments       = "restore \"" + storePath + "/project.json\""
            };

            using (var nugetP = new Process())
            {
                nugetP.StartInfo = nugetPInfo;
                nugetP.Start();
                nugetP.WaitForExit();
                nugetP.Close();
                nugetP.Dispose();
            }

            return(File.Exists(storePath + "\\project.lock.json"));
        }
コード例 #24
0
 public JSONObjectEnumer(JSONObject jsonObject)
 {
     Debug.Assert(jsonObject.isContainer); //must be an array or object to itterate
     _jobj = jsonObject;
 }
コード例 #25
0
ファイル: World.cs プロジェクト: GolfNorth/VelcroPhysicsUnity
        private void SolveTOI(ref TimeStep step)
        {
            Island.Reset(2 * Settings.MaxTOIContacts, Settings.MaxTOIContacts, 0, ContactManager);

            if (_stepComplete)
            {
                for (var i = 0; i < BodyList.Count; i++)
                {
                    BodyList[i]._flags       &= ~BodyFlags.IslandFlag;
                    BodyList[i]._sweep.Alpha0 = 0.0f;
                }

                for (var i = 0; i < ContactManager.ContactList.Count; i++)
                {
                    var c = ContactManager.ContactList[i];

                    // Invalidate TOI
                    c._flags   &= ~ContactFlags.IslandFlag;
                    c._flags   &= ~ContactFlags.TOIFlag;
                    c._toiCount = 0;
                    c._toi      = 1.0f;
                }
            }

            // Find TOI events and solve them.
            for (;;)
            {
                // Find the first TOI.
                Contact minContact = null;
                var     minAlpha   = 1.0f;

                for (var i = 0; i < ContactManager.ContactList.Count; i++)
                {
                    var c = ContactManager.ContactList[i];

                    // Is this contact disabled?
                    if (c.Enabled == false)
                    {
                        continue;
                    }

                    // Prevent excessive sub-stepping.
                    if (c._toiCount > Settings.MaxSubSteps)
                    {
                        continue;
                    }

                    float alpha;
                    if (c.TOIFlag)
                    {
                        // This contact has a valid cached TOI.
                        alpha = c._toi;
                    }
                    else
                    {
                        var fA = c.FixtureA;
                        var fB = c.FixtureB;

                        // Is there a sensor?
                        if (fA.IsSensor || fB.IsSensor)
                        {
                            continue;
                        }

                        var bA = fA.Body;
                        var bB = fB.Body;

                        var typeA = bA.BodyType;
                        var typeB = bB.BodyType;
                        Debug.Assert(typeA == BodyType.Dynamic || typeB == BodyType.Dynamic);

                        var activeA = bA.Awake && typeA != BodyType.Static;
                        var activeB = bB.Awake && typeB != BodyType.Static;

                        // Is at least one body active (awake and dynamic or kinematic)?
                        if (activeA == false && activeB == false)
                        {
                            continue;
                        }

                        var collideA = (bA.IsBullet || typeA != BodyType.Dynamic) &&
                                       (fA.IgnoreCCDWith & fB.CollisionCategories) == 0 && !bA.IgnoreCCD;
                        var collideB = (bB.IsBullet || typeB != BodyType.Dynamic) &&
                                       (fB.IgnoreCCDWith & fA.CollisionCategories) == 0 && !bB.IgnoreCCD;

                        // Are these two non-bullet dynamic bodies?
                        if (collideA == false && collideB == false)
                        {
                            continue;
                        }

                        // Compute the TOI for this contact.
                        // Put the sweeps onto the same time interval.
                        var alpha0 = bA._sweep.Alpha0;

                        if (bA._sweep.Alpha0 < bB._sweep.Alpha0)
                        {
                            alpha0 = bB._sweep.Alpha0;
                            bA._sweep.Advance(alpha0);
                        }
                        else if (bB._sweep.Alpha0 < bA._sweep.Alpha0)
                        {
                            alpha0 = bA._sweep.Alpha0;
                            bB._sweep.Advance(alpha0);
                        }

                        Debug.Assert(alpha0 < 1.0f);

                        // Compute the time of impact in interval [0, minTOI]
                        var input = new TOIInput();
                        input.ProxyA = new DistanceProxy(fA.Shape, c.ChildIndexA);
                        input.ProxyB = new DistanceProxy(fB.Shape, c.ChildIndexB);
                        input.SweepA = bA._sweep;
                        input.SweepB = bB._sweep;
                        input.TMax   = 1.0f;

                        TOIOutput output;
                        TimeOfImpact.CalculateTimeOfImpact(ref input, out output);

                        // Beta is the fraction of the remaining portion of the .
                        var beta = output.T;
                        if (output.State == TOIOutputState.Touching)
                        {
                            alpha = Mathf.Min(alpha0 + (1.0f - alpha0) * beta, 1.0f);
                        }
                        else
                        {
                            alpha = 1.0f;
                        }

                        c._toi    = alpha;
                        c._flags &= ~ContactFlags.TOIFlag;
                    }

                    if (alpha < minAlpha)
                    {
                        // This is the minimum TOI found so far.
                        minContact = c;
                        minAlpha   = alpha;
                    }
                }

                if (minContact == null || 1.0f - 10.0f * Settings.Epsilon < minAlpha)
                {
                    // No more TOI events. Done!
                    _stepComplete = true;
                    break;
                }

                // Advance the bodies to the TOI.
                var fA1 = minContact.FixtureA;
                var fB1 = minContact.FixtureB;
                var bA0 = fA1.Body;
                var bB0 = fB1.Body;

                var backup1 = bA0._sweep;
                var backup2 = bB0._sweep;

                bA0.Advance(minAlpha);
                bB0.Advance(minAlpha);

                // The TOI contact likely has some new contact points.
                minContact.Update(ContactManager);
                minContact._flags &= ~ContactFlags.TOIFlag;
                ++minContact._toiCount;

                // Is the contact solid?
                if (minContact.Enabled == false || minContact.IsTouching == false)
                {
                    // Restore the sweeps.
                    minContact._flags &= ~ContactFlags.EnabledFlag;
                    bA0._sweep         = backup1;
                    bB0._sweep         = backup2;
                    bA0.SynchronizeTransform();
                    bB0.SynchronizeTransform();
                    continue;
                }

                bA0.Awake = true;
                bB0.Awake = true;

                // Build the island
                Island.Clear();
                Island.Add(bA0);
                Island.Add(bB0);
                Island.Add(minContact);

                bA0._flags        |= BodyFlags.IslandFlag;
                bB0._flags        |= BodyFlags.IslandFlag;
                minContact._flags &= ~ContactFlags.IslandFlag;

                // Get contacts on bodyA and bodyB.
                Body[] bodies = { bA0, bB0 };
                for (var i = 0; i < 2; ++i)
                {
                    var body = bodies[i];
                    if (body.BodyType == BodyType.Dynamic)
                    {
                        for (var ce = body.ContactList; ce != null; ce = ce.Next)
                        {
                            var contact = ce.Contact;

                            if (Island.BodyCount == Island.BodyCapacity)
                            {
                                break;
                            }

                            if (Island.ContactCount == Island.ContactCapacity)
                            {
                                break;
                            }

                            // Has this contact already been added to the island?
                            if (contact.IslandFlag)
                            {
                                continue;
                            }

                            // Only add static, kinematic, or bullet bodies.
                            var other = ce.Other;
                            if (other.BodyType == BodyType.Dynamic &&
                                body.IsBullet == false && other.IsBullet == false)
                            {
                                continue;
                            }

                            // Skip sensors.
                            if (contact.FixtureA.IsSensor || contact.FixtureB.IsSensor)
                            {
                                continue;
                            }

                            // Tentatively advance the body to the TOI.
                            var backup = other._sweep;
                            if (!other.IsIsland)
                            {
                                other.Advance(minAlpha);
                            }

                            // Update the contact points
                            contact.Update(ContactManager);

                            // Was the contact disabled by the user?
                            if (contact.Enabled == false)
                            {
                                other._sweep = backup;
                                other.SynchronizeTransform();
                                continue;
                            }

                            // Are there contact points?
                            if (contact.IsTouching == false)
                            {
                                other._sweep = backup;
                                other.SynchronizeTransform();
                                continue;
                            }

                            // Add the contact to the island
                            minContact._flags |= ContactFlags.IslandFlag;
                            Island.Add(contact);

                            // Has the other body already been added to the island?
                            if (other.IsIsland)
                            {
                                continue;
                            }

                            // Add the other body to the island.
                            other._flags |= BodyFlags.IslandFlag;

                            if (other.BodyType != BodyType.Static)
                            {
                                other.Awake = true;
                            }

                            Island.Add(other);
                        }
                    }
                }

                TimeStep subStep;
                subStep.dt      = (1.0f - minAlpha) * step.dt;
                subStep.inv_dt  = 1.0f / subStep.dt;
                subStep.dtRatio = 1.0f;
                Island.SolveTOI(ref subStep, bA0.IslandIndex, bB0.IslandIndex);

                // Reset island flags and synchronize broad-phase proxies.
                for (var i = 0; i < Island.BodyCount; ++i)
                {
                    var body = Island.Bodies[i];
                    body._flags &= ~BodyFlags.IslandFlag;

                    if (body.BodyType != BodyType.Dynamic)
                    {
                        continue;
                    }

                    body.SynchronizeFixtures();

                    // Invalidate all contact TOIs on this displaced body.
                    for (var ce = body.ContactList; ce != null; ce = ce.Next)
                    {
                        ce.Contact._flags &= ~ContactFlags.TOIFlag;
                        ce.Contact._flags &= ~ContactFlags.IslandFlag;
                    }
                }

                // Commit fixture proxy movements to the broad-phase so that new contacts are created.
                // Also, some contacts can be destroyed.
                ContactManager.FindNewContacts();

                if (Settings.EnableSubStepping)
                {
                    _stepComplete = false;
                    break;
                }
            }
        }
コード例 #26
0
ファイル: World.cs プロジェクト: GolfNorth/VelcroPhysicsUnity
        private void Solve(ref TimeStep step)
        {
            // Size the island for the worst case.
            Island.Reset(BodyList.Count,
                         ContactManager.ContactList.Count,
                         JointList.Count,
                         ContactManager);

            // Clear all the island flags.
            foreach (var b in BodyList)
            {
                b._flags &= ~BodyFlags.IslandFlag;
            }

            foreach (var c in ContactManager.ContactList)
            {
                c._flags &= ~ContactFlags.IslandFlag;
            }

            foreach (var j in JointList)
            {
                j.IslandFlag = false;
            }

            // Build and simulate all awake islands.
            var stackSize = BodyList.Count;

            if (stackSize > _stack.Length)
            {
                _stack = new Body[Mathf.Max(_stack.Length * 2, stackSize)];
            }

            for (var index = BodyList.Count - 1; index >= 0; index--)
            {
                var seed = BodyList[index];
                if ((seed._flags & BodyFlags.IslandFlag) == BodyFlags.IslandFlag)
                {
                    continue;
                }

                if (seed.Awake == false || seed.Enabled == false)
                {
                    continue;
                }

                // The seed can be dynamic or kinematic.
                if (seed.BodyType == BodyType.Static)
                {
                    continue;
                }

                // Reset island and stack.
                Island.Clear();
                var stackCount = 0;
                _stack[stackCount++] = seed;

                seed._flags |= BodyFlags.IslandFlag;

                // Perform a depth first search (DFS) on the constraint graph.
                while (stackCount > 0)
                {
                    // Grab the next body off the stack and add it to the island.
                    var b = _stack[--stackCount];
                    Debug.Assert(b.Enabled);
                    Island.Add(b);

                    // Make sure the body is awake (without resetting sleep timer).
                    b._flags |= BodyFlags.AwakeFlag;

                    // To keep islands as small as possible, we don't
                    // propagate islands across static bodies.
                    if (b.BodyType == BodyType.Static)
                    {
                        continue;
                    }

                    // Search all contacts connected to this body.
                    for (var ce = b.ContactList; ce != null; ce = ce.Next)
                    {
                        var contact = ce.Contact;

                        // Has this contact already been added to an island?
                        if (contact.IslandFlag)
                        {
                            continue;
                        }

                        // Is this contact solid and touching?
                        if (ce.Contact.Enabled == false || ce.Contact.IsTouching == false)
                        {
                            continue;
                        }

                        // Skip sensors.
                        var sensorA = contact.FixtureA.IsSensor;
                        var sensorB = contact.FixtureB.IsSensor;
                        if (sensorA || sensorB)
                        {
                            continue;
                        }

                        Island.Add(contact);
                        contact._flags |= ContactFlags.IslandFlag;

                        var other = ce.Other;

                        // Was the other body already added to this island?
                        if (other.IsIsland)
                        {
                            continue;
                        }

                        Debug.Assert(stackCount < stackSize);
                        _stack[stackCount++] = other;

                        other._flags |= BodyFlags.IslandFlag;
                    }

                    // Search all joints connect to this body.
                    for (var je = b.JointList; je != null; je = je.Next)
                    {
                        if (je.Joint.IslandFlag)
                        {
                            continue;
                        }

                        var other = je.Other;

                        // WIP David
                        //Enter here when it's a non-fixed joint. Non-fixed joints have a other body.
                        if (other != null)
                        {
                            // Don't simulate joints connected to inactive bodies.
                            if (other.Enabled == false)
                            {
                                continue;
                            }

                            Island.Add(je.Joint);
                            je.Joint.IslandFlag = true;

                            if (other.IsIsland)
                            {
                                continue;
                            }

                            Debug.Assert(stackCount < stackSize);
                            _stack[stackCount++] = other;

                            other._flags |= BodyFlags.IslandFlag;
                        }
                        else
                        {
                            Island.Add(je.Joint);
                            je.Joint.IslandFlag = true;
                        }
                    }
                }

                Island.Solve(ref step, ref Gravity);

                // Post solve cleanup.
                for (var i = 0; i < Island.BodyCount; ++i)
                {
                    // Allow static bodies to participate in other islands.
                    var b = Island.Bodies[i];
                    if (b.BodyType == BodyType.Static)
                    {
                        b._flags &= ~BodyFlags.IslandFlag;
                    }
                }
            }

            // Synchronize fixtures, check for out of range bodies.

            foreach (var b in BodyList)
            {
                // If a body was not in an island then it did not move.
                if (!b.IsIsland)
                {
                    continue;
                }

                if (b.BodyType == BodyType.Static)
                {
                    continue;
                }

                // Update fixtures (for broad-phase).
                b.SynchronizeFixtures();
            }

            // Look for new contacts.
            ContactManager.FindNewContacts();
        }
コード例 #27
0
 public void FindCompiledJSONAsset()
 {
     Debug.Assert(inkAsset != null);
     jsonAsset = AssetDatabase.LoadAssetAtPath <TextAsset>(jsonPath);
 }
コード例 #28
0
 public InkFile(DefaultAsset inkAsset)
 {
     Debug.Assert(inkAsset != null);
     this.inkAsset = inkAsset;
 }
コード例 #29
0
 public int GetMaxElements(PersistableTypeHandle typeHandle)
 {
     Debug.Assert(typeHandle.IsValid, "Expected a valid type handle");
     return(_allPersistableTypeInfos[typeHandle.Handle - 1].MaxElements);
 }
コード例 #30
0
 public bool IsBufferType(PersistableTypeHandle typeHandle)
 {
     Debug.Assert(typeHandle.IsValid, "Expected a valid type handle");
     return(_allPersistableTypeInfos[typeHandle.Handle - 1].IsBuffer);
 }