Пример #1
0
        public void AnonymousTypeTest2()
        {
            Assert.Equal(new[] { "a", "b" }, ObjectUtility.GetPropertyDictionary(new
            {
                a = 1,
                b = 2
            }).Keys);

            var anonymous = new
            {
                a = 1,
                b = 2,
                c = new
                {
                    RegionID = 5,
                }
            };

            Assert.Equal(new[] { "a", "b", "RegionID" }, ObjectUtility.GetPropertyPureDictionary(anonymous, true).Keys);
            Assert.Equal(new[] { "a", "b", "c_RegionID" }, ObjectUtility.GetPropertyPureDictionary(anonymous, false).Keys);
        }
        public void DeleteCollection(ScriptableObjectCollection collection)
        {
            if (Application.isPlaying)
            {
                return;
            }

            if (!collections.Remove(collection))
            {
                return;
            }
            collectionGUIDs.Remove(collection.GUID);

#if UNITY_EDITOR
            for (int i = collection.Items.Count - 1; i >= 0; i--)
            {
                UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(collection.Items[i]));
            }
#endif
            ObjectUtility.SetDirty(this);
        }
Пример #3
0
        public void NestedToNull()
        {
            var     db      = DatabaseGenerator.Get();
            Product product = new Product()
            {
                Category = new Category()
                {
                    Title = "Featured"
                }
            };
            var tracker = new DocumentTracker(db);

            tracker.TrackChanges(product, ObjectUtility.CreateJObject(product, db));

            product.Category = null;

            var changed = tracker.GetChanges(product);

            var expectedJson = JObject.Parse("{'Category':null}");

            Assert.True(JObject.DeepEquals(expectedJson, changed));
        }
Пример #4
0
        public void DictionaryToNull()
        {
            var     db      = DatabaseGenerator.Get();
            Product product = new Product()
            {
                TypeQuantities = new Dictionary <string, int>()
                {
                    { "Soft", 1 }
                }
            };
            var tracker = new DocumentTracker(db);

            tracker.TrackChanges(product, ObjectUtility.CreateJObject(product, db));

            product.TypeQuantities = null;

            var changed = tracker.GetChanges(product);

            var expectedJson = JObject.Parse("{'TypeQuantities':null}");

            Assert.True(JObject.DeepEquals(expectedJson, changed));
        }
Пример #5
0
        public void ListToNull()
        {
            var     db      = DatabaseGenerator.Get();
            Product product = new Product()
            {
                Tags = new List <string>()
                {
                    "Soft"
                }
            };
            var tracker = new DocumentTracker(db);

            tracker.TrackChanges(product, ObjectUtility.CreateJObject(product, db));

            product.Tags = null;

            var changed = tracker.GetChanges(product);

            var expectedJson = JObject.Parse("{'Tags':null}");

            Assert.True(JObject.DeepEquals(expectedJson, changed));
        }
        private void DrawEditFoldoutButton(ref Rect popupRect)
        {
            Rect buttonRect = popupRect;

            buttonRect.width  = 30;
            buttonRect.height = 18;
            popupRect.width  -= buttonRect.width;
            buttonRect.x     += popupRect.width;

            GUIContent guiContent = CollectionEditorGUI.EditGUIContent;

            if (CollectionUtility.IsFoldoutOpen(foldoutObject))
            {
                guiContent = CollectionEditorGUI.CloseGUIContent;
            }

            if (GUI.Button(buttonRect, guiContent))
            {
                CollectionUtility.SetFoldoutOpen(foldoutObject, !CollectionUtility.IsFoldoutOpen(foldoutObject));
                ObjectUtility.SetDirty(collectableItem);
            }
        }
Пример #7
0
        public void NestedOneProperty()
        {
            var     db      = DatabaseGenerator.Get();
            Product product = new Product()
            {
                Category = new Category()
                {
                    Title = "Featured"
                }
            };
            var tracker = new DocumentTracker(db);

            tracker.TrackChanges(product, ObjectUtility.CreateJObject(product, db));

            product.Category.Title = "Stock";

            var changed = tracker.GetChanges(product);

            var expectedJson = JObject.Parse("{'Category':{'Title':'Stock'}}");

            Assert.Equal(JObject.DeepEquals(expectedJson, changed), true);
        }
Пример #8
0
    public FxPool(Transform root, GameObject template)
    {
        // Get FxController
        var fx = template.GetComponent <FXController>();

        if (fx == null)
        {
            fx             = template.AddComponent <FXController>();
            fx.loop        = true;
            fx.autoDestroy = true;
        }

        // Inactive template
        template.SetActive(false);

        // Attach template to root
        ObjectUtility.AttachToParentAndKeepLocalTrans(root, template.transform);

        this.root     = root;
        this.template = fx;
        this.released = false;
    }
Пример #9
0
        private void DrawEditFoldoutButton(ref Rect popupRect, ScriptableObjectCollectionItem targetItem)
        {
            Rect buttonRect = popupRect;

            buttonRect.width  = 30;
            buttonRect.height = 18;
            popupRect.width  -= buttonRect.width;
            buttonRect.x     += popupRect.width;

            GUIContent guiContent = CollectionEditorGUI.EditGUIContent;

            if (CollectionUtility.IsFoldoutOpen(targetItem, currentObject))
            {
                guiContent = CollectionEditorGUI.CloseGUIContent;
            }

            if (GUI.Button(buttonRect, guiContent))
            {
                CollectionUtility.SetFoldoutOpen(!CollectionUtility.IsFoldoutOpen(targetItem, currentObject), targetItem, currentObject);
                ObjectUtility.SetDirty(targetItem);
            }
        }
Пример #10
0
        public void DictionaryTwoProperty()
        {
            var     db      = DatabaseGenerator.Get();
            Product product = new Product()
            {
                TypeQuantities = new Dictionary <string, int>()
                {
                    { "Soft", 1 }
                }
            };
            var tracker = new DocumentTracker(db);

            tracker.TrackChanges(product, ObjectUtility.CreateJObject(product, db));

            product.TypeQuantities["Soft"] = 5;
            product.TypeQuantities.Add("Hard", 2);

            var changed = tracker.GetChanges(product);

            var expectedJson = JObject.Parse("{'TypeQuantities':{'Hard':2,'Soft':5}}");

            Assert.Equal(JObject.DeepEquals(expectedJson, changed), true);
        }
Пример #11
0
        public IEnumerator DoUpdate()
        {
            Transform areaTrans = transform.parent;

            while (areaTrans != null && areaTrans.GetComponent <Area>() == null)
            {
                areaTrans = areaTrans.parent;
            }
            Area area = areaTrans.GetComponent <Area>();

            if (area != null)
            {
                m_AreaId = area.Uid;

                m_RelativeAreaPos   = area.transform.InverseTransformPoint(transform.position);
                m_RelativeAreaRot   = Quaternion.Inverse(areaTrans.rotation) * transform.rotation;
                m_RelativeAreaScale = ObjectUtility.CalculateLossyScale(transform, area.transform);
                gameObject.name     = string.Format("{0}_寻宝节点", areaTrans.name);
            }

            m_SemaphorMarkCache.Clear();
            SemaphoreMark[] m_SemaphorMarks = GetComponentsInChildren <SemaphoreMark>();
            if (m_SemaphorMarks != null && m_SemaphorMarks.Length > 0)
            {
                m_SemaphorMarkCache.AddRange(m_SemaphorMarks);
                for (int iSeam = 0; iSeam < m_SemaphorMarkCache.Count; iSeam++)
                {
                    SemaphoreMark mark = m_SemaphorMarks[iSeam];
                    if (mark != null && mark.gameObject != null)
                    {
                        mark.DoUpdate();
                    }
                    yield return(null);
                }
            }
            yield return(null);
        }
        /// <summary>
        /// decode the batched request packet
        /// </summary>
        /// <param name="channel">the channel of bytes to read</param>
        /// <param name="request">the request of the response.</param>
        /// <param name="smbBatchedResponse">the batched response</param>
        /// <returns>the consumed length of batched response packet</returns>
        protected override int DecodeBatchedRequest(
            Channel channel,
            SmbPacket request, SmbBatchedResponsePacket smbBatchedResponse)
        {
            int result = base.DecodeBatchedRequest(channel, request, smbBatchedResponse);

            for (SmbBatchedResponsePacket currentPacket = smbBatchedResponse;
                 currentPacket != null && currentPacket.AndxPacket != null;
                 currentPacket = currentPacket.AndxPacket as SmbBatchedResponsePacket)
            {
                SmbPacket andxPacket = currentPacket.AndxPacket;

                // create the smb packet
                object smbParameters = ObjectUtility.GetFieldValue(currentPacket, "smbParameters");
                if (smbParameters != null)
                {
                    SmbHeader smbHeader = smbBatchedResponse.SmbHeader;
                    smbHeader.Command = (SmbCommand)ObjectUtility.GetFieldValue(smbParameters, "AndXCommand");
                    andxPacket        = CreateSmbResponsePacket(null, smbHeader, null);
                }

                // convert from cifs packet to smb packet
                if (andxPacket != null)
                {
                    Type smbPacketType = andxPacket.GetType();
                    andxPacket = ObjectUtility.CreateInstance(
                        smbPacketType.Module.FullyQualifiedName,
                        smbPacketType.FullName,
                        new object[] { currentPacket.AndxPacket }) as SmbPacket;
                }

                currentPacket.AndxPacket = andxPacket;
            }

            return(result);
        }
        /// <summary>
        /// Get the ancestor nodes of the given tree node.
        /// </summary>
        /// <param name="nodeGuid">Tree node guid.</param>
        /// <returns>
        /// Return the guid array of the ancestor nodes, whose order is from the parent node to root node.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// Thrown when the given node doesn't exist.
        /// </exception>
        internal Guid[] GetAncestorNodes(Guid nodeGuid)
        {
            if (!dataMap.ContainsKey(nodeGuid))
            {
                throw new ArgumentException("The given node doesn't exist.", "nodeGuid");
            }

            if (ObjectUtility.DeepCompare(root.Value, nodeGuid))
            {
                return(new Guid[] { });
            }

            List <Guid> tmpList = new List <Guid>();

            Guid currentNode = nodeGuid;

            while (parentNodeMap.ContainsKey(currentNode))
            {
                currentNode = parentNodeMap[currentNode];
                tmpList.Add(currentNode);
            }

            return(tmpList.ToArray());
        }
Пример #14
0
//----------------------------------------------------------------------------------------------------------------------    
    private static void DestroyIrrelevantComponents(GameObject obj, EntityType curEntityType) {

        HashSet<Type> componentsToDelete = new HashSet<Type>(m_componentsToDeleteOnReload);

        //Check which component should remain (should not be deleted)
        switch (curEntityType) {
            case EntityType.Camera:
                componentsToDelete.Remove(typeof(Camera));
                break;
            case EntityType.Light:
                componentsToDelete.Remove(typeof(Light));
                break;
            case EntityType.Mesh: {
                componentsToDelete.Remove(typeof(SkinnedMeshRenderer));
                componentsToDelete.Remove(typeof(MeshFilter));
                componentsToDelete.Remove(typeof(MeshRenderer));
                break;
            }                
            case EntityType.Points:
                componentsToDelete.Remove(typeof(PointCache));
                componentsToDelete.Remove(typeof(PointCacheRenderer));
                break;
            default:
                break;
        }
        

        foreach (Type t in componentsToDelete) {
            Component c = obj.GetComponent(t);
            if (null == c)
                continue;
            
            ObjectUtility.Destroy(c);
        }

    }
Пример #15
0
    public void Despawm(FXController fx)
    {
        if (released)
        {
            Object.Destroy(fx.Root.gameObject);
        }
        else
        {
#if FX_POOL_METRICS
            despawmToPoolCount++;
#endif

            // Reset data
            fx.ClearFinishCallback();
            fx.SetFreeToLastPoolTime(Time.time);

            Debug.Assert(fx.Root.parent != root);

            // Return to pool
            ObjectUtility.AttachToParentAndResetLocalTrans(root, fx.Root);
            fx.Root.gameObject.SetActive(false);
            despawmFXs.Insert(0, fx);
        }
    }
Пример #16
0
        bool ExportToFile(List <Kisayol> list)
        {
            bool res = false;

            try
            {
                svFlDialog = new SaveFileDialog();
                DialogResult dr = svFlDialog.ShowDialog();
                if (dr == System.Windows.Forms.DialogResult.OK || dr == System.Windows.Forms.DialogResult.Yes)
                {
                    string fileName = svFlDialog.FileName;
                    if (ObjectUtility.ToStr(fileName).Replace(" ", "").Length == 0)
                    {
                        MessageUtil.Warn("Save File Name can not be empty.");
                        return(res);
                    }

                    if (fileName.EndsWith(".xls") == false)
                    {
                        fileName += ".xls";
                    }

                    res = ExportManager.ExportToExcel(list, fileName);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                svFlDialog = null;
            }

            return(res);
        }
Пример #17
0
 public JToken PostJsonFor(string url, object updata) => PostJsonFor(url, ObjectUtility.CovertToDictionary(updata));
 public void Setup()
 {
     _objectUtility = new ObjectUtility();
 }
Пример #19
0
 public string PostJsonDownload(Stream receiver, string url, object updata, int bufferSize = RECOMMENDED_BUFFER_SIZE)
 => PostJsonDownload(receiver, url, ObjectUtility.CovertToDictionary(updata), bufferSize);
Пример #20
0
 public TRet PostJsonFor <TRet>(string url, object updata) => PostJsonFor <TRet>(url, ObjectUtility.CovertToDictionary(updata));
Пример #21
0
 /// <summary>Get the items matching the given ID.</summary>
 /// <param name="id">The category or item ID.</param>
 private IEnumerable <SObject> GetItems(int id)
 {
     return(id < 0
         ? ObjectUtility.GetObjectsInCategory(id)
         : new[] { new SObject(id, 1) });
 }
Пример #22
0
 public string PostJson(string url, object updata) => PostJson(url, ObjectUtility.CovertToDictionary(updata));
 /// <summary>
 /// Clones the packet.
 /// </summary>
 /// <returns>The cloned packet.</returns>
 public override StackPacket Clone()
 {
     return((StackPacket)ObjectUtility.DeepClone(this));
 }
Пример #24
0
 /// <summary>
 /// Broadcasts an asynchronous Action to all child components of a given root.
 /// </summary>
 /// <param name="obj">the root object.</param>
 /// <param name="message">the message to run.</param>
 /// <typeparam name="T">the type to run the Action against.</typeparam>
 /// <returns>the awaitable task.</returns>
 public static Task Broadcast <T>(this Object obj, Func <T, Task> message) =>
 Task.WhenAll(ObjectUtility.GetAll <T>(obj).Select(message));
Пример #25
0
        public async Task <bool> ReplicateShardWriteOperationAsync(ShardWriteOperation operation)
        {
            // Get the last operation
            ShardWriteOperation lastOperation;
            var startTime = DateTime.Now;

            if (operation.Pos != 1)
            {
                while ((lastOperation = await GetOrPopulateOperationCache(operation.Data.ShardId.Value)) == null || !lastOperation.Applied || lastOperation.Pos < operation.Pos - 1)
                {
                    //Assume in the next 3 seconds you should receive the previos requests
                    if ((DateTime.Now - startTime).TotalMilliseconds > 3000)
                    {
                        return(false);
                    }
                    await Task.Delay(100);
                }

                if (lastOperation.Pos != operation.Pos - 1)
                {
                    lastOperation = await _shardRepository.GetShardWriteOperationAsync(operation.Data.ShardId.Value, operation.Pos - 1);
                }

                string newHash;
                if ((newHash = ObjectUtility.HashStrings(lastOperation.ShardHash, operation.Id)) != operation.ShardHash)
                {
                    //Critical error with data concurrency, revert back to last known good commit via the resync process
                    _logger.LogError(_nodeStateService.GetNodeLogId() + "Failed to check the hash for operation " + operation.Id + ", marking shard as out of sync...");
                    throw new Exception(_nodeStateService.GetNodeLogId() + "Failed to check the hash for operation " + operation.Id + ", marking shard as out of sync...");
                }
            }

            // if (operation.Pos > 1)
            //{
            //   lock (_shardLastOperationCache[operation.Data.ShardId.Value])
            //  {
            //The operation must already be being applied

            /* if (_shardLastOperationCache[operation.Data.ShardId.Value].Pos >= operation.Pos)
             * {
             *   throw new Exception("There must be a replication process being run");
             * }*/

            _shardRepository.AddShardWriteOperationAsync(operation).GetAwaiter().GetResult();
            //Run shard operation
            ApplyOperationToDatastore(operation);
            _shardRepository.MarkShardWriteOperationAppliedAsync(operation.Id).GetAwaiter().GetResult();
            //Update the cache
            UpdateOperationCache(operation.Data.ShardId.Value, operation);
            //}

            /* }
             * else
             * {
             *   await _shardRepository.AddShardWriteOperationAsync(operation);
             *   //Run shard operation
             *   ApplyOperationToDatastore(operation);
             *   await _shardRepository.MarkShardWriteOperationAppliedAsync(operation.Id);
             *   //Update the cache
             *   UpdateOperationCache(operation.Data.ShardId.Value, operation);
             * }*/

            return(true);
        }
Пример #26
0
        public async Task <WriteShardDataResponse> WriteShardData(ShardData data, ShardOperationOptions operationType, string operationId, DateTime transactionDate)
        {
            ShardWriteOperation operation = new ShardWriteOperation()
            {
                Data            = data,
                Id              = operationId,
                Operation       = operationType,
                TransactionDate = transactionDate
            };

            ShardWriteOperation lastOperation = await GetOrPopulateOperationCache(operation.Data.ShardId.Value);

            //Start at 1
            operation.Pos = lastOperation == null ? 1 : lastOperation.Pos + 1;
            var hash = lastOperation == null ? "" : lastOperation.ShardHash;

            operation.ShardHash = ObjectUtility.HashStrings(hash, operation.Id);
            _logger.LogDebug(_nodeStateService.GetNodeLogId() + "writing new operation " + operationId + " with data " + Environment.NewLine + JsonConvert.SerializeObject(data, Formatting.Indented));
            //Write the data

            var writeOperation = await _shardRepository.AddShardWriteOperationAsync(operation); //Add shard operation

            if (writeOperation)
            {
                ApplyOperationToDatastore(operation);
                var shardMetadata = _stateMachine.GetShard(operation.Data.ShardType, operation.Data.ShardId.Value);
                //Mark operation as applied
                await _shardRepository.MarkShardWriteOperationAppliedAsync(operation.Id);

                //Update the cache
                UpdateOperationCache(operation.Data.ShardId.Value, operation);
                ConcurrentBag <Guid> InvalidNodes = new ConcurrentBag <Guid>();
                //All allocations except for your own
                var tasks = shardMetadata.InsyncAllocations.Where(id => id != _nodeStateService.Id).Select(async allocation =>
                {
                    try
                    {
                        var result = await _clusterClient.Send(allocation, new ReplicateShardWriteOperation()
                        {
                            Operation = operation
                        });

                        if (result.IsSuccessful)
                        {
                            _logger.LogDebug(_nodeStateService.GetNodeLogId() + "Successfully replicated all " + shardMetadata.Id + "shards.");
                        }
                        else
                        {
                            throw new Exception("Failed to replicate data to shard " + shardMetadata.Id + " to node " + allocation + " for operation " + operation.ToString() + Environment.NewLine + JsonConvert.SerializeObject(operation, Formatting.Indented));
                        }
                    }
                    catch (TaskCanceledException e)
                    {
                        _logger.LogError(_nodeStateService.GetNodeLogId() + "Failed to replicate shard " + shardMetadata.Id + " on node " + allocation + " for operation " + operation.Pos + " as request timed out, marking shard as not insync...");
                        InvalidNodes.Add(allocation);
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(_nodeStateService.GetNodeLogId() + "Failed to replicate shard " + shardMetadata.Id + " for operation " + operation.Pos + " with error " + e.Message + ", marking shard as not insync..." + Environment.NewLine + e.StackTrace);
                        InvalidNodes.Add(allocation);
                    }
                });

                await Task.WhenAll(tasks);

                if (InvalidNodes.Count() > 0)
                {
                    await _clusterClient.Send(new ExecuteCommands()
                    {
                        Commands = new List <BaseCommand>()
                        {
                            new UpdateShardMetadataAllocations()
                            {
                                ShardId = data.ShardId.Value,
                                Type    = data.ShardType,
                                StaleAllocationsToAdd     = InvalidNodes.ToHashSet(),
                                InsyncAllocationsToRemove = InvalidNodes.ToHashSet()
                            }
                        },
                        WaitForCommits = true
                    });

                    _logger.LogInformation(_nodeStateService.GetNodeLogId() + " had stale virtual machines.");
                }

                return(new WriteShardDataResponse()
                {
                    Pos = operation.Pos,
                    ShardHash = operation.ShardHash,
                    IsSuccessful = true
                });
            }
            else
            {
                return(new WriteShardDataResponse()
                {
                    IsSuccessful = false
                });
            }
        }
//----------------------------------------------------------------------------------------------------------------------
        internal static IEnumerator UpdateRenderCacheCoroutine(PlayableDirector director, RenderCachePlayableAsset renderCachePlayableAsset)
        {
            Assert.IsNotNull(director);
            Assert.IsNotNull(renderCachePlayableAsset);

            TimelineClipSISData timelineClipSISData = renderCachePlayableAsset.GetBoundTimelineClipSISData();

            if (null == timelineClipSISData)
            {
                EditorUtility.DisplayDialog("Streaming Image Sequence",
                                            "RenderCachePlayableAsset is not ready",
                                            "Ok");
                yield break;
            }

            TrackAsset         track          = renderCachePlayableAsset.GetBoundTimelineClipSISData().GetOwner().parentTrack;
            BaseRenderCapturer renderCapturer = director.GetGenericBinding(track) as BaseRenderCapturer;

            if (null == renderCapturer)
            {
                EditorUtility.DisplayDialog("Streaming Image Sequence",
                                            "Please bind an appropriate RenderCapturer component to the track.",
                                            "Ok");
                yield break;
            }


            //begin capture
            bool canCapture = renderCapturer.BeginCapture();

            if (!canCapture)
            {
                EditorUtility.DisplayDialog("Streaming Image Sequence",
                                            renderCapturer.GetLastErrorMessage(),
                                            "Ok");
                yield break;
            }


            //Check output folder
            string outputFolder = renderCachePlayableAsset.GetFolder();

            if (string.IsNullOrEmpty(outputFolder) || !Directory.Exists(outputFolder))
            {
                EditorUtility.DisplayDialog("Streaming Image Sequence",
                                            "Invalid output folder",
                                            "Ok");
                yield break;
            }

            Texture capturerTex = renderCapturer.GetInternalTexture();

            //Show progress in game view
            GameObject           progressGo = new GameObject("Blitter");
            LegacyTextureBlitter blitter    = progressGo.AddComponent <LegacyTextureBlitter>();

            blitter.SetTexture(capturerTex);
            blitter.SetCameraDepth(int.MaxValue);

            TimelineClip timelineClip     = timelineClipSISData.GetOwner();
            double       nextDirectorTime = timelineClip.start;
            double       timePerFrame     = 1.0f / track.timelineAsset.editorSettings.fps;

            int fileCounter = 0;
            int numFiles    = (int)Math.Ceiling(timelineClip.duration / timePerFrame) + 1;
            int numDigits   = MathUtility.GetNumDigits(numFiles);

            string        prefix         = $"{timelineClip.displayName}_";
            List <string> imageFileNames = new List <string>(numFiles);

            //Store old files that has the same pattern
            string[]         existingFiles = Directory.GetFiles(outputFolder, $"*.png");
            HashSet <string> filesToDelete = new HashSet <string>(existingFiles);

            bool cancelled = false;

            while (nextDirectorTime <= timelineClip.end && !cancelled)
            {
                string fileName       = $"{prefix}{fileCounter.ToString($"D{numDigits}")}.png";
                string outputFilePath = Path.Combine(outputFolder, fileName);

                SISPlayableFrame playableFrame = timelineClipSISData.GetPlayableFrame(fileCounter);
                bool             captureFrame  = (!timelineClipSISData.AreFrameMarkersRequested() || //if markers are not requested, capture
                                                  !File.Exists(outputFilePath) || //if file doesn't exist, capture
                                                  (null != playableFrame && playableFrame.IsUsed() && !playableFrame.IsLocked())
                                                  );

                if (filesToDelete.Contains(outputFilePath))
                {
                    filesToDelete.Remove(outputFilePath);
                }
                imageFileNames.Add(fileName);

                if (captureFrame)
                {
                    SetDirectorTime(director, nextDirectorTime);

                    //Need at least two frames in order to wait for the TimelineWindow to be updated ?
                    yield return(null);

                    yield return(null);

                    yield return(null);

                    //Unload texture because it may be overwritten
                    StreamingImageSequencePlugin.UnloadImageAndNotify(outputFilePath);
                    renderCapturer.CaptureToFile(outputFilePath);
                }


                nextDirectorTime += timePerFrame;
                ++fileCounter;

                cancelled = EditorUtility.DisplayCancelableProgressBar(
                    "StreamingImageSequence", "Caching render results", ((float)fileCounter / numFiles));
            }

            if (!cancelled)
            {
                renderCachePlayableAsset.SetImageFileNames(imageFileNames);

                //Delete old files
                if (AssetDatabase.IsValidFolder(outputFolder))
                {
                    foreach (string oldFile in filesToDelete)
                    {
                        AssetDatabase.DeleteAsset(oldFile);
                    }
                }
                else
                {
                    foreach (string oldFile in filesToDelete)
                    {
                        File.Delete(oldFile);
                    }
                }
            }

            //Notify
            FolderContentsChangedNotifier.GetInstance().Notify(outputFolder);

            //Cleanup
            EditorUtility.ClearProgressBar();
            renderCapturer.EndCapture();
            ObjectUtility.Destroy(progressGo);

            AssetDatabase.Refresh();

            yield return(null);
        }
Пример #28
0
    // Play Pfx.
    public void PlayPfx(FXController fx, int destroyMode, int userData, string modelBone, string bone, bool boneFollow, Vector3 offset, Vector3 rotate, bool useSpecificPosition, Vector3 specificPosition)
    {
        // Set Render layer

        /**
         * Bug 记录。
         *
         * 对于魔化卫庄的组合技,这个技能在主Action中有目标选择,但是每一个伤害事件都有自己的目标选择,最终可能有一种情况,即所有的EventTargetRecord中的目标均不包含Action选择的目标
         * 在主Action中配置了一些播放特效的事件,这些事件服务器不作处理,也不会发给客户端,而是由客户端自己根据配置文件构建,构建时使用ActionRecord的TargetAvtarIndexs里的AvatarIndex,
         * 指定的AvatarIndex可能不在任何EventTargetRecord中,所以SkillCombatRound在遮罩屏幕时不会将这个角色点亮,导致“由这个角色”释放的特效也没有被点亮
         *
         * 修改逻辑,如果正处于屏幕遮罩中,那么所有的特效都有应该具有SceneMaskLayer
         */
        //BattleScene bs = BattleScene.GetBattleScene();

        //int Layer = 0;
        //if (bs != null && bs.IsEnableSceneMask)
        //	Layer = GameDefines.SceneMaskLayer;
        //else Layer = avatar.gameObject.layer;

        int Layer = avatar.gameObject.layer;

        // Set Render layer
        fx.Root.gameObject.layer = Layer;
        foreach (var subObj in fx.Root.GetComponentsInChildren <Transform>())
        {
            subObj.gameObject.layer = Layer;
        }

        // If bone follow, attach to this bone.
        if (boneFollow)
        {
            var attachingGO = fx.Root;

            // Try to find specified
            if (modelBone != "")
            {
                var modelBoneObj = ObjectUtility.FindChildObject(attachingGO, modelBone);
                if (modelBoneObj != null)
                {
                    attachingGO = modelBoneObj;
                }
            }

            // If specify bone, to this bone.
            if (bone != "")
            {
                var boneGO = ObjectUtility.FindChildObject(avatar.AvatarObject, bone);
                if (boneGO == null)
                {
                    Debug.LogWarning(string.Format("Can not find bone:{0} in avatar", bone));
                }
                ObjectUtility.AttachToParentAndResetLocalPosAndRotation(boneGO, attachingGO);
            }
            // Has no specify bone, to the root bone.
            else
            {
                ObjectUtility.AttachToParentAndResetLocalPosAndRotation(avatar.CachedTransform, attachingGO);
            }
        }
        // If not bone follow, just play at this bone position.
        else
        {
            // If specify bone, use this bone position.
            if (bone != "")
            {
                var boneGO = ObjectUtility.FindChildObject(avatar.CachedTransform, bone);
                if (boneGO == null)
                {
                    Debug.LogWarning(string.Format("Can not find bone:{0} in avatar", bone));
                }
                ObjectUtility.UnifyWorldTrans(boneGO, fx.Root);
            }
            // Has specific transform, use the transform.
            else if (useSpecificPosition)
            {
                fx.Root.position = specificPosition;
            }
            // Has no specify bone, use the root bone position.
            else
            {
                ObjectUtility.UnifyWorldTrans(avatar.CachedTransform, fx.Root);
            }
        }

        fx.Root.Translate(offset);
        fx.Root.Rotate(rotate);

        if (destroyMode != AvatarAction.Effect._DestroyType.Normal)
        {
            // Add to dictionary.
            var fxInst = new FxInst(fx, destroyMode, userData);
            fxMap[fxInst.instanceId] = fxInst;

            // Set auto destroy flag to Pfx script.
            //FXController PfxScript = fx.GetComponentInChildren<FXController>();
            //if (PfxScript != null)
            {
                fx.autoDestroy = true;

                // Pfx will not loop except buff.
                if (destroyMode == AvatarAction.Effect._DestroyType.Buff)
                {
                    fx.loop = true;
                }

                if (destroyMode == AvatarAction.Effect._DestroyType.BlockAction)
                {
                    fx.AddFinishCallback(PfxFinishedBb, fxInst);
                }
            }
        }
    }
        public virtual string LoadGridAjax <T>(IEnumerable <T> source = null, Expression <Func <T, bool> > predicate = null, params string[] includes) where T : class
        {
            try
            {
                var draw          = Request.Form.GetValues("draw").FirstOrDefault();
                var start         = Request.Form.GetValues("start").FirstOrDefault();
                var length        = Request.Form.GetValues("length").FirstOrDefault();
                var sortColumn    = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
                var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
                var searchValue   = Request.Form.GetValues("search[value]").FirstOrDefault();

                //Paging Size (10,20,50,100)
                int pageSize = length != null?Convert.ToInt32(length) : 0;

                int skip = start != null?Convert.ToInt32(start) : 0;

                int recordsTotal = 0;

                if (source == null || source is IQueryable)
                {
                    var modelData = source == null?Repository.Instance.All <T>(includes) : source;

                    if (!string.IsNullOrEmpty(searchValue))
                    {
                        modelData = Repository.Instance.Filter(predicate);

                        //if (source != null)
                        //    modelData = source.Intersect(modelData);
                        //var searchColumns = search.Count() == 0 ? ObjectUtility.GetAllColumnsByObject<T>().ToArray() : search;
                        //modelData = modelData.Where(x => searchColumns.Any(y => (x.GetPropertyValue(y)).ToString().ToLower().IndexOf(searchValue.ToLower()) != -1));
                    }
                    //Sorting
                    if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
                    {
                        modelData = modelData.OrderBy(sortColumn + " " + sortColumnDir);
                    }

                    ////total number of rows count
                    recordsTotal = modelData.Count();
                    ////Paging
                    pageSize = recordsTotal < pageSize ? recordsTotal : pageSize;
                    var data = modelData.Skip(skip).Take(pageSize).ToList();
                    //Returning Json Data
                    return(JsonConvert.SerializeObject(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, Formatting.Indented,
                                                       new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                }
                else
                {
                    var modelData = source;
                    if (!string.IsNullOrEmpty(searchValue))
                    {
                        var searchColumns = predicate == null?ObjectUtility.GetAllColumnsByObject <T>().ToArray() : null;

                        //var u = modelData.Where<T>(predicate);//(searchColumns == null) ? modelData.Where<T>(predicate).As;
                        if (searchColumns == null)
                        {
                            modelData = modelData.AsQueryable().Where(predicate);
                        }
                        else
                        {
                            modelData = modelData.Where(x => searchColumns.Any(y => (x.GetPropertyValue(y)).ToString().ToLower().IndexOf(searchValue.ToLower()) != -1));
                        }
                    }
                    if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
                    {
                        modelData = sortColumnDir.ToLower() == "asc" ? modelData.OrderBy(x => x.GetPropertyValue(sortColumn)) : modelData.OrderByDescending(x => x.GetPropertyValue(sortColumn));
                    }
                    recordsTotal = modelData.Count();
                    pageSize     = recordsTotal < pageSize ? recordsTotal : pageSize;
                    var data = modelData.Skip(skip).Take(pageSize).ToList();
                    return(JsonConvert.SerializeObject(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, Formatting.Indented,
                                                       new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                }
            }
            catch (Exception ex)
            {
                throw;

                Console.WriteLine(ex);
                var modelData = (from tempcustomer in Repository.Instance.All <T>()
                                 select tempcustomer);
                return(JsonConvert.SerializeObject(new { draw = "", recordsFiltered = modelData.Count(), recordsTotal = modelData.Count(), data = modelData.Take(100).ToList() }, Formatting.Indented,
                                                   new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                }));
            }
        }
Пример #30
0
        public static void FindWidgetlAssignToVar(CodeGenerator gen, DataContext rootContext, DataContext widgetContext)
        {
            var path = ObjectUtility.GetGameObjectPath(widgetContext.gameObject, rootContext.gameObject);

            gen.PrintLine(WidgetVariable(widgetContext), " = trans.Find(\"", path, "\").GetComponent<", WidgetTypeName(widgetContext), ">();");
        }
Пример #31
0
 /// <summary>
 /// to create an instance of the StackPacket class that is identical to the current StackPacket.
 /// </summary>
 /// <returns>The copy of this instance</returns>
 public override StackPacket Clone()
 {
     return(ObjectUtility.DeepClone(this) as SmbPacket);
 }