Exemplo n.º 1
0
//    public Object LoadSingleAssetResource(string guid)
//    {
//        if (guid == null || guid == "")
//        {
//            GameDebug.LogError("Guid invalid");
//            return null;
//        }
//
//        var reference = new WeakAssetReference(guid);
//        return GetSingleAssetResource(reference);
//    }

    public Object GetSingleAssetResource(WeakAssetReference reference)
    {
        var def = new SingleResourceBundle();

        if (m_resources.TryGetValue(reference, out def))
        {
            return(def.asset);
        }

        def = new SingleResourceBundle();
        var useBundles = !Application.isEditor || forceBundles.IntValue > 0;

        var guidStr = reference.GetGuidStr();

#if UNITY_EDITOR
        if (!useBundles)
        {
            var path = AssetDatabase.GUIDToAssetPath(guidStr);

            def.asset = AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Object));

            if (def.asset == null)
            {
                GameDebug.LogWarning("Failed to load resource " + guidStr + " at " + path);
            }
            if (verbose.IntValue > 0)
            {
                GameDebug.Log("resource: loading non-bundled asset " + path + "(" + guidStr + ")");
            }
        }
#endif
        if (useBundles)
        {
            var bundlePath = GetBundlePath();
            def.bundle = AssetBundle.LoadFromFile(bundlePath + "/" + m_assetResourceFolder + "/" + guidStr);
            if (verbose.IntValue > 0)
            {
                GameDebug.Log("resource: loading bundled asset: " + m_assetResourceFolder + "/" + guidStr);
            }
            var handles = def.bundle.LoadAllAssets();
            if (handles.Length > 0)
            {
                def.asset = handles[0];
            }
            else
            {
                GameDebug.LogWarning("Failed to load resource " + guidStr);
            }
        }

        m_resources.Add(reference, def);
        return(def.asset);
    }
Exemplo n.º 2
0
        /// <summary>
        /// 检查包括活动在内所有系统的开启
        /// </summary>
        private void CheckSysOpenCondition()
        {
            bool all_inited = true;

            foreach (var recv in mWaitNetMsg.Values)
            {
                if (recv == false)
                {
                    all_inited = false;
                    break;
                }
            }

            if (all_inited)
            {
                var db_sys_config = DBManager.GetInstance().GetDB <DBSysConfig>();
                foreach (var sys_id in mRawOpenSysIds)
                {
                    //GameDebug.LogRed("初始系统:id=" + sys_id);
                    var sys_config = db_sys_config.GetConfigById(sys_id);
                    if (sys_config != null)
                    {
                        // 活动类型的系统需要检查活动是否开启
                        if (sys_config.IsActivity)
                        {
                            bool is_open = ActivityHelper.IsActivityOpen(sys_config.Id);
                            if (is_open)
                            {
                                mOpenSysList.Add(sys_config);
                                mOpenSysDic[sys_config.Id] = sys_config;
                            }
                            else
                            {
                                GameDebug.LogRed(string.Format("系统: id= {0} 对应的活动未开启", sys_id));
                            }
                        }
                        else
                        {
                            mOpenSysList.Add(sys_config);
                            mOpenSysDic[sys_config.Id] = sys_config;
                        }
                    }
                    else
                    {
                        GameDebug.LogWarning(string.Format("[MSG_PLAYER_SYS_OPEN_INFO] 找不到对应的系统:{0}", sys_id));
                    }
                }
                mOpenSysList.Sort();

                ClientEventMgr.GetInstance().FireEvent((int)ClientEvent.CE_SYS_CONFIG_INIT, null);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 试图走到目标点,但是通过方向、速度来进行同步
        /// </summary>
        public int TryWalkToAlong(Vector3 pos, System.Action reachCallback = null)
        {
            // 被定身或者在攻击的时候不能移动
            if (mOwner.DisableMoveState)
            {
                GameDebug.LogWarning("TryWalkToAlong warning, actor is in disable move state!!!");
                return(0);
            }
            if (mOwner.IsAttacking())
            {
                if (mOwner.IsInSkillActionEndingStage())    //后摇阶段,可以移动
                {
                    Skill cur_skill = mOwner.GetCurSkill();
                    if (cur_skill != null)
                    {
                        cur_skill.End();
                    }
                }
                else    //非后摇阶段,不可以移动
                {
                    GameDebug.LogWarning("TryWalkToAlong warning, actor is attacking and not ending stage!!!");
                    return(0);
                }
            }

            // 只有当可以行走时,才设置移动速度
            if (mOwner.ActorMachine.IsWalking() || mOwner.FSM.CanReact((uint)ActorMachine.EFSMEvent.DE_Walk))
            {
                mOwner.MoveSpeed = mOwner.GetWalkSpeed();
            }

            if (mOwner.WalkTo(pos))
            {
                m_WalkId++;

                mOwner.ActorMachine.OnWalkToPointChange = OnWalkingChange;
                mOwner.ActorMachine.OnReachTarget       = OnWalktoTarget;

                if (reachCallback != null)
                {
                    if (mReachCallbacks == null)
                    {
                        mReachCallbacks = new Dictionary <int, System.Action>();
                        mReachCallbacks.Clear();
                    }
                    mReachCallbacks.Add(m_WalkId, reachCallback);
                }

                return(m_WalkId);
            }
            return(0);
        }
Exemplo n.º 4
0
    public void WriteString(string name, char[] value, int length, int maxLength, OverrunBehaviour overrunBehaviour)
    {
        ValidateOrGenerateSchema(name, NetworkSchema.FieldType.String, 0, false, 0, maxLength);

        GameDebug.Assert(maxLength <= s_ByteBuffer.Length, "NetworkWriter: Max length has to be less than {0}", s_ByteBuffer.Length);
        GameDebug.Assert((maxLength & 0x3) == 0, "MaxLength has to be 32bit aligned");

        var byteCount = 0;

        if (length > 0)
        {
            // Ensure the (utf-8) *encoded* string is not too big. If it is, cut it off,
            // convert back to unicode and then back again to utf-8. This little dance gives
            // a valid utf-8 string within the buffer size.
            byteCount = NetworkConfig.encoding.GetBytes(value, 0, length, s_ByteBuffer, 0);
            if (byteCount > maxLength)
            {
                if (overrunBehaviour == OverrunBehaviour.AssertMaxLength)
                {
                    GameDebug.Assert(false, "NetworkWriter : string {0} too long. (Using {1}/{2} allowed encoded bytes): ", value, byteCount, maxLength);
                }
                // truncate
                var truncWithBadEnd = NetworkConfig.encoding.GetString(s_ByteBuffer, 0, maxLength);
                var truncOk         = truncWithBadEnd.Substring(0, truncWithBadEnd.Length - 1);
                var newbyteCount    = NetworkConfig.encoding.GetBytes(truncOk, 0, truncOk.Length, s_ByteBuffer, 0);

                if (overrunBehaviour == OverrunBehaviour.WarnAndTrunc)
                {
                    GameDebug.LogWarning(string.Format("NetworkWriter : truncated string with {0} bytes. (result: {1})", byteCount - newbyteCount, truncOk));
                }
                byteCount = newbyteCount;
                GameDebug.Assert(byteCount <= maxLength, "String encoding failed");
            }
        }

        m_Output[m_Position++] = (uint)byteCount;
        byte *dst = (byte *)(m_Output + m_Position);
        int   i   = 0;

        for (; i < byteCount; ++i)
        {
            *dst++ = s_ByteBuffer[i];
        }
        for (; i < maxLength; ++i)
        {
            *dst++ = 0;
        }

        GameDebug.Assert(((uint)dst & 0x3) == 0, "Expected to stay aligned!");
        m_Position += maxLength / 4;
    }
Exemplo n.º 5
0
    /// <summary>
    /// 开放给Lua端调用的Post接口
    /// </summary>
    /// <param name="url">URL</param>
    /// <param name="values">值表</param>
    /// <param name="files">文件表,会以二进制的形式向服务端请求(通过WWWForm.AddBinaryData的形式)</param>
    /// <param name="cb">回调</param>
    public void POST(string url, XLua.LuaTable values, XLua.LuaTable files, POSTCB cb)
    {
        Dictionary <string, string> data = new Dictionary <string, string>();
        IDictionaryEnumerator       de   = null;

        if (values != null)
        {
            //de = values.GetEnumerator();
            //while (de.MoveNext())
            //{
            //    data.Add(de.Key as string, de.Value as string);
            //}
            foreach (string key in values.GetKeys <string>())
            {
                data.Add(key, values.Get <string>(key));
            }
        }

        Dictionary <string, KeyValuePair <string, byte[]> > stream = new Dictionary <string, KeyValuePair <string, byte[]> >();

        if (files != null)
        {
            //de = files.GetEnumerator();
            //while (de.MoveNext())
            //{
            //    string field = de.Key as string;
            //    string path = de.Value as string;
            //    if (string.IsNullOrEmpty(path) || !File.Exists(path))
            //    {
            //        GameDebug.LogWarning(string.Format("Unexpect path:{0}", path));
            //        continue;
            //    }
            //    byte[] bytes = File.ReadAllBytes(path);
            //    stream.Add(field, new KeyValuePair<string, byte[]>(Path.GetFileName(path), bytes));
            //}
            foreach (string field in files.GetKeys <string>())
            {
                string path = values.Get <string>(field);
                if (string.IsNullOrEmpty(path) || !File.Exists(path))
                {
                    GameDebug.LogWarning(string.Format("Unexpect path:{0}", path));
                    continue;
                }
                byte[] bytes = File.ReadAllBytes(path);
                stream.Add(field, new KeyValuePair <string, byte[]>(Path.GetFileName(path), bytes));
            }
        }

        POST(url, data, stream, cb, null);
    }
Exemplo n.º 6
0
        }                                                                   //奖励组

        public virtual void CreateGoodsByTypeId(uint _id)
        {
            this.type_idx = _id;
            var goods_info = GoodsHelper.GetGoodsInfo(_id);

            if (goods_info != null)
            {
                this.main_type = goods_info.type;
                this.SetIdFindData(_id);
            }
            else
            {
                GameDebug.LogWarning(string.Format("itme gid: {0} not exist", _id));
            }
        }
Exemplo n.º 7
0
        protected override void UnInitUI()
        {
            GameDebug.LogWarning("UIGuideWindow.UnInitUI, this window should not be deleted");

            base.UnInitUI();

            CleanupUpdateTimer();

            if (m_GuideDescTimer != null)
            {
                m_GuideDescTimer.Destroy();
                m_GuideDescTimer = null;
            }

            UnInitEvent();
        }
Exemplo n.º 8
0
 public void Stop(SoundHandle sh, float fadeOutTime = 0.0f)
 {
     if (!sh.IsValid())
     {
         GameDebug.LogWarning("SoundSystem.Stop(): invalid SoundHandle");
         return;
     }
     if (fadeOutTime == 0.0f)
     {
         sh.emitter.fadeToKill.SetValue(0.0f);
     }
     else
     {
         sh.emitter.fadeToKill.SetValue(1.0f);
         sh.emitter.fadeToKill.MoveTo(0.0f, fadeOutTime);
     }
 }
    public override void OnPlayableCreate(Playable playable)
    {
        base.OnPlayableCreate(playable);

        var layer = LayerMask.NameToLayer("PostProcess Volumes");

        if (layer == -1)
        {
            GameDebug.LogWarning("Unable to find layer mask for camera fader");
        }

        m_Exposure = ScriptableObject.CreateInstance <AutoExposure>();
        m_Exposure.enabled.Override(true);
        m_Exposure.keyValue.Override(0);

        m_FadeVolume = PostProcessManager.instance.QuickVolume(layer, 100.0f, m_Exposure);
    }
    public override void OnInspectorGUI()
    {
        GUILayout.Label("Gather prefabs from current game config");

        var prefabAssetRef = target as PrefabAssetRegistryAuthoring;

        if (GUILayout.Button("Gather Prefabs"))
        {
            var refCollection = new WeakAssetReferenceCollection();
            GatherAssetReferences(refCollection, BuildType.Client);
            GatherAssetReferences(refCollection, BuildType.Server);

            //GameDebug.Log($"refCollection: {refCollection.References.Count}");


            prefabAssetRef.Assets.Clear();

            foreach (var reference in refCollection.References)
            {
                if (!reference.IsSet())
                {
                    continue;
                }

                var path  = AssetDatabase.GUIDToAssetPath(reference.ToGuidStr());
                var asset = AssetDatabase.LoadAssetAtPath <GameObject>(path);

                if (asset == null)
                {
                    GameDebug.LogWarning("Loading asset:" + reference.ToGuidStr() + " failed. Not a gameobject ?");
                    continue;
                }

                prefabAssetRef.Assets.Add(asset);
            }

            EditorUtility.SetDirty(target);
        }


        var assetsProperty = serializedObject.FindProperty("Assets");

        EditorGUILayout.PropertyField(assetsProperty);

//        DrawDefaultInspector();
    }
Exemplo n.º 11
0
        /// <summary>
        /// 销毁窗口(因为热更界面的需要,只在Editor中调用,其他地方不能使用)
        /// </summary>
        /// <param name="name"></param>
        public void DestroyWindow(string name)
        {
            UIBaseWindow baseWin;

            if (mWindows.TryGetValue(name, out baseWin))
            {
                if (baseWin.mUIObject != null)
                {
                    baseWin.Destroy();
                    DestroyWindowGameObject((GameObject)baseWin.mUIObject);
                    mWindows.Remove(name);
                }
            }
            else
            {
                GameDebug.LogWarning(string.Format("DestroyWindow {0} is null", name));
            }
        }
Exemplo n.º 12
0
        static int _m_LogWarning_xlua_st_(RealStatePtr L)
        {
            try {
                {
#if UNITY_EDITOR
                    string text = LuaAPI.lua_tostring(L, 1);

                    GameDebug.LogWarning(text);
#else
                    LuaAPI.lua_tostring_noret(L, 1);
#endif

                    return(0);
                }
            } catch (System.Exception __gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + __gen_e));
            }
        }
Exemplo n.º 13
0
        private object getCsObj(RealStatePtr L, int index, int udata)
        {
            object obj;

            if (udata == -1)
            {
                if (LuaAPI.lua_type(L, index) != LuaTypes.LUA_TUSERDATA)
                {
                    return(null);
                }

                Type type = GetTypeOf(L, index);
                if (type == typeof(decimal))
                {
                    decimal v;
                    Get(L, index, out v);
                    return(v);
                }
                GetCSObject get;
                if (type != null && custom_get_funcs.TryGetValue(type, out get))
                {
                    return(get(L, index));
                }
                else
                {
                    return(null);
                }
            }
            else if (objects.TryGetValue(udata, out obj))
            {
#if !UNITY_5 && !XLUA_GENERAL
                if (obj != null && obj is UnityEngine.Object && ((obj as UnityEngine.Object) == null))
                {
                    string log = string.Format("The object of type '{0}' has been destroyed but you are still trying to access it.", obj.GetType().Name);
                    GameDebug.LogWarning(log);
                    return(null);
                    //throw new UnityEngine.MissingReferenceException("The object of type '"+ obj.GetType().Name +"' has been destroyed but you are still trying to access it.");
                }
#endif
                return(obj);
            }
            return(null);
        }
Exemplo n.º 14
0
    public void Stop(SoundSystem.SoundHandle sh, float fadeOutTime = 0.0f)
    {
        if (!IsValid(ref sh))
        {
            GameDebug.LogWarning("SoundSystem.Stop(): invalid SoundHandle");
            return;
        }
        var emitter = m_Emitters[sh.emitter_idx];

        if (fadeOutTime == 0.0f)
        {
            emitter.fadeToKill.SetValue(0.0f);
        }
        else
        {
            emitter.fadeToKill.SetValue(1.0f);
            emitter.fadeToKill.MoveTo(0.0f, fadeOutTime);
        }
    }
Exemplo n.º 15
0
    static Entity GetRegistryEntity(EntityManager entityManager)
    {
        var query       = entityManager.CreateEntityQuery(typeof(PrefabAssetRegistry.Entry));
        var entityArray = query.ToEntityArray(Allocator.TempJob);

        if (entityArray.Length == 0)
        {
            GameDebug.LogError("Failed to find PrefabAssetRegistry. Have you included the PrefabAssetRegistry subscene ?");
        }
        if (entityArray.Length > 1)
        {
            GameDebug.LogWarning("Found " + entityArray.Length + " PrefabAssetRegistries. First one will be used");
        }

        var entity = entityArray.Length > 0 ? entityArray[0] : Entity.Null;

        entityArray.Dispose();
        query.Dispose();
        return(entity);
    }
Exemplo n.º 16
0
    public static void SetState <T>(Component owner, int tick, ref T state) where T : struct
    {
        if (!m_enabled)
        {
            return;
        }

        GenericData <T> entry = GetEntry <T>(owner);

        int index = entry.stateTicks.Register((uint)tick);

        entry.states[index] = state;

        int predictionIndex = entry.predictionTicks.GetIndex((uint)tick);

        if (predictionIndex != -1)
        {
            var predictedState = entry.predictions[predictionIndex] as IPredictedData <T>;
            if (predictedState != null)
            {
                if (!predictedState.VerifyPrediction(ref state))
                {
                    entry.mispredictedTicks.Add(tick);
                    System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
                    strBuilder.AppendLine("Prediction fail tick:" + tick);
                    strBuilder.AppendLine("PREDICTED");
                    strBuilder.Append(predictedState.ToString());
                    strBuilder.AppendLine("SERVER");
                    strBuilder.Append(state.ToString());
                    GameDebug.LogWarning(strBuilder.ToString());

                    if (mispredictEvent != null)
                    {
                        mispredictEvent();
                    }
                }
            }
        }

        HighestTick = Mathf.Max(HighestTick, tick);
    }
Exemplo n.º 17
0
        /// <summary>
        /// 触发相应的对话框
        /// </summary>
        /// <returns><c>true</c>, if dialog story was triggered, <c>false</c> otherwise.</returns>
        /// <param name="dialogInfo">Dialog info.</param>
        public bool TriggerDialogBox(DBDialog.DialogInfo dialogInfo, string customName, Actor otherPlayer, uint actorId, System.Action finishedCallback, System.Action skipedCallback, Task relatedTask)
        {
            ClearDialog();

            // 是否在系统开放中
            if (SysConfigManager.Instance.IsWaiting() == true)
            {
                GameDebug.LogWarning("DialogManager.TriggerDialogBox SysConfigManager is waiting!!");
                return(false);
            }

            if (dialogInfo != null)
            {
                GameDebug.Log("Trigger dialog box: " + dialogInfo.mId);

                mDialogInfo  = dialogInfo;
                mDialogIndex = 0;

                mCustomName  = customName;
                mOtherPlayer = otherPlayer;
                mActorId     = actorId;

                mFinishedCallback = finishedCallback;
                mSkipedCallback   = skipedCallback;

                mRelatedTask = relatedTask;

                ShowDialogWindow();

                return(true);
            }
            else
            {
                if (finishedCallback != null)
                {
                    finishedCallback();
                }
            }

            return(false);
        }
Exemplo n.º 18
0
    protected override void Update(Entity entity, CharPresentation charPresentation)
    {
        if (charPresentation.attached)
        {
            return;
        }

        if (!charPresentation.updateTransform)
        {
            return;
        }

        if (charPresentation.attachToPresentation == Entity.Null)
        {
            return;
        }


        if (!EntityManager.Exists(charPresentation.attachToPresentation))
        {
            GameDebug.LogWarning("Huhb ?");
            return;
        }

        var refPresentation =
            EntityManager.GetComponentObject <CharPresentation>(charPresentation.attachToPresentation);

        charPresentation.transform.parent        = refPresentation.itemAttachBone.transform;
        charPresentation.transform.localPosition = Vector3.zero;
        charPresentation.transform.localRotation = Quaternion.identity;
        charPresentation.attached = true;
        Debug.Log("Attached");


//        var refPresentation =
//            EntityManager.GetComponentObject<CharPresentation>(charPresentation.attachToPresentation);
//
//        charPresentation.transform.position = refPresentation.itemAttachBone.position;
//        charPresentation.transform.rotation = refPresentation.itemAttachBone.rotation;
    }
Exemplo n.º 19
0
        protected override void ResetUI()
        {
            base.ResetUI();

            var local_player = Game.GetInstance().GetLocalPlayer();

            if (local_player != null)
            {
                var sin_value = local_player.ActorAttribute.Sin;
                mSinLabel.text = string.Format("[FF0000]{0}", sin_value);
            }
            else
            {
#if UNITY_EDITOR
                GameDebug.LogWarning("UIWildEnterWindow LocalPlayer is null");
#endif
                mSinLabel.text = string.Format("[FF0000]{0}",
                                               LocalPlayerManager.Instance.LocalActorAttribute.Sin.ToString());
            }

            UpdateTmpBagNotEmpty();
        }
Exemplo n.º 20
0
    public static BlobAssetReference <Registry> GetRegistry(EntityManager entityManager)
    {
        var query = entityManager.CreateEntityQuery(typeof(RegistryEntity));

        var registryEntityArray = query.ToComponentDataArray <RegistryEntity>(Allocator.TempJob);

        if (registryEntityArray.Length == 0)
        {
            GameDebug.LogError("Failed to find entity HeroRegistry.RegistryEntity. Is it included in a scene ?");
        }
        if (registryEntityArray.Length > 1)
        {
            GameDebug.LogWarning("Found " + registryEntityArray.Length + " HeroRegistry.RegistryEntity entities. First one will be used");
        }

        var result = registryEntityArray.Length > 0 ? registryEntityArray[0].Value : BlobAssetReference <Registry> .Null;

        registryEntityArray.Dispose();
        query.Dispose();

        return(result);
    }
Exemplo n.º 21
0
    public SoundHandle Play(SoundDef soundDef)
    {
        GameDebug.Assert(soundDef != null);

        var e = AllocEmitter();

        if (e == null)
        {
            return(new SoundHandle(null));
        }

        if (soundDef.spatialBlend > 0.0f)
        {
            GameDebug.LogWarning(string.Format("Playing 3d {0} sound at 0,0,0", soundDef.name));
        }

        e.source.transform.position = new Vector3(0, 0, 0);
        e.repeatCount = Random.Range(soundDef.repeatMin, soundDef.repeatMax);
        e.playing     = true;
        e.soundDef    = soundDef;
        StartEmitter(e);
        return(new SoundHandle(e));
    }
Exemplo n.º 22
0
    public void WriteString(string name, char[] value, int length, int maxLength, OverrunBehaviour overrunBehaviour)
    {
        ValidateOrGenerateSchema(name, NetworkSchema.FieldType.String, 0, false, 0, maxLength);
        if (length == 0)
        {
            m_Output.WriteByteArray(null, 0, 0, maxLength);
            return;
        }

        GameDebug.Assert(maxLength <= s_ByteBuffer.Length, "NetworkWriter: Max length has to be less than {0}", s_ByteBuffer.Length);

        // Ensure the (utf-8) *encoded* string is not too big. If it is, cut it off,
        // convert back to unicode and then back again to utf-8. This little dance gives
        // a valid utf-8 string within the buffer size.
        var byteCount = NetworkConfig.encoding.GetBytes(value, 0, length, s_ByteBuffer, 0);

        if (byteCount > maxLength)
        {
            if (overrunBehaviour == OverrunBehaviour.AssertMaxLength)
            {
                GameDebug.Assert(false, "NetworkWriter : string {0} too long. (Using {1}/{2} allowed encoded bytes): ", value, byteCount, maxLength);
            }
            // truncate
            var truncWithBadEnd = NetworkConfig.encoding.GetString(s_ByteBuffer, 0, maxLength);
            var truncOk         = truncWithBadEnd.Substring(0, truncWithBadEnd.Length - 1);
            var newbyteCount    = NetworkConfig.encoding.GetBytes(truncOk, 0, truncOk.Length, s_ByteBuffer, 0);

            if (overrunBehaviour == OverrunBehaviour.WarnAndTrunc)
            {
                GameDebug.LogWarning(string.Format("NetworkWriter : truncated string with {0} bytes. (result: {1})", byteCount - newbyteCount, truncOk));
            }
            byteCount = newbyteCount;
            GameDebug.Assert(byteCount <= maxLength);
        }

        m_Output.WriteByteArray(s_ByteBuffer, 0, byteCount, maxLength);
    }
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        dstManager.AddComponentData(entity, new AnimSource.Data());
        dstManager.AddComponentData(entity, settings);
        dstManager.AddBuffer <AnimSourceSprintBlend.AnimSourceEntities>(entity);

        // TODO: Try to use Native Array version of buffer, once the code works
        // Add child AnimSources
        int numChildren = 0;

        for (var i = 0; i < transform.childCount; i++)
        {
            var child = transform.GetChild(i);

            if (child.GetComponent <AnimSourceAuthoring>() == null)
            {
                continue;
            }

            var entryEntity = conversionSystem.GetPrimaryEntity(child.gameObject);

            var childAnimSourceEntities = dstManager.GetBuffer <AnimSourceSprintBlend.AnimSourceEntities>(entity);
            var e = new AnimSourceSprintBlend.AnimSourceEntities {
                Value = entryEntity
            };
            childAnimSourceEntities.Add(e);

            numChildren++;
        }

        if (numChildren != 2)
        {
            GameDebug.LogWarning($"Sprint Blend supports exactly child AnimSources, seems you are using the wrong number: {numChildren}/{transform.childCount}");
        }

//        GameDebug.Log("CREATING SPRINT BLEND");
    }
Exemplo n.º 24
0
    public void AddReference(WeakAssetReference reference)
    {
        if (!reference.IsSet())
        {
            return;
        }

        if (references.Contains(reference))
        {
            return;
        }

        var path = AssetDatabase.GUIDToAssetPath(reference.ToGuidStr());

        if (String.IsNullOrEmpty(path))
        {
            GameDebug.LogWarning("Asset does not exist:" + reference.ToGuidStr());
            return;
        }

        GameDebug.Log("Adding asset:" + reference.ToGuidStr() + " " + path);

        references.Add(reference);
    }
Exemplo n.º 25
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var PostUpdateCommands     = new EntityCommandBuffer(Allocator.TempJob);
        var LocalToWorldFromEntity = GetComponentDataFromEntity <Unity.Transforms.LocalToWorld>(true);

        Entities
        .WithReadOnly(LocalToWorldFromEntity)
        .WithNativeDisableContainerSafetyRestriction(PostUpdateCommands)
        .WithoutBurst()     // Uses EntityManager.Exists
        .ForEach((Entity e, ref SoundRequest req) =>
        {
            // If handle is invalid, let go of this tracker
            if (!SoundSystem.Instance.IsValid(ref req.soundHandle))
            {
                PostUpdateCommands.DestroyEntity(e);
                return;
            }
            // Update position
            if (!EntityManager.Exists(req.trackEntity))
            {
                GameDebug.LogWarning("Sound trying to follow invalid entity " + req.trackEntity);
                PostUpdateCommands.DestroyEntity(e);
                return;
            }
            if (!LocalToWorldFromEntity.HasComponent(req.trackEntity))
            {
                GameDebug.LogWarning("Sound trying to follow entity " + req.trackEntity + " which does not have a transform");
                PostUpdateCommands.DestroyEntity(e);
                return;
            }
            var ltw = LocalToWorldFromEntity[req.trackEntity];
            SoundSystem.Instance.UpdatePosition(ref req.soundHandle, ltw.Position);
        }).Run();
        PostUpdateCommands.Playback(EntityManager);
        PostUpdateCommands.Dispose();
        return(default);
Exemplo n.º 26
0
    public void Update()
    {
        if (!m_isHeadless)
        {
            RenderSettings.Update();
        }

        // TODO (petera) remove this hack once we know exactly when renderer is available...
        if (!pipeSetup)
        {
            var hdpipe = RenderPipelineManager.currentPipeline as HDRenderPipeline;
            if (hdpipe != null)
            {
//                hdpipe.DebugLayer2DCallback = DebugOverlay.Render;
//                hdpipe.DebugLayer3DCallback = DebugOverlay.Render3D;

                var layer = LayerMask.NameToLayer("PostProcess Volumes");
                if (layer == -1)
                {
                    GameDebug.LogWarning("Unable to find layer mask for camera fader");
                }
                else
                {
                    m_Exposure        = ScriptableObject.CreateInstance <AutoExposure>();
                    m_Exposure.active = false;
                    m_Exposure.enabled.Override(true);
                    m_Exposure.keyValue.Override(0);
                    m_ExposureVolume = PostProcessManager.instance.QuickVolume(layer, 100.0f, m_Exposure);
                }

                pipeSetup = true;
            }
        }
        if (m_ExposureReleaseCount > 0)
        {
            m_ExposureReleaseCount--;
            if (m_ExposureReleaseCount == 0)
            {
                BlackFade(false);
            }
        }

        // Verify if camera was somehow destroyed and pop it
        if (m_CameraStack.Count > 1 && m_CameraStack[m_CameraStack.Count - 1] == null)
        {
            PopCamera(null);
        }

#if UNITY_EDITOR
        // Ugly hack to force focus to game view when using scriptable renderloops.
        if (Time.frameCount < 4)
        {
            try
            {
                var gameViewType = typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.GameView");
                var gameView     = (EditorWindow)Resources.FindObjectsOfTypeAll(gameViewType)[0];
                gameView.Focus();
            }
            catch (System.Exception) { /* too bad */ }
        }
#endif

        frameTime = (double)m_Clock.ElapsedTicks / m_StopwatchFrequency;

        // Switch game loop if needed
        if (m_RequestedGameLoopTypes.Count > 0)
        {
            // Multiple running gameloops only allowed in editor
#if !UNITY_EDITOR
            ShutdownGameLoops();
#endif
            bool initSucceeded = false;
            for (int i = 0; i < m_RequestedGameLoopTypes.Count; i++)
            {
                try
                {
                    IGameLoop gameLoop = (IGameLoop)System.Activator.CreateInstance(m_RequestedGameLoopTypes[i]);
                    initSucceeded = gameLoop.Init(m_RequestedGameLoopArguments[i]);
                    if (!initSucceeded)
                    {
                        break;
                    }

                    m_gameLoops.Add(gameLoop);
                }
                catch (System.Exception e)
                {
                    GameDebug.Log(string.Format("Game loop initialization threw exception : ({0})\n{1}", e.Message, e.StackTrace));
                }
            }


            if (!initSucceeded)
            {
                ShutdownGameLoops();

                GameDebug.Log("Game loop initialization failed ... reverting to boot loop");
            }

            m_RequestedGameLoopTypes.Clear();
            m_RequestedGameLoopArguments.Clear();
        }

        try
        {
            if (!m_ErrorState)
            {
                foreach (var gameLoop in m_gameLoops)
                {
                    gameLoop.Update();
                }
                levelManager.Update();
            }
        }
        catch (System.Exception e)
        {
            HandleGameloopException(e);
            throw;
        }

        if (m_SoundSystem != null)
        {
            m_SoundSystem.Update();
        }

        if (clientFrontend != null)
        {
            clientFrontend.UpdateGame();
        }

        Console.ConsoleUpdate();

        WindowFocusUpdate();

        UpdateCPUStats();

        sqpClient.Update();

        endUpdateEvent?.Invoke();
    }
Exemplo n.º 27
0
        protected override void OnUpdate()
        {
            // Camera.main may not be available when the system is created, so need this to set it for the first time
            if (MainCamera == null)
            {
                if (Camera.main != null)
                {
                    MainCamera = Camera.main;
                }
                else
                {
                    GameDebug.LogWarning("PartOwner update: No camera.main");
                    return;
                }
            }

            var camPos = (float3)MainCamera.transform.position;

            // TODO: Jobified ForEach blocked by PrefabAssetRegistry.CreateEntity
            Entities.ForEach((Entity partOwnerEntity, ref Translation translation, ref RegistryAsset registryAsset, ref InputState inputState,
                              ref State state) =>
            {
                var registry = PartRegistry.GetPartRegistry(World, registryAsset.Value);

                // Calc lod
                var charPos = translation.Value;
                var dist    = math.distance(camPos, charPos);
                var newLod  = -1;
                // TODO (mogensh) add threshold that needs to be passed before change (so it does not flicker)
                for (int lod = 0; lod < registry.Value.LODLevels.Length; lod++)
                {
                    if (dist <= registry.Value.LODLevels[lod].EndDist)
                    {
                        newLod = lod;
                        break;
                    }
                }


                // TODO (mogensh) hack: force LOD 0
                newLod = 0;


                // Handle out of lod distance specifically
                if (newLod == -1)
                {
                    if (state.currentLOD != newLod)
                    {
                        state.currentLOD = newLod;

                        GameDebug.Log(Part.ShowLifetime, "Out of LOD distance");

                        var partBuf = EntityManager.GetBuffer <PartElement>(partOwnerEntity)
                                      .ToNativeArray(Allocator.Temp);
                        var partOutBuf = PostUpdateCommands.SetBuffer <PartElement>(partOwnerEntity);
                        partOutBuf.ResizeUninitialized(partBuf.Length);
                        for (int j = 0; j < partBuf.Length; j++)
                        {
                            var partElement = partBuf[j];

                            // Destroy old part
                            if (partElement.PartId != 0)
                            {
                                if (partElement.PartEntity != Entity.Null)
                                {
                                    GameDebug.Log(Part.ShowLifetime, "Destroying part. Category:{0} partId:{1}", j,
                                                  partElement.PartId);
                                    PostUpdateCommands.DestroyEntity(partElement.PartEntity);
                                }

                                partElement.PartEntity = Entity.Null;
                                partElement.PartId     = 0;
                                partElement.Asset      = WeakAssetReference.Default;
                            }

                            partOutBuf[j] = partElement;
                        }

                        PostUpdateCommands.SetComponent(partOwnerEntity, state);
                    }


                    return;
                }



                var newRig = BlobAssetReference <RigDefinition> .Null;
                if (EntityManager.HasComponent <SharedRigDefinition>(partOwnerEntity))
                {
                    newRig = EntityManager.GetSharedComponentData <SharedRigDefinition>(partOwnerEntity).Value;
                }


                // Change bodypart if LOD or rig changed
                var packedPartIds = inputState.PackedPartIds;
                if (packedPartIds != state.CurrentPackedPartIds ||
                    newLod != state.currentLOD ||
                    (newRig != BlobAssetReference <RigDefinition> .Null && newRig != state.currentRig))
                {
                    var partBuf = EntityManager.GetBuffer <PartElement>(partOwnerEntity).ToNativeArray(Allocator.Temp);


                    var partIds = new NativeArray <int>(partBuf.Length, Allocator.Temp);
                    registry.Value.UnpackPartsList(inputState.PackedPartIds, partIds);

                    GameDebug.Log(World, Part.ShowLifetime, "Property changed. Lod:{0}", newLod);

                    var partOutBuf = PostUpdateCommands.SetBuffer <PartElement>(partOwnerEntity);
                    partOutBuf.ResizeUninitialized(partBuf.Length);
                    for (int j = 0; j < partBuf.Length; j++)
                    {
                        var partId      = partIds[j];
                        var partElement = partBuf[j];

                        // Find new asset given the new properties
                        var asset = new WeakAssetReference();
                        if (partId > 0)
                        {
                            var skeletonHash = newRig.IsCreated ? newRig.Value.GetHashCode() : 0;
                            var found        = registry.Value.FindAsset(j, partId, skeletonHash, newLod, ref asset);
                            if (!found)
                            {
                                GameDebug.Log(World, Part.ShowLifetime,
                                              "Failed to find valid part. Category:{0} PartId:{1}", j, partId);
                            }
                        }


                        // No change if asset has not changed
                        if (partElement.Asset == asset)
                        {
                            partOutBuf[j] = partElement;
                            continue;
                        }


                        // Destroy old part
                        if (partElement.PartId != 0)
                        {
                            if (partElement.PartEntity != Entity.Null)
                            {
                                GameDebug.Log(World, Part.ShowLifetime, "Destroying part. Category:{0} partId:", j,
                                              partElement.PartId);
                                PostUpdateCommands.DestroyEntity(partElement.PartEntity);
                            }

                            partElement.PartEntity = Entity.Null;
                            partElement.PartId     = 0;
                            partElement.Asset      = WeakAssetReference.Default;
                        }

                        // Create new part
                        if (partId != 0 && asset.IsSet())
                        {
                            partElement.PartEntity = PrefabAssetManager.CreateEntity(EntityManager, asset);
                            partElement.PartId     = partId;
                            partElement.Asset      = asset;

                            if (partElement.PartEntity != Entity.Null)
                            {
                                GameDebug.Log(World, Part.ShowLifetime,
                                              "Creating part. Owner:{0} Cat:{1} PartId:{2} Asset:{3} part:{4}", partOwnerEntity,
                                              j, partId, asset.ToGuidStr(), partElement.PartEntity);
                                var part   = Part.Owner.Default;
                                part.Value = partOwnerEntity;
                                PostUpdateCommands.SetComponent(partElement.PartEntity, part);

                                // TODO (mogensh) add "static" property on owner (or get somehow). If static just set world transform
                                PostUpdateCommands.AddComponent(partElement.PartEntity,
                                                                new Parent {
                                    Value = partOwnerEntity
                                });
                                PostUpdateCommands.AddComponent(partElement.PartEntity, new LocalToParent());
                            }
                            else
                            {
                                GameDebug.LogError("Failed to create part. Asset:" + asset.ToGuidStr());
                            }
                        }

                        partOutBuf[j] = partElement;
                    }

                    state.CurrentPackedPartIds = packedPartIds;
                    state.currentRig           = newRig;
                    state.currentLOD           = newLod;
                    PostUpdateCommands.SetComponent(partOwnerEntity, state);
                }
            });
        }
Exemplo n.º 28
0
    public void Update()
    {
        if (focus != Application.isFocused)
        {
            focus = Application.isFocused;
            if (SoundSystem.soundMute.IntValue == -1)
            {
                m_MasterVolume.MoveTo(focus ? 1.0f : 0.0f, 0.5f);
            }
        }

        var masterVolume = m_MasterVolume.GetValue();

        if (SoundSystem.soundMute.IntValue == 0)
        {
            masterVolume = 0.0f;
            Overlay.Managed.Write(Overlay.Color.Red, Overlay.Managed.CellsWide - 10, 2, "{0}", "AUDIO MUTED");
        }
        else if (SoundSystem.soundMute.IntValue == 1)
        {
            masterVolume = 1.0f;
            Overlay.Managed.Write(Overlay.Color.Green, Overlay.Managed.CellsWide - 10, 2, "{0}", "AUDIO PLAYING");
        }

        m_AudioMixer.SetFloat("MasterVolume", DecibelFromAmplitude(Mathf.Clamp(SoundSystem.soundMasterVol.FloatValue, 0.0f, 1.0f) * masterVolume));
        m_AudioMixer.SetFloat("MusicVolume", DecibelFromAmplitude(Mathf.Clamp(SoundSystem.soundMusicVol.FloatValue, 0.0f, 1.0f)));
        m_AudioMixer.SetFloat("SFXVolume", DecibelFromAmplitude(Mathf.Clamp(SoundSystem.soundSFXVol.FloatValue, 0.0f, 1.0f)));
        m_AudioMixer.SetFloat("MenuVolume", DecibelFromAmplitude(Mathf.Clamp(SoundSystem.soundMenuVol.FloatValue, 0.0f, 1.0f)));

        // Update running sounds
        int count = 0;

        foreach (var e in m_Emitters)
        {
            if (!e.playing)
            {
                continue;
            }
            if (e.source == null)
            {
                // Could happen if parent was killed. Not good, but fixable:
                GameDebug.LogWarning("Soundemitter had its audiosource destroyed. Making a new.");
                e.source      = MakeAudioSource();
                e.repeatCount = 0;
            }
            if (e.fadeToKill.IsMoving())
            {
                e.source.volume = AmplitudeFromDecibel(e.soundDef.volume) * e.fadeToKill.GetValue();
            }
            else if (e.fadeToKill.GetValue() == 0.0f)
            {
                // kill no matter what
                e.Kill();
            }
            if (e.source.isPlaying)
            {
                count++;
                continue;
            }
            if (e.repeatCount > 1)
            {
                e.repeatCount--;
                StartEmitter(e);
                continue;
            }
            // Reset for reuse
            e.playing = false;
            e.seqId   = -1; // make handles invalid
            e.source.transform.parent = m_SourceHolder.transform;
            e.source.enabled          = true;
            e.source.gameObject.SetActive(true);
            e.source.transform.position = Vector3.zero;
            e.fadeToKill.SetValue(1.0f);
        }
        if (SoundSystem.soundDebug.IntValue > 0)
        {
//            Overlay.Managed.Write(30, 1, "Mixer: {0} {1}", m_AudioMixer.GetInstanceID(), Game.game.audioMixer.GetInstanceID());
            int ii = 4;
            foreach (var o in GameObject.FindObjectsOfType <AudioMixerGroup>())
            {
                Overlay.Managed.Write(30, ii++, "group: {0} {1}", o.name, o.GetInstanceID());
            }
            Overlay.Managed.Write(1, 1, "Num audios {0}", count);
            for (int i = 0, c = m_Emitters.Length; i < c; ++i)
            {
                var e = m_Emitters[i];
                Overlay.Managed.Write(1, 3 + i, "Emitter {0:##}  {1} {2} {3}", i, e.playing ? e.soundDef.name : "<n/a>", e.source.gameObject.activeInHierarchy ? "act" : "nact", e.playing ? "Mixer: " + e.source.outputAudioMixerGroup.audioMixer.GetInstanceID() : "");
            }
            if (m_CurrentListener == null)
            {
                Overlay.Managed.Write(Overlay.Managed.CellsWide / 2 - 5, Overlay.Managed.CellsTall, "No AudioListener?");
                return;
            }
            for (int i = 0, c = m_Emitters.Length; i < c; ++i)
            {
                var e = m_Emitters[i];
                if (!e.playing)
                {
                    continue;
                }
                var     s      = e.source.spatialBlend;
                Vector3 locpos = m_CurrentListener.transform.InverseTransformPoint(e.source.transform.position);
                int     x      = (int)Mathf.Lerp(e.source.panStereo * 10.0f, Mathf.Clamp(locpos.x, -10, 10), s);;
                int     z      = (int)Mathf.Lerp(-10.0f, Mathf.Clamp(locpos.z, -10, 10), s);
                Overlay.Managed.Write(s < 0.5 ? Overlay.Color.Green : Overlay.Color.Blue, Overlay.Managed.CellsWide / 2 + x, Overlay.Managed.CellsTall / 2 - z, "{0} ({1:##.#})", e.soundDef.name, locpos.magnitude);
            }
        }
    }
Exemplo n.º 29
0
        public Instance(EntityManager entityManager, Entity owner, PlayableGraph graph, AnimGraph_StateSelector settings)
        {
            m_settings      = settings;
            m_graph         = graph;
            m_EntityManager = entityManager;
            m_Owner         = owner;

            animStateMixer = AnimationMixerPlayable.Create(m_graph, 0, true);
            m_RootPlayable = animStateMixer;

            // Animation states
            animStates = new AnimationControllerEntry[(int)CharacterAnimationState.NumStates];

            // Instantiate controllers. We only create one of each type even though it might be used in multiple animation states
            var controllers          = new Dictionary <AnimGraphAsset, IAnimGraphInstance>();
            var controllerPorts      = new Dictionary <IAnimGraphInstance, int>();
            var stateTransitionPorts = new List <int>();
            var transitionTimes      = new Dictionary <IAnimGraphInstance, float[]>();

            foreach (var controllderDef in m_settings.controllers)
            {
                if (controllderDef.template == null)
                {
                    continue;
                }

                if (controllers.ContainsKey(controllderDef.template))
                {
                    continue;
                }

                var controller = controllderDef.template.Instatiate(entityManager, owner, m_graph);
                controllers.Add(controllderDef.template, controller);

                var outputPlayable = Playable.Null;
                var outputPort     = 0;
                controller.GetPlayableOutput(0, ref outputPlayable, ref outputPort);
                var port = animStateMixer.AddInput(outputPlayable, outputPort);

                controllerPorts.Add(controller, port);
                stateTransitionPorts.Add(port);

                var times = new float[(int)CharacterAnimationState.NumStates];
                for (var i = 0; i < (int)CharacterAnimationState.NumStates; i++)
                {
                    times[i] = controllderDef.transitionTime;
                }

                for (var i = 0; i < controllderDef.customTransitions.Length; i++)
                {
                    var sourceStateIndex = (int)controllderDef.customTransitions[i].sourceState;
                    var time             = controllderDef.customTransitions[i].transtionTime;
                    times[sourceStateIndex] = time;
                }

                transitionTimes.Add(controller, times);
            }

            // Setup states specifically defined
            foreach (var controllderDef in m_settings.controllers)
            {
                var animState = controllderDef.animationState;
                if (animStates[(int)animState].controller != null)
                {
                    GameDebug.LogWarning("Animation state already registered");
                    continue;
                }

                var controller = controllers[controllderDef.template];
                animStates[(int)animState].controller       = controller;
                animStates[(int)animState].animStateUpdater = controller as IGraphState;
                animStates[(int)animState].port             = controllerPorts[controller];
                animStates[(int)animState].transitionTimes  = transitionTimes[controller];
            }

            m_StateTranstion = new SimpleTranstion <AnimationMixerPlayable>(animStateMixer, stateTransitionPorts.ToArray());
        }
Exemplo n.º 30
0
    int AllocEmitter()
    {
        // Look for unused emitter
        for (int i = 0; i < m_Emitters.Length; ++i)
        {
            var e = m_Emitters[i];
            if (!e.playing)
            {
                e.seqId = m_SequenceId++;
                return(i);
            }
        }

        // Hunt down one emitter to kill
        int   emitter_idx = -1;
        float distance    = float.MinValue;
        var   listenerPos = m_CurrentListener != null ? m_CurrentListener.transform.position : Vector3.zero;

        for (var i = 0; i < m_Emitters.Length; ++i)
        //foreach (var e in m_Emitters)
        {
            var e = m_Emitters[i];

            var s = e.source;

            if (s == null)
            {
                // Could happen if parent was killed. Not good, but fixable:
                GameDebug.LogWarning("Soundemitter had its audiosource destroyed. Making a new.");
                e.source      = MakeAudioSource();
                e.repeatCount = 0;
                s             = e.source;
            }

            // Skip destroyed sources and looping sources
            if (s.loop)
            {
                continue;
            }

            // Pick closest; assuming 2d sounds very close!
            var dist = 0.0f;
            if (s.spatialBlend > 0.0f)
            {
                dist = (s.transform.position - listenerPos).magnitude;

                // if tracking another object assume closer
                var t = s.transform;
                if (t.parent != m_SourceHolder.transform)
                {
                    dist *= 0.5f;
                }
            }

            if (dist > distance)
            {
                distance    = dist;
                emitter_idx = i;
            }
        }
        if (emitter_idx != -1)
        {
            var e = m_Emitters[emitter_idx];
            e.Kill();
            e.seqId = m_SequenceId++;
            return(emitter_idx);
        }
        GameDebug.Log("Unable to allocate sound emitter!");
        return(-1);
    }