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(); }
public bool Init(string[] args) { m_StateMachine = new StateMachine <ClientState>(); m_StateMachine.Add(ClientState.Browsing, EnterBrowsingState, UpdateBrowsingState, LeaveBrowsingState); m_StateMachine.Add(ClientState.Connecting, EnterConnectingState, UpdateConnectingState, null); m_StateMachine.Add(ClientState.Loading, EnterLoadingState, UpdateLoadingState, null); m_StateMachine.Add(ClientState.Playing, EnterPlayingState, UpdatePlayingState, LeavePlayingState); #if UNITY_EDITOR Game.game.levelManager.UnloadLevel(); #endif m_GameWorld = new GameWorld("ClientWorld"); m_NetworkTransport = new SocketTransport(); m_NetworkClient = new NetworkClient(m_NetworkTransport); if (Application.isEditor || Game.game.buildId == "AutoBuild") { NetworkClient.clientVerifyProtocol.Value = "0"; } m_NetworkClient.UpdateClientConfig(); m_NetworkStatistics = new NetworkStatisticsClient(m_NetworkClient); m_ChatSystem = new ChatSystemClient(m_NetworkClient); GameDebug.Log("Network client initialized"); m_requestedPlayerSettings.playerName = clientPlayerName.Value; m_requestedPlayerSettings.teamId = -1; Console.AddCommand("disconnect", CmdDisconnect, "Disconnect from server if connected", this.GetHashCode()); Console.AddCommand("prediction", CmdTogglePrediction, "Toggle prediction", this.GetHashCode()); Console.AddCommand("runatserver", CmdRunAtServer, "Run command at server", this.GetHashCode()); Console.AddCommand("respawn", CmdRespawn, "Force a respawn", this.GetHashCode()); Console.AddCommand("nextchar", CmdNextChar, "Select next character", this.GetHashCode()); Console.AddCommand("nextteam", CmdNextTeam, "Select next character", this.GetHashCode()); Console.AddCommand("spectator", CmdSpectator, "Select spectator cam", this.GetHashCode()); Console.AddCommand("matchmake", CmdMatchmake, "matchmake <hostname[:port]/{projectid}>: Find and join a server", this.GetHashCode()); if (args.Length > 0) { targetServer = args[0]; m_StateMachine.SwitchTo(ClientState.Connecting); } else { m_StateMachine.SwitchTo(ClientState.Browsing); } ReplicatedPrefabMgr.Initialize(); ClientServerSystemManager.InitClientSystems(); World.Active.GetExistingSystem <TickClientSimulationSystem>().Enabled = true; World.Active.GetExistingSystem <TickClientPresentationSystem>().Enabled = true; Unity.Networking.Transport.NetworkEndPoint ep = Unity.Networking.Transport.NetworkEndPoint.Parse(targetServer, (ushort)NetworkConfig.netcodeServerPort); World clientWorld = ClientServerSystemManager.clientWorld; EntityManager em = clientWorld.EntityManager; Entity ent = clientWorld.GetExistingSystem <NetworkStreamReceiveSystem>().Connect(ep); em.AddComponentData(ent, new NetworkStreamInGame()); GameDebug.Log("Client initialized"); return(true); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { inputDeps.Complete(); var nodeSet = m_AnimationGraphSystem.Set; var commands = new EntityCommandBuffer(Allocator.TempJob); var ownedAbilityBufferFromEntity = GetBufferFromEntity <AbilityOwner.OwnedAbility>(true); // Handle created entities Entities .WithoutBurst() // Can be removed once NodeSets are Burst-friendly .WithNone <SystemState>() .ForEach((Entity entity, ref AnimSource.Data animSource, ref Settings settings) => { // GameDebug.Log("Init Run"); var state = SystemState.Default; var abilityMovementEntity = Ability.FindAbility(ownedAbilityBufferFromEntity, animSource.animStateEntity, AbilityMovement.Tag); if (abilityMovementEntity == Entity.Null) { return; } var abilityMovementSettings = EntityManager.GetComponentData <AbilityMovement.Settings>(abilityMovementEntity); state.JumpNode = AnimationGraphHelper.CreateNode <ClipPlayerNode>(m_AnimationGraphSystem, "JumpNode"); state.DeltaTimeNode = AnimationGraphHelper.CreateNode <DeltaTimeNode>(m_AnimationGraphSystem, "DeltaTimeNode"); state.AimVerticalNode = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "AimVerticalNode"); state.AimHorizontalNode = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "AimHorizontalNode"); state.AdditiveRefPoseA = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "AdditiveRefPoseA"); state.AdditiveRefPoseB = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "AdditiveRefPoseB"); state.AimVerticalDelta = AnimationGraphHelper.CreateNode <DeltaNode>(m_AnimationGraphSystem, "AimVerticalDelta"); state.AimHorizontalDelta = AnimationGraphHelper.CreateNode <DeltaNode>(m_AnimationGraphSystem, "AimHorizontalDelta"); state.MixerNode = AnimationGraphHelper.CreateNode <LayerMixerNode>(m_AnimationGraphSystem, "MixerNode"); nodeSet.SendMessage(state.JumpNode, ClipPlayerNode.SimulationPorts.Speed, 1.0f); nodeSet.SendMessage(state.MixerNode, LayerMixerNode.SimulationPorts.WeightInput0, 1f); nodeSet.SendMessage(state.MixerNode, LayerMixerNode.SimulationPorts.WeightInput1, 1f); nodeSet.SendMessage(state.MixerNode, LayerMixerNode.SimulationPorts.WeightInput2, 1f); nodeSet.SendMessage(state.MixerNode, LayerMixerNode.SimulationPorts.BlendModeInput1, BlendingMode.Additive); nodeSet.SendMessage(state.MixerNode, LayerMixerNode.SimulationPorts.BlendModeInput2, BlendingMode.Additive); nodeSet.Connect(state.DeltaTimeNode, DeltaTimeNode.KernelPorts.DeltaTime, state.JumpNode, ClipPlayerNode.KernelPorts.DeltaTime); nodeSet.Connect(state.JumpNode, ClipPlayerNode.KernelPorts.Output, state.MixerNode, LayerMixerNode.KernelPorts.Input0); nodeSet.Connect(state.AdditiveRefPoseA, ClipNode.KernelPorts.Output, state.AimVerticalDelta, DeltaNode.KernelPorts.Subtract); nodeSet.Connect(state.AdditiveRefPoseB, ClipNode.KernelPorts.Output, state.AimHorizontalDelta, DeltaNode.KernelPorts.Subtract); nodeSet.Connect(state.AimVerticalNode, ClipNode.KernelPorts.Output, state.AimVerticalDelta, DeltaNode.KernelPorts.Input); nodeSet.Connect(state.AimHorizontalNode, ClipNode.KernelPorts.Output, state.AimHorizontalDelta, DeltaNode.KernelPorts.Input); nodeSet.Connect(state.AimVerticalDelta, DeltaNode.KernelPorts.Output, state.MixerNode, LayerMixerNode.KernelPorts.Input1); nodeSet.Connect(state.AimHorizontalDelta, DeltaNode.KernelPorts.Output, state.MixerNode, LayerMixerNode.KernelPorts.Input2); // Store clip info state.AimVerticalDuration = settings.JumpAimVerticalClip.Value.Duration; state.AimHorizontalDuration = settings.JumpAimHorizontalClip.Value.Duration; state.JumpDuration = settings.JumpClip.Value.Duration; // Adjust play speed so vertical velocity in animation is matched with character velocity (so feet doesnt penetrate ground) var animJumpVel = settings.jumpHeight / settings.JumpClip.Value.Duration; var characterJumpVel = abilityMovementSettings.jumpAscentVelocity; if (characterJumpVel > 0f && animJumpVel > 0f) { state.PlaySpeed = characterJumpVel / animJumpVel; } else { GameDebug.LogWarning("Cannot set jump anim speed, values need to be more than 0"); } // Expose input and outputs animSource.outputNode = state.MixerNode; animSource.outputPortID = (OutputPortID)LayerMixerNode.KernelPorts.Output; commands.AddComponent(entity, state); }).Run(); // Handled deleted entities var animationGraphSystem = m_AnimationGraphSystem; Entities .WithoutBurst() // Can be removed once NodeSets are Burst-friendly .WithNone <Settings>() .ForEach((Entity entity, ref SystemState state) => { Deinitialize(commands, entity, animationGraphSystem, state); }).Run(); commands.Playback(EntityManager); commands.Dispose(); return(default);
public void StoneComb(DefenceUIParam uiparam) { PlayerDataModule module = ModuleManager.Instance.FindModule <PlayerDataModule>(); if (null == module) { return; } StoneTableItem stoneitem = null; if (uiparam.isequiped) { DefenceObj defencedata = module.GetItemByIDAndPos(uiparam.itemid, uiparam.packpos, uiparam.packtype) as DefenceObj; if (null == defencedata) { return; } stoneitem = DataManager.StoneTable[defencedata.GetStoneInfoByPos(uiparam.stonepos).stoneid] as StoneTableItem; } else { stoneitem = DataManager.StoneTable[uiparam.stoneid] as StoneTableItem; } if (null == stoneitem) { return; } if (-1 == stoneitem.combid) { //宝石已达最高等级 PopTipManager.Instance.AddNewTip(StringHelper.GetString("stonesmax")); return; } DefenceCombItem combItem = DataManager.DefenceCombTable[stoneitem.combid] as DefenceCombItem; if (null == combItem) { //弹窗:宝石无法合成 PopTipManager.Instance.AddNewTip(StringHelper.GetString("stone_comb_error")); return; } if (module.GetProceeds(ProceedsType.Money_Game) < combItem.moenyused) { //弹窗:玩家金币不足 PopTipManager.Instance.AddNewTip(StringHelper.GetString("money_game_shortage")); return; } uint playerhascitem = module.GetItemNumByID(combItem.item1, PackageType.Pack_Gem); if (uiparam.isequiped) { playerhascitem += 1; } if (playerhascitem < combItem.num1) { ////弹窗:道具【名称】【个数】不足 stoneitem = DataManager.StoneTable[combItem.item1] as StoneTableItem; if (null == stoneitem) { GameDebug.LogError("stone.txt中没有此宝石 id = " + combItem.item1); return; } PopTipManager.Instance.AddNewTip(StringHelper.GetString("item_need").Replace("?", stoneitem.name)); return; } StoneCombActionParam param = new StoneCombActionParam(); param.DefenceId = uiparam.itemid; param.stoneId = stoneitem.id; param.PackType = (int)uiparam.packtype; param.pos = uiparam.packpos; param.stonepos = uiparam.stonepos; param.isequiped = uiparam.isequiped; Net.Instance.DoAction((int)Message.MESSAGE_ID.ID_MSG_DEFENCE_STONE_COMB, param); }
void OnMatchmakingError(string errorInfo) { GameDebug.LogError($"Matchmaking failed! Error is: {errorInfo}"); m_useMatchmaking = false; m_matchmaker = null; }
public int[] combo_time; //普攻连击限制 //-------------------------------------------------------------------------------------- public override void ParseJson(object jd) { Dictionary <string, object> item = (Dictionary <string, object>)jd; skill_id = item.TryGetLong("skillid"); name = item.TryGetString("name"); hero_id = item.TryGetLong("hero_id"); skill_name = item.TryGetString("skill_name"); des = item.TryGetString("des"); skill_atlas = item.TryGetString("icon_atlas"); skill_icon = item.TryGetString("skill_icon"); spell_motion = item.TryGetString("skill_motion"); sound = item.TryGetString("sound"); hit_sound = item.TryGetString("hit_sound"); target_ceiling = item.TryGetByte("target_ceiling"); attack_type = item.TryGetByte("attack_type"); types = item.TryGetByte("types"); dist = item.TryGetFloat("dist"); castBefore = item.TryGetFloat("end_motion"); if (item.ContainsKey("singular_aoe")) { isSingle = item["singular_aoe"] == null ? true : byte.Parse(item["singular_aoe"].ToString()) == 0; } if (item.ContainsKey("ignore_terrain")) { ignoreTerrain = item["ignore_terrain"] == null ? false : byte.Parse(item["ignore_terrain"].ToString()) == 0; } if (item.ContainsKey("pierce through")) { isPierce = item["pierce through"] == null ? false : byte.Parse(item["pierce through"].ToString()) == 0; } flight_speed = item.TryGetFloat("flight_speed"); if (item.ContainsKey("max_fly")) { max_fly = item["max_fly"] == null ? 0 : float.Parse(item["max_fly"].ToString()); } skill_type = item.ContainsKey("skill_type") && item["skill_type"] != null ? (SkillCastType)byte.Parse(item["skill_type"].ToString()) : (SkillCastType)0; if (item.ContainsKey("range_type")) { range_type = (rangeType)byte.Parse(item["range_type"].ToString()); } aoe_long = item.TryGetFloat("aoe_long"); aoe_wide = item.TryGetFloat("aoe_wide"); angle = item.TryGetFloat("angle"); site = item.TryGetInt("site"); seat = item.TryGetInt("seat"); alertedType = item.TryGetInt("alerted_type"); length_base = item.TryGetFloat("length_base"); energy = item.TryGetInt("energy"); if (item.ContainsKey("choose_target")) { choseTarget = (ChoseTarget)(int.Parse(item["choose_target"].ToString())); } if (item.ContainsKey("rangen_type")) { object[] rangens = item["rangen_type"] as object[]; if (rangens != null) { rangenValue.type = rangens.Length > 0 ? (RangenType)(int.Parse(rangens[0].ToString())) : RangenType.OuterCircle; switch (rangenValue.type) { case RangenType.OuterCircle: rangenValue.outerRadius = rangens.Length > 1 ? float.Parse(rangens[1].ToString()) : 0; break; case RangenType.OuterCircle_InnerCube: rangenValue.outerRadius = rangens.Length > 1 ? float.Parse(rangens[1].ToString()) : 0; rangenValue.length = rangens.Length > 2 ? float.Parse(rangens[2].ToString()) : 0; rangenValue.width = rangens.Length > 3 ? float.Parse(rangens[3].ToString()) : 0; break; case RangenType.OuterCircle_InnerSector: rangenValue.outerRadius = rangens.Length > 1 ? float.Parse(rangens[1].ToString()) : 0; rangenValue.angle = rangens.Length > 2 ? float.Parse(rangens[2].ToString()) : 0; break; case RangenType.OuterCircle_InnerCircle: rangenValue.outerRadius = rangens.Length > 1 ? float.Parse(rangens[1].ToString()) : 0; rangenValue.innerRadius = rangens.Length > 2 ? float.Parse(rangens[2].ToString()) : 0; break; case RangenType.InnerCube: rangenValue.length = rangens.Length > 1 ? float.Parse(rangens[1].ToString()) : 0; rangenValue.width = rangens.Length > 2 ? float.Parse(rangens[2].ToString()) : 0; break; default: break; } } } if (item.ContainsKey("interval_time")) { interval_time = FSDataNodeTable <SkillNode> .GetSingleton().ParseToFloatArray(item["interval_time"]); } if (item.ContainsKey("damage_ratio")) { damage_ratio = FSDataNodeTable <SkillNode> .GetSingleton().ParseToFloatArray(item["damage_ratio"]); } if (item.ContainsKey("nullity_type")) { int[] nodelist = item["nullity_type"] as int[]; if (nodelist != null) { nullity_type = new int[nodelist.Length]; for (int m = 0; m < nodelist.Length; m++) { nullity_type[m] = nodelist[m]; } } } if (item.ContainsKey("influence_type")) { int[] influenceList = item["influence_type"] as int[]; if (influenceList != null) { influence_type = influenceList; } } missable = item.TryGetByte("missable"); efficiency_time = item.TryGetFloat("efficiency_time"); effect_time = item.TryGetFloat("effect_time"); cooling = item.TryGetFloat("cooling"); if (item.ContainsKey("base_num1")) { base_num1 = FSDataNodeTable <SkillNode> .GetSingleton().ParseToFloatArray(item["base_num1"]); } if (item.ContainsKey("growth_ratio1")) { growth_ratio1 = FSDataNodeTable <SkillNode> .GetSingleton().ParseToFloatArray(item["growth_ratio1"]); } if (item.ContainsKey("skill_ratio")) { skill_ratio = FSDataNodeTable <SkillNode> .GetSingleton().ParseToFloatArray(item["skill_ratio"]); if (skill_ratio == null) { GameDebug.LogError("skill_ratio null"); } } if (item.ContainsKey("stats")) { stats = item["stats"] as int[]; } if (item.ContainsKey("buffs_target")) { buffs_target = item["buffs_target"] as int[]; } if (item.ContainsKey("special_buffs")) { specialBuffs = (object[])item["special_buffs"]; } if (item.ContainsKey("skill_parts")) { skill_parts = FSDataNodeTable <SkillNode> .GetSingleton().ParseToLongArray(item["skill_parts"]); } if (item.ContainsKey("add_state")) { add_state = item["add_state"] as object[]; } range = item.TryGetFloat("dist"); warn_time = item.TryGetFloat("warn_time"); // nullity_type = byte.Parse(item["nullity_type"].ToString()); animatorTime = item.TryGetFloat("actuation time"); if (item.ContainsKey("life_drain")) { life_drain = item["life_drain"] as object[]; } if (item.ContainsKey("alerted_position")) { alerted_position = item.TryGetInt("alerted_position"); } //-------------------------------------------------------------------------------------- //新加数据 energyvalue = item.TryGetInt("energy_value"); can_move = item.TryGetInt("can_move") == 2; is_turnround = item.TryGetInt("is_turnround") == 1; face_type = (FaceType)item.TryGetInt("face_type"); effect = item.TryGetStringIntArr("effect"); effect_position = item.TryGetIntArr("effect_position"); if (item.ContainsKey("effect_positionxyz") && item["effect_positionxyz"] != null) { object[] effect_positionxyz_temp = item["effect_positionxyz"] as object[]; GetVector3List(effect_positionxyz, effect_positionxyz_temp); } effect_start = item.TryGetDoubleArr("effect_start"); effect_end = item.TryGetDoubleArr("effect_end"); skill_usetype = (SkillUseType)item.TryGetInt("skill_usetype"); bullet_time = item.TryGetDoubleArr("bullet_time"); bullet_id = item.TryGetIntArr("bullet_id"); bul_target_type = item.TryGetIntArr("bul_target_type"); if (item.ContainsKey("bul_target_value") && item["bul_target_value"] != null) { bul_target_value = new List <int[]>(); object[] bul_target_value_temp = item["bul_target_value"] as object[]; for (int i = 0; i < bul_target_value_temp.Length; i++) { int[] objs = bul_target_value_temp[i] as int[]; bul_target_value.Add(objs); } } bul_target_size = item.TryGetIntArr("bul_target_size"); max_bul = item.TryGetIntArr("max_bul"); if (item.ContainsKey("bul_num_single") && item["bul_num_single"] != null) { bul_num_single = new List <int[]>(); object[] bul_num_single_temp = item["bul_num_single"] as object[]; for (int i = 0; i < bul_num_single_temp.Length; i++) { int[] objs = bul_num_single_temp[i] as int[]; bul_num_single.Add(objs); } } bul_start = item.TryGetIntArr("bul_start"); isFiringPoint = item.TryGetInt("firing"); if (item.ContainsKey("firing_xyz") && item["firing_xyz"] != null) { object[] firing_xyz_temp = item["firing_xyz"] as object[]; GetVector3List(firing_xyz, firing_xyz_temp); } bul_end = item.TryGetInt("bul_end"); if (item.ContainsKey("bul_end_xyz") && item["bul_end_xyz"] != null) { object[] bul_end_xyz_temp = item["bul_end_xyz"] as object[]; GetVector3List(bul_end_xyz, bul_end_xyz_temp); } bul_end_angle = item.TryGetIntArr("bul_end_angle"); bul_son_max = item.TryGetIntArr("bul_son_max"); combo_time = item.TryGetIntArr("combo_time"); //-------------------------------------------------------------------------------------- }
static public unsafe void Write <TOutputStream>(ref TOutputStream output, NetworkSchema schema, byte[] inputData, byte[] baselineData, byte[] fieldsChangedPrediction, byte fieldMask, ref uint entity_hash) where TOutputStream : NetworkCompression.IOutputStream { GameDebug.Assert(baselineData != null); var inputStream = new ByteInputStream(inputData); var baselineStream = new ByteInputStream(baselineData); int numFields = schema.fields.Count; GameDebug.Assert(fieldsChangedPrediction.Length >= numFields / 8, "Not enough bits in fieldsChangedPrediction for all fields"); for (int i = 0, l = fieldsNotPredicted.Length; i < l; ++i) { fieldsNotPredicted[i] = 0; } // calculate bitmask of fields that need to be encoded for (int fieldIndex = 0; fieldIndex < schema.fields.Count; ++fieldIndex) { var field = schema.fields[fieldIndex]; // Skip fields that are masked out bool masked = (field.fieldMask & fieldMask) != 0; byte fieldByteOffset = (byte)((uint)fieldIndex >> 3); byte fieldBitOffset = (byte)((uint)fieldIndex & 0x7); switch (field.fieldType) { case NetworkSchema.FieldType.Bool: { uint value = inputStream.ReadBits(1); uint baseline = baselineStream.ReadUInt8(); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value); if (value != baseline) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.Int: { uint value = inputStream.ReadBits(field.bits); uint baseline = (uint)baselineStream.ReadBits(field.bits); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value); if (value != baseline) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.UInt: { uint value = inputStream.ReadBits(field.bits); uint baseline = (uint)baselineStream.ReadBits(field.bits); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value); if (value != baseline) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.Float: { uint value = inputStream.ReadBits(field.bits); uint baseline = (uint)baselineStream.ReadBits(field.bits); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, value); if (value != baseline) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.Vector2: { uint vx = inputStream.ReadBits(field.bits); uint vy = inputStream.ReadBits(field.bits); uint bx = baselineStream.ReadUInt32(); uint by = baselineStream.ReadUInt32(); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vx); entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vy); if (vx != bx || vy != by) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.Vector3: { uint vx = inputStream.ReadBits(field.bits); uint vy = inputStream.ReadBits(field.bits); uint vz = inputStream.ReadBits(field.bits); uint bx = baselineStream.ReadUInt32(); uint by = baselineStream.ReadUInt32(); uint bz = baselineStream.ReadUInt32(); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vx); entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vy); entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vz); if (vx != bx || vy != by || vz != bz) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.Quaternion: { uint vx = inputStream.ReadBits(field.bits); uint vy = inputStream.ReadBits(field.bits); uint vz = inputStream.ReadBits(field.bits); uint vw = inputStream.ReadBits(field.bits); uint bx = baselineStream.ReadUInt32(); uint by = baselineStream.ReadUInt32(); uint bz = baselineStream.ReadUInt32(); uint bw = baselineStream.ReadUInt32(); if (!masked) { entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vx); entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vy); entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vz); entity_hash = NetworkUtils.SimpleHashStreaming(entity_hash, vw); if (vx != bx || vy != by || vz != bz || vw != bw) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } break; } case NetworkSchema.FieldType.String: case NetworkSchema.FieldType.ByteArray: { // TODO : Do a better job of string and buffer diffs? byte[] valueBuffer; int valueOffset; int valueLength; inputStream.GetByteArray(out valueBuffer, out valueOffset, out valueLength, field.arraySize); byte[] baselineBuffer = null; int baselineOffset = 0; int baselineLength = 0; baselineStream.GetByteArray(out baselineBuffer, out baselineOffset, out baselineLength, field.arraySize); if (!masked) { entity_hash += 0; // TODO client side has no easy way to hash strings. enable this when possible: NetworkUtils.SimpleHash(valueBuffer, valueLength); if (valueLength != baselineLength || NetworkUtils.MemCmp(valueBuffer, valueOffset, baselineBuffer, baselineOffset, valueLength) != 0) { fieldsNotPredicted[fieldByteOffset] |= (byte)(1 << fieldBitOffset); } } } break; } } inputStream.Reset(); baselineStream.Reset(); int skipContext = schema.id * NetworkConfig.maxContextsPerSchema + NetworkConfig.firstSchemaContext; // Client needs fieldsNotPredicted. We send the delta between it and fieldsChangedPrediction { for (int i = 0; i * 8 < numFields; i++) { byte deltaFields = (byte)(fieldsNotPredicted[i] ^ fieldsChangedPrediction[i]); output.WritePackedNibble((uint)(deltaFields & 0xF), skipContext + i * 2); output.WritePackedNibble((uint)((deltaFields >> 4) & 0xF), skipContext + i * 2 + 1); } } int startBitPosition = 0; for (int fieldIndex = 0; fieldIndex < numFields; ++fieldIndex) { var field = schema.fields[fieldIndex]; int fieldStartContext = field.startContext; startBitPosition = output.GetBitPosition2(); byte fieldByteOffset = (byte)((uint)fieldIndex >> 3); byte fieldBitOffset = (byte)((uint)fieldIndex & 0x7); var notPredicted = ((fieldsNotPredicted[fieldByteOffset] & (1 << fieldBitOffset)) != 0); switch (field.fieldType) { case NetworkSchema.FieldType.Bool: { uint value = inputStream.ReadBits(1); /*uint unused_baseline = */ baselineStream.ReadUInt8(); if (notPredicted) { output.WriteRawBits(value, 1); NetworkSchema.AddStatsToFieldBool(field, (value != 0), false, output.GetBitPosition2() - startBitPosition); } break; } case NetworkSchema.FieldType.Int: { uint value = inputStream.ReadBits(field.bits); uint baseline = (uint)baselineStream.ReadBits(field.bits); if (notPredicted) { if (field.delta) { output.WritePackedUIntDelta(value, baseline, fieldStartContext); NetworkSchema.AddStatsToFieldInt(field, (int)value, (int)baseline, output.GetBitPosition2() - startBitPosition); } else { output.WriteRawBits(value, field.bits); NetworkSchema.AddStatsToFieldInt(field, (int)value, 0, output.GetBitPosition2() - startBitPosition); } } break; } case NetworkSchema.FieldType.UInt: { uint value = inputStream.ReadBits(field.bits); uint baseline = (uint)baselineStream.ReadBits(field.bits); if (notPredicted) { if (field.delta) { output.WritePackedUIntDelta(value, baseline, fieldStartContext); NetworkSchema.AddStatsToFieldUInt(field, value, baseline, output.GetBitPosition2() - startBitPosition); } else { output.WriteRawBits(value, field.bits); NetworkSchema.AddStatsToFieldUInt(field, value, 0, output.GetBitPosition2() - startBitPosition); } } break; } case NetworkSchema.FieldType.Float: { uint value = inputStream.ReadBits(field.bits); uint baseline = (uint)baselineStream.ReadBits(field.bits); if (notPredicted) { if (field.delta) { output.WritePackedUIntDelta(value, baseline, fieldStartContext); NetworkSchema.AddStatsToFieldFloat(field, value, baseline, output.GetBitPosition2() - startBitPosition); } else { output.WriteRawBits(value, field.bits); NetworkSchema.AddStatsToFieldFloat(field, value, 0, output.GetBitPosition2() - startBitPosition); } } break; } case NetworkSchema.FieldType.Vector2: { uint vx = inputStream.ReadBits(field.bits); uint vy = inputStream.ReadBits(field.bits); uint bx = baselineStream.ReadUInt32(); uint by = baselineStream.ReadUInt32(); if (notPredicted) { if (field.delta) { output.WritePackedUIntDelta(vx, bx, fieldStartContext + 0); output.WritePackedUIntDelta(vy, by, fieldStartContext + 1); NetworkSchema.AddStatsToFieldVector2(field, vx, vy, bx, by, output.GetBitPosition2() - startBitPosition); } else { output.WriteRawBits(vx, field.bits); output.WriteRawBits(vy, field.bits); NetworkSchema.AddStatsToFieldVector2(field, vx, vy, 0, 0, output.GetBitPosition2() - startBitPosition); } } break; } case NetworkSchema.FieldType.Vector3: { uint vx = inputStream.ReadBits(field.bits); uint vy = inputStream.ReadBits(field.bits); uint vz = inputStream.ReadBits(field.bits); uint bx = baselineStream.ReadUInt32(); uint by = baselineStream.ReadUInt32(); uint bz = baselineStream.ReadUInt32(); if (notPredicted) { if (field.delta) { output.WritePackedUIntDelta(vx, bx, fieldStartContext + 0); output.WritePackedUIntDelta(vy, by, fieldStartContext + 1); output.WritePackedUIntDelta(vz, bz, fieldStartContext + 2); NetworkSchema.AddStatsToFieldVector3(field, vx, vy, vz, bx, by, bz, output.GetBitPosition2() - startBitPosition); } else { output.WriteRawBits(vx, field.bits); output.WriteRawBits(vy, field.bits); output.WriteRawBits(vz, field.bits); NetworkSchema.AddStatsToFieldVector3(field, vx, vy, vz, 0, 0, 0, output.GetBitPosition2() - startBitPosition); } } break; } case NetworkSchema.FieldType.Quaternion: { // TODO : Figure out what to do with quaternions uint vx = inputStream.ReadBits(field.bits); uint vy = inputStream.ReadBits(field.bits); uint vz = inputStream.ReadBits(field.bits); uint vw = inputStream.ReadBits(field.bits); uint bx = baselineStream.ReadUInt32(); uint by = baselineStream.ReadUInt32(); uint bz = baselineStream.ReadUInt32(); uint bw = baselineStream.ReadUInt32(); if (notPredicted) { if (field.delta) { output.WritePackedUIntDelta(vx, bx, fieldStartContext + 0); output.WritePackedUIntDelta(vy, by, fieldStartContext + 1); output.WritePackedUIntDelta(vz, bz, fieldStartContext + 2); output.WritePackedUIntDelta(vw, bw, fieldStartContext + 3); NetworkSchema.AddStatsToFieldQuaternion(field, vx, vy, vz, vw, bx, by, bz, bw, output.GetBitPosition2() - startBitPosition); } else { output.WriteRawBits(vx, field.bits); output.WriteRawBits(vy, field.bits); output.WriteRawBits(vz, field.bits); output.WriteRawBits(vw, field.bits); NetworkSchema.AddStatsToFieldQuaternion(field, vx, vy, vz, vw, 0, 0, 0, 0, output.GetBitPosition2() - startBitPosition); } } break; } case NetworkSchema.FieldType.String: case NetworkSchema.FieldType.ByteArray: { // TODO : Do a better job of string and buffer diffs? byte[] valueBuffer; int valueOffset; int valueLength; inputStream.GetByteArray(out valueBuffer, out valueOffset, out valueLength, field.arraySize); byte[] baselineBuffer = null; int baselineOffset = 0; int baselineLength = 0; baselineStream.GetByteArray(out baselineBuffer, out baselineOffset, out baselineLength, field.arraySize); if (notPredicted) { output.WritePackedUInt((uint)valueLength, fieldStartContext); output.WriteRawBytes(valueBuffer, valueOffset, valueLength); if (field.fieldType == NetworkSchema.FieldType.String) { NetworkSchema.AddStatsToFieldString(field, valueBuffer, valueOffset, valueLength, output.GetBitPosition2() - startBitPosition); } else { NetworkSchema.AddStatsToFieldByteArray(field, valueBuffer, valueOffset, valueLength, output.GetBitPosition2() - startBitPosition); } } } break; } } }
SoundEmitter AllocEmitter() { // Look for unused emitter foreach (var e in m_Emitters) { if (!e.playing) { e.seqId = m_SequenceId++; return(e); } } // Hunt down one emitter to kill SoundEmitter emitter = null; float distance = float.MinValue; var listenerPos = m_CurrentListener != null ? m_CurrentListener.transform.position : Vector3.zero; foreach (var e in m_Emitters) { 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 = e; } } if (emitter != null) { emitter.Kill(); emitter.seqId = m_SequenceId++; return(emitter); } GameDebug.Log("Unable to allocate sound emitter!"); return(null); }
public void Update() { if (focus != Application.isFocused) { focus = Application.isFocused; if (soundMute.IntValue == -1) { m_MasterVolume.MoveTo(focus ? 1.0f : 0.0f, 0.5f); } } var masterVolume = m_MasterVolume.GetValue(); if (soundMute.IntValue == 0) { masterVolume = 0.0f; DebugOverlay.Write(Color.red, DebugOverlay.Width - 10, 2, "{0}", "AUDIO MUTED"); } else if (soundMute.IntValue == 1) { masterVolume = 1.0f; DebugOverlay.Write(Color.green, DebugOverlay.Width - 10, 2, "{0}", "AUDIO PLAYING"); } m_AudioMixer.SetFloat("MasterVolume", DecibelFromAmplitude(Mathf.Clamp(soundMasterVol.FloatValue, 0.0f, 1.0f) * masterVolume)); m_AudioMixer.SetFloat("MusicVolume", DecibelFromAmplitude(Mathf.Clamp(soundMusicVol.FloatValue, 0.0f, 1.0f))); m_AudioMixer.SetFloat("SFXVolume", DecibelFromAmplitude(Mathf.Clamp(soundSFXVol.FloatValue, 0.0f, 1.0f))); m_AudioMixer.SetFloat("MenuVolume", DecibelFromAmplitude(Mathf.Clamp(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.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 (soundDebug.IntValue > 0) { DebugOverlay.Write(30, 1, "Mixer: {0} {1}", m_AudioMixer.GetInstanceID(), Game.game.audioMixer.GetInstanceID()); int ii = 4; foreach (var o in GameObject.FindObjectsOfType <AudioMixerGroup>()) { DebugOverlay.Write(30, ii++, "group: {0} {1}", o.name, o.GetInstanceID()); } DebugOverlay.Write(1, 1, "Num audios {0}", count); for (int i = 0, c = m_Emitters.Length; i < c; ++i) { var e = m_Emitters[i]; DebugOverlay.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) { DebugOverlay.Write(DebugOverlay.Width / 2 - 5, DebugOverlay.Height, "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); float x = Mathf.Lerp(e.source.panStereo * 10.0f, Mathf.Clamp(locpos.x, -10, 10), s);; float z = Mathf.Lerp(-10.0f, Mathf.Clamp(locpos.z, -10, 10), s); DebugOverlay.Write(Color.Lerp(Color.green, Color.blue, s), DebugOverlay.Width / 2 + x, DebugOverlay.Height / 2 - z, "{0} ({1:##.#})", e.soundDef.name, locpos.magnitude); } } }
public static List <List <uint> > ParseArrayUintUint(string str) { var uintUintList = new List <List <uint> >(); if (!string.IsNullOrEmpty(str) && str.Length >= 2) { bool brace_start = false; List <uint> brace_content = null; StringBuilder char_content = null; bool start = false; for (int i = 0; i < str.Length; ++i) { char c = str[i]; if (c == '[') { start = true; continue; } else if (c == ']') { break; } else if (c == '{') { if (brace_start) { GameDebug.LogError("ParseArrayStringString error, duplication brace."); break; } else { brace_start = true; brace_content = new List <uint>(); char_content = new StringBuilder(5); uintUintList.Add(brace_content); } } else if (c == '}') { if (brace_start) { brace_start = false; if (brace_content != null) { if (char_content != null) { var content_str = char_content.ToString(); char_content = null; brace_content.Add(ParseUI_s(content_str, 0)); brace_content = null; } else { GameDebug.LogError("ParseArrayStringString error, char_content is null."); break; } } } else { GameDebug.LogError("ParseArrayStringString error, brace_start state is invalid."); break; } } else if (c == ',') { if (brace_content != null) { if (char_content != null) { var content_str = char_content.ToString(); brace_content.Add(ParseUI_s(content_str, 0)); char_content = new StringBuilder(10); } else { GameDebug.LogError("ParseArrayStringString error, char_content is null."); break; } } } else { if (start == false) { GameDebug.LogError("ParseArrayStringString error, has same char before start."); continue; } else if (brace_start) { if (char_content != null) { char_content.Append(c); } else { GameDebug.LogError("ParseArrayStringString error, char_content is null."); break; } } } } } return(uintUintList); }
public void ClearAtId(int id) { GameDebug.Assert(entries[id] != null, "Trying to clear id that already is empty"); entries[id] = null; EditorUtility.SetDirty(this); }
public override void Load() { #if UNITY_EDITOR string resName = DBManager.AssetsResPath + "/" + mStrPath; TextAsset textObj = EditorResourceLoader.LoadAssetAtPath(resName, typeof(TextAsset)) as TextAsset; if (textObj != null) { string strData = CommonTool.BytesToUtf8(textObj.bytes); if (strData != "") { ParseData(strData); } IsLoaded = true; } else { GameDebug.LogError("DB file load failed: " + mStrPath); } #else AssetBundle db_bundle = DBManager.GetInstance().DBBundle; if (db_bundle != null) { string fileName = Path.GetFileNameWithoutExtension(mStrPath); Object resObj = db_bundle.LoadAsset(fileName); TextAsset text = resObj as TextAsset; if (text != null) { string strData = CommonTool.BytesToUtf8(text.bytes); if (strData != "") { ParseData(strData); } IsLoaded = true; Resources.UnloadAsset(text); } else { GameDebug.LogError("DB file load failed: " + mStrPath); } } else { GameDebug.LogError("DB asset is null!!!"); } #endif /*AssetManager manager = Game.GetInstance().MainInterface.GetAssetManager(); * if (manager== null) * { * GameDebug.LogError("No AssetManager!"); * return; * }*/ /*if (xc.Game.GetInstance().IsUsePackage() || Application.platform != RuntimePlatform.WindowsPlayer) * { * string path = mStrPath; * //string ext = Path.GetExtension(mStrPath).ToLower(); * manager.LoadAsset(path, LoadData); * } * else * { * string path = ""; * string nameNoExtend = PathHelp.GetPathWithNoExtend(mStrPath); * * path = "Resources/" + mStrPath; * path = PathHelp.GetFullPaltformPath(path, false); * * System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open); * byte[] content = new byte[stream.Length]; * stream.Read(content, 0, (int)stream.Length); * * IsLoaded = true; * * string strData = AssetManager.BinToUtf8(content); * ParseData(strData); * stream.Close(); * }*/ }
protected override JobHandle OnUpdate(JobHandle inputDeps) { inputDeps.Complete(); var nodeSet = m_AnimationGraphSystem.Set; var commands = new EntityCommandBuffer(Allocator.TempJob); // Handle created entities Entities .WithoutBurst() // Can be removed once NodeSets are Burst-friendly .WithNone <SystemState>() .ForEach((Entity entity, ref AnimSource.Data animSource, ref Settings settings) => { GameDebug.Log(World, AnimSource.ShowLifetime, "Init AnimSourceInAir entity:{0}", entity); var state = SystemState.Default; state.MainMixer = AnimationGraphHelper.CreateNode <MixerNode>(m_AnimationGraphSystem, "MainMixer"); state.InAirClipNode = AnimationGraphHelper.CreateNode <ClipPlayerNode>(m_AnimationGraphSystem, "InAirClipNode"); nodeSet.Connect(state.InAirClipNode, ClipPlayerNode.KernelPorts.Output, state.MainMixer, MixerNode.KernelPorts.Input0); state.LandAnticClipNode = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "LandAnticClipNode"); state.AdditiveRefPose = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "AdditiveRefPose"); state.AimDelta = AnimationGraphHelper.CreateNode <DeltaNode>(m_AnimationGraphSystem, "AimDelta"); nodeSet.Connect(state.LandAnticClipNode, ClipNode.KernelPorts.Output, state.MainMixer, MixerNode.KernelPorts.Input1); state.AimMixer = AnimationGraphHelper.CreateNode <LayerMixerNode>(m_AnimationGraphSystem, "AimMixer"); nodeSet.Connect(state.MainMixer, MixerNode.KernelPorts.Output, state.AimMixer, LayerMixerNode.KernelPorts.Input0); nodeSet.SendMessage(state.AimMixer, LayerMixerNode.SimulationPorts.BlendModeInput0, BlendingMode.Override); nodeSet.SendMessage(state.AimMixer, LayerMixerNode.SimulationPorts.WeightInput0, 1f); state.AimUpDownClipNode = AnimationGraphHelper.CreateNode <ClipNode>(m_AnimationGraphSystem, "AimUpDownClipNode"); nodeSet.Connect(state.AdditiveRefPose, ClipNode.KernelPorts.Output, state.AimDelta, DeltaNode.KernelPorts.Subtract); nodeSet.Connect(state.AimUpDownClipNode, ClipNode.KernelPorts.Output, state.AimDelta, DeltaNode.KernelPorts.Input); nodeSet.Connect(state.AimDelta, DeltaNode.KernelPorts.Output, state.AimMixer, LayerMixerNode.KernelPorts.Input1); nodeSet.SendMessage(state.AimMixer, LayerMixerNode.SimulationPorts.BlendModeInput1, BlendingMode.Additive); nodeSet.SendMessage(state.AimMixer, LayerMixerNode.SimulationPorts.WeightInput1, 1f); // Store clip info state.AimVerticalDuration = settings.animAimDownToUp.Value.Duration; // Expose input and outputs animSource.outputNode = state.AimMixer; animSource.outputPortID = (OutputPortID)LayerMixerNode.KernelPorts.Output; commands.AddComponent(entity, state); }).Run(); // Handled deleted entities var animationGraphSystem = m_AnimationGraphSystem; Entities .WithoutBurst() // Can be removed once NodeSets are Burst-friendly .WithNone <Settings>().ForEach((Entity entity, ref SystemState state) => { Deinitialize(World, commands, entity, animationGraphSystem, state); }).Run(); commands.Playback(EntityManager); commands.Dispose(); return(default);
//-------------------------------------------------------- // 控件消息 //-------------------------------------------------------- /// <summary> /// 点击登录按钮 /// </summary> void OnClickLoginButton() { #if UNITY_ANDROID GameDebug.LogError("hasNotch: " + DBOSManager.getDBOSManager().getBridge().hasNotch().ToString()); GameDebug.LogError("getNotchSize: " + DBOSManager.getDBOSManager().getBridge().getNotchSize().ToString()); GameDebug.LogError("Screen.safeArea: " + Screen.safeArea.ToString()); GameDebug.LogError("StartTimeStamp: " + GlobalConfig.Instance.StartTimeStamp); #endif Game game = xc.Game.GetInstance(); GlobalConfig globalConfig = GlobalConfig.GetInstance(); //快捷登录界面增加超级ticket,可直接登录外网服务器 string superTicketStr = mSuperTicketInput.text; if (!string.IsNullOrEmpty(superTicketStr)) { globalConfig.LoginInfo.Ticket = superTicketStr; } if (!string.IsNullOrEmpty(mHostURLInput.text)) { GlobalConfig.DebugHostURL = mHostURLInput.text; globalConfig.ResetHostURL(); } if (!string.IsNullOrEmpty(mGameMarkInput.text)) { GlobalConfig.DebugGameMark = mGameMarkInput.text; } if (!string.IsNullOrEmpty(mServerTypeInput.text)) { GlobalConfig.DebugServerType = int.Parse(mServerTypeInput.text); } if (mDebugToggle.isOn) { globalConfig.IsDebugMode = true; game.GameMode = (Game.EGameMode)((int)game.GameMode | (int)Game.EGameMode.GM_Debug); // 关卡测试 SceneHelp.Instance.SwitchPreposeScene(GlobalConst.DefaultTestScene, true); game.GetFSM().React((uint)GameEvent.GE_SWITCH_PLAYING_TEST); } else { bool local_server = false; #if UNITY_ANDROID || UNITY_IPHONE local_server = false; #else string server_file = Application.streamingAssetsPath + "/server.txt"; if (File.Exists(server_file)) { string accountStr = mAccountInput.text; if (string.IsNullOrEmpty(accountStr)) { UINotice.Instance.ShowMessage("请先输入账号"); return; } string server_ip = File.ReadAllText(server_file); if (string.IsNullOrEmpty(server_ip) == false) { globalConfig.IsDebugMode = false; globalConfig.LoginInfo.AccName = accountStr; game.Account = accountStr; GlobalSettings.GetInstance().LastAccount = accountStr; GlobalSettings.GetInstance().LastServer = server_ip; xc.ServerInfo server_info = new xc.ServerInfo(); server_info.Url = server_ip; server_info.SId = 1; GlobalConfig.GetInstance().LoginInfo.ServerInfo = server_info; GlobalSettings.GetInstance().Save(); local_server = true; LoginServer(server_ip); } } #endif if (local_server == false) { OnClickServerListButton(); } } }
static void OnPlayModeStateChanged(PlayModeStateChange mode) { GameDebug.Log("PlayMode is changed to: " + mode.ToString()); }
static void StartSource(AudioSource source, SoundDef soundDef) #endif { Profiler.BeginSample(".Set source clip"); source.clip = soundDef.clips[Random.Range(0, soundDef.clips.Count)]; Profiler.EndSample(); Profiler.BeginSample(".Setup source"); // Map from halftone space to linear playback multiplier source.pitch = Mathf.Pow(2.0f, Random.Range(soundDef.pitchMin, soundDef.pitchMax) / 12.0f); source.minDistance = soundDef.distMin; source.maxDistance = soundDef.distMax; source.volume = AmplitudeFromDecibel(soundDef.volume); source.loop = soundDef.loopCount < 1 ? true : false; source.rolloffMode = soundDef.rolloffMode; float delay = Random.Range(soundDef.delayMin, soundDef.delayMax); if (s_MixerGroups != null) { source.outputAudioMixerGroup = s_MixerGroups[(int)soundDef.soundGroup]; } source.spatialBlend = soundDef.spatialBlend; source.panStereo = Random.Range(soundDef.panMin, soundDef.panMax); Profiler.EndSample(); // soundSpatialize can be null as this is run from editor too Profiler.BeginSample(".Setup spatializer"); if (soundSpatialize != null && soundSpatialize.IntValue > 0 && soundDef.spatialBlend > 0.5f) { source.spatialize = true; source.SetSpatializerFloat(0, 8.0f); source.SetSpatializerFloat(1, 0.0f); //source.SetSpatializerFloat(2, soundDef.distMin); //source.SetSpatializerFloat(3, soundDef.distMax); source.SetSpatializerFloat(4, 0.0f); source.SetSpatializerFloat(5, 0.0f); source.spatializePostEffects = false; //source.rolloffMode = source.spatialize ? AudioRolloffMode.Linear : source.rolloffMode; } else { source.spatialize = false; } Profiler.EndSample(); // TODO (petera) can we remove this? -- should never be needed due to re-enabling code in main update loop if (!source.enabled) { GameDebug.Log("Fixing disabled soundsource"); source.enabled = true; } Profiler.BeginSample("AudioSource.Play"); if (delay > 0.0f) { source.PlayDelayed(delay); } else { source.Play(); } Profiler.EndSample(); }
protected override void OnUpdate() { //newGDV.GetCharValue(); // Handle change of game mode if (m_CurrentGameModeName != modeName.Value) { m_CurrentGameModeName = modeName.Value; switch (m_CurrentGameModeName) { case "deathmatch": m_GameMode = new GameModeDeathmatch(); break; case "assault": m_GameMode = new GameModeAssault(); break; default: m_GameMode = new NullGameMode(); break; } m_GameMode.Initialize(m_World, this); GameDebug.Log("New gamemode : '" + m_GameMode.GetType().ToString() + "'"); Restart(); return; } // Handle joining players var playerStates = m_PlayersComponentGroup.GetComponentArray <PlayerState>(); for (int i = 0, c = playerStates.Length; i < c; ++i) { var player = playerStates[i]; if (!player.gameModeSystemInitialized) { player.score = 0; player.displayGameScore = true; player.goalCompletion = -1.0f; m_GameMode.OnPlayerJoin(player); player.gameModeSystemInitialized = true; } } m_GameMode.Update(); // General rules gameModeState.gameTimerSeconds = GetGameTimer(); var playerEntities = m_PlayersComponentGroup.GetEntityArray(); var playerCharacterControls = m_PlayersComponentGroup.GetComponentArray <PlayerCharacterControl>(); for (int i = 0, c = playerStates.Length; i < c; ++i) { var player = playerStates[i]; var controlledEntity = player.controlledEntity; var playerEntity = playerEntities[i]; player.actionString = player.enableCharacterSwitch ? "Press H to change character" : ""; var charControl = playerCharacterControls[i]; // Spawn contolled entity (character) any missing if (controlledEntity == Entity.Null) { var position = new Vector3(0.0f, 0.2f, 0.0f); var rotation = Quaternion.identity; GetRandomSpawnTransform(player.teamIndex, ref position, ref rotation); m_GameMode.OnPlayerRespawn(player, ref position, ref rotation); if (charControl.characterType == -1) { charControl.characterType = Game.characterType.IntValue; if (Game.allowCharChange.IntValue == 1) { charControl.characterType = 3; //charControl.characterType = SelectedCharacter; //Change spawned character here } } if (charControl.characterType == 1000) { SpectatorCamSpawnRequest.Create(PostUpdateCommands, position, rotation, playerEntity); } else { CharacterSpawnRequest.Create(PostUpdateCommands, charControl.characterType, position, rotation, playerEntity); } continue; } // Has new new entity been requested if (charControl.requestedCharacterType != -1) { if (charControl.requestedCharacterType != charControl.characterType) { charControl.characterType = charControl.requestedCharacterType; if (player.controlledEntity != Entity.Null) { // Despawn current controlled entity. New entity will be created later if (EntityManager.HasComponent <Character>(controlledEntity)) { var predictedState = EntityManager.GetComponentData <CharacterPredictedData>(controlledEntity); var rotation = predictedState.velocity.magnitude > 0.01f ? Quaternion.LookRotation(predictedState.velocity.normalized) : Quaternion.identity; CharacterDespawnRequest.Create(PostUpdateCommands, controlledEntity); CharacterSpawnRequest.Create(PostUpdateCommands, charControl.characterType, predictedState.position, rotation, playerEntity); } player.controlledEntity = Entity.Null; } } charControl.requestedCharacterType = -1; continue; } if (EntityManager.HasComponent <HealthStateData>(controlledEntity)) { // Is character dead ? var healthState = EntityManager.GetComponentData <HealthStateData>(controlledEntity); if (healthState.health == 0) { // Send kill msg if (healthState.deathTick == m_World.worldTime.tick) { var killerEntity = healthState.killedBy; var killerIndex = FindPlayerControlling(ref playerStates, killerEntity); PlayerState killerPlayer = null; if (killerIndex != -1) { killerPlayer = playerStates[killerIndex]; var format = s_KillMessages[Random.Range(0, s_KillMessages.Length)]; var l = StringFormatter.Write(ref _msgBuf, 0, format, killerPlayer.playerName, player.playerName, m_TeamColors[killerPlayer.teamIndex], m_TeamColors[player.teamIndex]); chatSystem.SendChatAnnouncement(new CharBufView(_msgBuf, l)); } else { var format = s_SuicideMessages[Random.Range(0, s_SuicideMessages.Length)]; var l = StringFormatter.Write(ref _msgBuf, 0, format, player.playerName, m_TeamColors[player.teamIndex]); chatSystem.SendChatAnnouncement(new CharBufView(_msgBuf, l)); } m_GameMode.OnPlayerKilled(player, killerPlayer); } // Respawn dead players except if in ended mode if (m_EnableRespawning && (m_World.worldTime.tick - healthState.deathTick) * m_World.worldTime.tickInterval > respawnDelay.IntValue) { // Despawn current controlled entity. New entity will be created later if (EntityManager.HasComponent <Character>(controlledEntity)) { CharacterDespawnRequest.Create(PostUpdateCommands, controlledEntity); } player.controlledEntity = Entity.Null; } } } } }
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} skeletonHash: {2}", j, partId, skeletonHash); } else { GameDebug.Log(World, Part.ShowLifetime, "Find valid part. Category:{0} PartId:{1} skeletonHash: {2}", j, partId, skeletonHash); } } // 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); } }); }
protected override void Update(Entity abilityEntity, CharBehaviour charAbility, AbilityControl abilityCtrl, Ability_Movement.Settings settings) { if (abilityCtrl.active == 0) { if (abilityCtrl.behaviorState != AbilityControl.State.Idle) { abilityCtrl.behaviorState = AbilityControl.State.Idle; EntityManager.SetComponentData(abilityEntity, abilityCtrl); } return; } // Movement is always active (unless canceled) if (abilityCtrl.behaviorState != AbilityControl.State.Active) { abilityCtrl.behaviorState = AbilityControl.State.Active; EntityManager.SetComponentData(abilityEntity, abilityCtrl); } var time = m_world.WorldTime; var command = EntityManager.GetComponentData <UserCommandComponentData>(charAbility.character).command; var predictedState = EntityManager.GetComponentData <CharacterPredictedData>(charAbility.character); var character = EntityManager.GetComponentObject <Character>(charAbility.character); var newPhase = CharacterPredictedData.LocoState.MaxValue; var phaseDuration = time.DurationSinceTick(predictedState.locoStartTick); var isOnGround = predictedState.IsOnGround(); var isMoveWanted = command.moveMagnitude != 0.0f; // Ground movement if (isOnGround) { if (isMoveWanted) { newPhase = CharacterPredictedData.LocoState.GroundMove; } else { newPhase = CharacterPredictedData.LocoState.Stand; } } if (command.buttons.IsSet(UserCommand.Button.Jump) && predictedState.releasedJump == 1 && isOnGround) { newPhase = CharacterPredictedData.LocoState.Jump; } if (predictedState.locoState == CharacterPredictedData.LocoState.Jump) { if (phaseDuration >= Game.config.jumpAscentDuration && predictedState.boosting == 0) { newPhase = CharacterPredictedData.LocoState.InAir; } } if (predictedState.boostingInAirCount >= 1 && predictedState.boosting == 0) //in air boosting ended { if (!isOnGround) { newPhase = CharacterPredictedData.LocoState.InAir; } } predictedState.releasedJump = !command.buttons.IsSet(UserCommand.Button.Jump) ? 1 : 0; // Set phase start tick if phase has changed if (newPhase != CharacterPredictedData.LocoState.MaxValue && newPhase != predictedState.locoState) { predictedState.locoState = newPhase; predictedState.locoStartTick = time.tick; } if (time.tick != predictedState.tick + 1) { GameDebug.Log("Update tick invalid. Game tick:" + time.tick + " but current state is at tick:" + predictedState.tick); } predictedState.tick = time.tick; // Apply damange impulse from previus frame if (time.tick == predictedState.damageTick + 1) { predictedState.velocity += predictedState.damageDirection * predictedState.damageImpulse; predictedState.locoState = CharacterPredictedData.LocoState.InAir; predictedState.locoStartTick = time.tick; } var moveQuery = EntityManager.GetComponentObject <CharacterMoveQuery>(charAbility.character); // Simple adjust of height while on platform if (predictedState.locoState == CharacterPredictedData.LocoState.Stand && character.groundCollider != null && character.groundCollider.gameObject.layer == m_platformLayer) { if (character.altitude < moveQuery.settings.skinWidth - 0.01f) { var platform = character.groundCollider; var posY = platform.transform.position.y + moveQuery.settings.skinWidth; predictedState.position.y = posY; } } // Calculate movement and move character var deltaPos = Vector3.zero; CalculateMovement(ref time, ref predictedState, ref command, ref deltaPos); // Setup movement query moveQuery.collisionLayer = character.teamId == 0 ? m_charCollisionALayer : m_charCollisionBLayer; moveQuery.moveQueryStart = predictedState.position; moveQuery.moveQueryEnd = moveQuery.moveQueryStart + (float3)deltaPos; EntityManager.SetComponentData(charAbility.character, predictedState); }
/// <summary> /// 通过内存池来创建物品图标 /// </summary> /// <param name="template"></param> /// <param name="wnd_name"></param> /// <param name="goodsID"></param> /// <param name="num"></param> /// <param name="isShowTips"></param> /// <param name="isScale"></param> /// <param name="isBind"></param> /// <returns></returns> public GameObject CreateGoodsItemCache(GameObject template, string wnd_name, Transform parent, uint goodsID, ulong num, bool isShowTips = true, bool isScale = false, uint isBind = uint.MaxValue) { if (template == null) { return(null); } var wnd = UIManager.instance.GetWindow(wnd_name); if (wnd == null) { return(null); } var gameObject = wnd.GetItemGameObj(parent); UIItemRef itemRef = template.GetComponent <UIItemRef>(); UIItemNewSlot newSlot = template.GetComponent <UIItemNewSlot>(); gameObject.transform.SetParent(template.transform.parent, false); gameObject.SetActive(true); UIItemNewSlot itemSlot; if (itemRef) { itemSlot = UIItemNewSlot.Bind(gameObject, itemRef.TargetPanel, itemRef.ClipPanel); } else if (newSlot) { itemSlot = UIItemNewSlot.Bind(gameObject, newSlot.TargetPanel, newSlot.ClipPanel); } else { itemSlot = UIItemNewSlot.Bind(gameObject); } Goods itemInfo = GoodsHelper.CreateGoodsByTypeId(goodsID); if (isShowTips == false && isScale == false) { var collider = gameObject.GetComponent <Collider>(); if (collider != null) { collider.enabled = false; } } if (itemInfo == null) { GameDebug.LogError("CreateGoodsItem error, can not find goods " + goodsID); return(gameObject); } itemInfo.num = num; if (isBind != uint.MaxValue) { itemInfo.bind = isBind; } UIItemNewSlot.TypeParse typeParse = UIItemNewSlot.CreateUIItemTypeParse(); if (isShowTips == true) { typeParse._mType = 2; } else { typeParse._mType = 0; } itemSlot.setItemInfo(itemInfo, typeParse, isScale); return(gameObject); }
unsafe public static int Read <TInputStream>(ref TInputStream input, NetworkSchema schema, uint[] outputData, uint[] baselineData, byte[] fieldsChangedPrediction, byte fieldMask, ref uint hash) where TInputStream : NetworkCompression.IInputStream { GameDebug.Assert(baselineData != null); var index = 0; int numFields = schema.numFields; int skipContext = schema.id * NetworkConfig.maxContextsPerSchema + NetworkConfig.firstSchemaContext; for (int i = 0; i * 8 < numFields; i++) { uint value = input.ReadPackedNibble(skipContext + 2 * i + 0); value |= input.ReadPackedNibble(skipContext + 2 * i + 1) << 4; fieldsNotPredicted[i] = (byte)(value ^ fieldsChangedPrediction[i]); } for (int i = 0; i < numFields; ++i) { var field = schema.fields[i]; GameDebug.Assert(field.byteOffset == index * 4); int fieldStartContext = field.startContext; byte fieldByteOffset = (byte)((uint)i >> 3); byte fieldBitOffset = (byte)((uint)i & 0x7); bool skip = (fieldsNotPredicted[fieldByteOffset] & (1 << fieldBitOffset)) == 0; bool masked = ((field.fieldMask & fieldMask) != 0); skip = skip || masked; switch (field.fieldType) { case NetworkSchema.FieldType.Bool: { uint value = baselineData[index]; if (!skip) { value = input.ReadRawBits(1); } if (!masked) { hash = NetworkUtils.SimpleHashStreaming(hash, value); } outputData[index] = value; index++; break; } case NetworkSchema.FieldType.UInt: case NetworkSchema.FieldType.Int: case NetworkSchema.FieldType.Float: { uint baseline = (uint)baselineData[index]; uint value = baseline; if (!skip) { if (field.delta) { value = input.ReadPackedUIntDelta(baseline, fieldStartContext); } else { value = input.ReadRawBits(field.bits); } } if (!masked) { hash = NetworkUtils.SimpleHashStreaming(hash, value); } outputData[index] = value; index++; break; } case NetworkSchema.FieldType.Vector2: { uint bx = baselineData[index]; uint by = baselineData[index + 1]; uint vx = bx; uint vy = by; if (!skip) { if (field.delta) { vx = input.ReadPackedUIntDelta(bx, fieldStartContext + 0); vy = input.ReadPackedUIntDelta(by, fieldStartContext + 1); } else { vx = input.ReadRawBits(field.bits); vy = input.ReadRawBits(field.bits); } } if (!masked) { hash = NetworkUtils.SimpleHashStreaming(hash, vx); hash = NetworkUtils.SimpleHashStreaming(hash, vy); } outputData[index] = vx; outputData[index + 1] = vy; index += 2; break; } case NetworkSchema.FieldType.Vector3: { uint bx = baselineData[index]; uint by = baselineData[index + 1]; uint bz = baselineData[index + 2]; uint vx = bx; uint vy = by; uint vz = bz; if (!skip) { if (field.delta) { vx = input.ReadPackedUIntDelta(bx, fieldStartContext + 0); vy = input.ReadPackedUIntDelta(by, fieldStartContext + 1); vz = input.ReadPackedUIntDelta(bz, fieldStartContext + 2); } else { vx = input.ReadRawBits(field.bits); vy = input.ReadRawBits(field.bits); vz = input.ReadRawBits(field.bits); } } if (!masked) { hash = NetworkUtils.SimpleHashStreaming(hash, vx); hash = NetworkUtils.SimpleHashStreaming(hash, vy); hash = NetworkUtils.SimpleHashStreaming(hash, vz); } outputData[index] = vx; outputData[index + 1] = vy; outputData[index + 2] = vz; index += 3; break; } case NetworkSchema.FieldType.Quaternion: { uint bx = baselineData[index]; uint by = baselineData[index + 1]; uint bz = baselineData[index + 2]; uint bw = baselineData[index + 3]; uint vx = bx; uint vy = by; uint vz = bz; uint vw = bw; if (!skip) { if (field.delta) { vx = input.ReadPackedUIntDelta(bx, fieldStartContext + 0); vy = input.ReadPackedUIntDelta(by, fieldStartContext + 1); vz = input.ReadPackedUIntDelta(bz, fieldStartContext + 2); vw = input.ReadPackedUIntDelta(bw, fieldStartContext + 3); //RUTODO: normalize } else { vx = input.ReadRawBits(field.bits); vy = input.ReadRawBits(field.bits); vz = input.ReadRawBits(field.bits); vw = input.ReadRawBits(field.bits); } } if (!masked) { hash = NetworkUtils.SimpleHashStreaming(hash, vx); hash = NetworkUtils.SimpleHashStreaming(hash, vy); hash = NetworkUtils.SimpleHashStreaming(hash, vz); hash = NetworkUtils.SimpleHashStreaming(hash, vw); } outputData[index] = vx; outputData[index + 1] = vy; outputData[index + 2] = vz; outputData[index + 3] = vw; index += 4; break; } case NetworkSchema.FieldType.String: case NetworkSchema.FieldType.ByteArray: { // TODO : Do a better job with deltaing strings and buffers if (!skip) { uint count = input.ReadPackedUInt(fieldStartContext); outputData[index] = count; index++; fixed(uint *buf = outputData) { byte *dst = (byte *)(buf + index); int idx = 0; for (; idx < count; ++idx) { *dst++ = (byte)input.ReadRawBits(8); } for (; idx < field.arraySize / 4; ++idx) { *dst++ = 0; } } index += field.arraySize / 4; } else { for (int idx = 0, c = field.arraySize / 4; idx < c; ++idx) { outputData[index + idx] = baselineData[index + idx]; } index += field.arraySize / 4 + 1; } if (!masked) { hash += 0; // TODO (hash strings and bytearrays as well) } } break; } } return(index * 4); }
public bool FromJson(string json) { GameDebug.LogGreen("解析JSON:" + json); Hashtable jsonObj = MiniJSON.JsonDecode(json) as Hashtable; if (jsonObj == null || jsonObj["result"] == null) { result = -1; GameDebug.LogError("游戏公告解析失败" + json); return(false); } result = int.Parse(jsonObj["result"].ToString()); if (result != 1) { result = -1; GameDebug.LogError("游戏公告解析失败" + json); return(false); } Hashtable args = jsonObj["args"] as Hashtable; if (args == null) { result = -1; GameDebug.LogError("游戏公告参数解析失败" + json); return(false); } ArrayList notice_list = args["notice_list"] as ArrayList; if (notice_list == null) { GameDebug.LogError("游戏公告解析失败 notice_list " + json); return(false); } this.allNotice.Clear(); for (int i = 0; i < notice_list.Count; i++) { var tbl = notice_list[i] as Hashtable; int type = 0; if (tbl["tag"] != null) { type = int.Parse(tbl["tag"].ToString()); } if (type == 0) { type = 1;//活动 } else if (type == 1) { type = 2;//公告 } else { type = 0; } int openType = 0; if (tbl["type"] != null) { openType = int.Parse(tbl["type"].ToString()); } int status = 1; if (tbl["status"] != null) { status = int.Parse(tbl["status"].ToString()); } int noticeOrder = 0; if (tbl["notice_order"] != null) { noticeOrder = int.Parse(tbl["notice_order"].ToString()); } bool isNew = false; if (tbl["icon_status"] != null && tbl["icon_status"].ToString() != "null" && (int.Parse(tbl["icon_status"].ToString()) == 1)) { isNew = true; } string title = tbl["title"] == null ? "" : tbl["title"].ToString(); string content = tbl["content"] == null ? "" : tbl["content"].ToString(); List <string> titles = new List <string>(); List <string> contents = new List <string>(); titles.Add(title); contents.Add(content); if (tbl["sub_content"] != null && tbl["sub_content"] is ArrayList) { var subList = tbl["sub_content"] as ArrayList; for (int j = 0; j < subList.Count; j++) { var c = subList[j] as Hashtable; titles.Add(c["title"].ToString()); contents.Add(c["content"].ToString()); } } var item = GetItemInfo(type, isNew, titles, contents, openType, status, noticeOrder); //无效的不管 if (item.status != 1) { allNotice.Add(item); } } allNotice.Sort(CompareFunc); this.type = 0; foreach (var notice in allNotice) { if (notice.openType == 1) { this.type = 1; } else { this.type = 0; } } return(true); }
protected override void ParseData(SqliteDataReader reader) { if (reader == null || !reader.HasRows) { return; } SysConfig config = null; while (reader.Read()) { var id = DBTextResource.ParseUI(GetReaderString(reader, "sys_id")); config = new SysConfig(id); var sys_title = GetReaderString(reader, "sys_title"); var level = DBTextResource.ParseUS_s(GetReaderString(reader, "lv_open"), 0); string taskTypeStr = GetReaderString(reader, "task_limit"); if (string.IsNullOrEmpty(taskTypeStr)) { taskTypeStr = "0"; } var task_type = (ESysTaskType)Enum.Parse(typeof(ESysTaskType), taskTypeStr); var task_id = DBTextResource.ParseUI_s(GetReaderString(reader, "task_args"), 0); string positionStr = GetReaderString(reader, "position"); if (string.IsNullOrEmpty(positionStr)) { positionStr = "0"; } var pos = (ESysBtnPos)Enum.Parse(typeof(ESysBtnPos), positionStr); uint sub_pos = DBTextResource.ParseUI_s(GetReaderString(reader, "sub_pos"), 0); string fixedPosStr = GetReaderString(reader, "fixed_pos"); if (string.IsNullOrEmpty(fixedPosStr)) { fixedPosStr = "0"; } var is_fixed = (ESysBtnFixType)DBTextResource.ParseUI_s(fixedPosStr, 1); bool show_bg = DBTextResource.ParseUI_s(GetReaderString(reader, "show_bg"), 0) == 1; uint is_activity = DBTextResource.ParseUI_s(GetReaderString(reader, "is_activity"), 0); var desc = GetReaderString(reader, "desc"); var btn_sprite = GetReaderString(reader, "btn_spr"); var btn_text = GetReaderString(reader, "btn_text"); var sort_order = DBTextResource.ParseBT_s(GetReaderString(reader, "sort_order"), 0); var transfer_limit = DBTextResource.ParseUI_s(GetReaderString(reader, "transfer_limit"), 0); var not_open_tips = GetReaderString(reader, "not_open_tips"); var main_ui_btn_id = DBTextResource.ParseUI_s(GetReaderString(reader, "main_ui_btn_id"), 0); config.Init(level, task_type, task_id, pos, sub_pos, is_fixed, show_bg, is_activity == 1, desc, btn_sprite, btn_text, sort_order, transfer_limit, not_open_tips, sys_title, main_ui_btn_id); config.NeedAnim = DBTextResource.ParseUI_s(GetReaderString(reader, "is_need_anim"), 0) == 0 ? false : true; if (pos == ESysBtnPos.NONE) // 当在主ui上没有按钮图标的时候,也一定不需要播放开启的动画 { if (config.NeedAnim) { config.NeedAnim = false; GameDebug.LogError(string.Format("sys:{0} 在主ui上没有图标, 却配置了开启动画", id)); } } config.InitNeedShow = DBTextResource.ParseUI_s(GetReaderString(reader, "is_need_show"), 0) == 0 ? false : true; config.PatchId = DBTextResource.ParseI_s(GetReaderString(reader, "patch_id"), 0); config.HideBtnWhenActNotOpen = DBTextResource.ParseUI_s(GetReaderString(reader, "hide_btn_when_act_not_open"), 0) == 0 ? false : true; config.SysIdClosePresent = DBTextResource.ParseUI_s(GetReaderString(reader, "sys_id_close_present"), 0); // 如果有系统开放关联配置,需要将数据存在另外的字典中 if (config.SysIdClosePresent != 0) { List <uint> notifySysIdList = null; if (!mConfigRelation.TryGetValue(config.SysIdClosePresent, out notifySysIdList)) { notifySysIdList = new List <uint>(); mConfigRelation[config.SysIdClosePresent] = notifySysIdList; } if (!notifySysIdList.Contains(config.Id)) { notifySysIdList.Add(config.Id); } } config.TabOrder = DBTextResource.ParseUI_s(GetReaderString(reader, "tab_order"), 0); config.DropDown = DBTextResource.ParseArrayUint(GetReaderString(reader, "drop_down"), ","); config.DropDownType = DBTextResource.ParseUI(GetReaderString(reader, "drop_down_type")); config.UIBehavior = DBTextResource.ParseArrayString(GetReaderString(reader, "ui_behavior")); config.TimeLimitStr = GetReaderString(reader, "time_limit"); config.CustomCondition = DBTextResource.ParseUI_s(GetReaderString(reader, "custom_condition"), 0) == 0 ? false : true; mConfigList.Add(config); mConfigMap[config.Id] = config; } mConfigList.Sort(); }
protected override void OnUpdate() { // var entityArray = Group.GetEntityArray(); var eventArray = Group.GetComponentArray <CharacterEvents>(); var charPresentArray = Group.GetComponentArray <CharPresentation>(); for (var i = 0; i < eventArray.Length; i++) { var charEvents = eventArray[i]; var charPresentation = charPresentArray[i]; var presentationState = EntityManager.GetComponentData <PresentationState>(charPresentation.character); charEvents.GenerateStateChangeEvents(ref presentationState); //Fire sounds based on active events if (!charEvents.active) { continue; } // TODO clear events first frame active, so we dont fire all events accumulated while inactive GameDebug.Assert(charEvents.footstepLeft && charEvents.footstepRight, "Footstep on {0} not set up", charEvents); if (charEvents.onFootDown) { if (Time.time > charEvents.lastFootstepTime + charEvents.minFootstepInterval) { var sound = charEvents.nextFootLeft ? charEvents.footstepLeft : charEvents.footstepRight; Game.SoundSystem.Play(sound, charEvents.transform); charEvents.nextFootLeft = !charEvents.nextFootLeft; charEvents.lastFootstepTime = Time.time; } charEvents.onFootDown = false; } if (charEvents.onLand) { if (charEvents.land != null) { Game.SoundSystem.Play(charEvents.land, charEvents.transform); charEvents.onLand = false; charEvents.onLand = false; } } if (charEvents.onDoubleJump) { if (charEvents.doubleJump != null) { Game.SoundSystem.Play(charEvents.doubleJump, charEvents.transform); charEvents.onDoubleJump = false; } } if (charEvents.onJumpStart) { if (charEvents.jumpStart != null) { Game.SoundSystem.Play(charEvents.jumpStart, charEvents.transform); charEvents.onJumpStart = false; } } } }
void HandleTime(float frameDuration) { // Update tick rate (this will only change runtime in test scenarios) // TODO (petera) consider use ConfigVars with Server flag for this if (m_NetworkClient.serverTickRate != m_PredictedTime.tickRate) { m_PredictedTime.tickRate = m_NetworkClient.serverTickRate; m_RenderTime.tickRate = m_NetworkClient.serverTickRate; } // Sample input into current command // The time passed in here is used to calculate the amount of rotation from stick position // The command stores final view direction bool chatOpen = Game.game.clientFrontend != null && Game.game.clientFrontend.chatPanel.isOpen; bool userInputEnabled = Game.GetMousePointerLock() && !chatOpen; m_PlayerModule.SampleInput(userInputEnabled, Time.deltaTime, m_RenderTime.tick); int prevTick = m_PredictedTime.tick; // Increment time var deltaPredictedTime = frameDuration * frameTimeScale; m_PredictedTime.AddDuration(deltaPredictedTime); // Adjust time to be synchronized with server int preferredBufferedCommandCount = 2; int preferredTick = m_NetworkClient.serverTime + (int)(((m_NetworkClient.timeSinceSnapshot + m_NetworkStatistics.rtt.average) / 1000.0f) * m_GameWorld.worldTime.tickRate) + preferredBufferedCommandCount; bool resetTime = false; if (!resetTime && m_PredictedTime.tick < preferredTick - 3) { GameDebug.Log(string.Format("Client hard catchup ... ")); resetTime = true; } if (!resetTime && m_PredictedTime.tick > preferredTick + 6) { GameDebug.Log(string.Format("Client hard slowdown ... ")); resetTime = true; } frameTimeScale = 1.0f; if (resetTime) { GameDebug.Log(string.Format("CATCHUP ({0} -> {1})", m_PredictedTime.tick, preferredTick)); m_NetworkStatistics.notifyHardCatchup = true; m_GameWorld.nextTickTime = Game.frameTime; m_PredictedTime.tick = preferredTick; m_PredictedTime.SetTime(preferredTick, 0); } else { int bufferedCommands = m_NetworkClient.lastAcknowlegdedCommandTime - m_NetworkClient.serverTime; if (bufferedCommands < preferredBufferedCommandCount) { frameTimeScale = 1.01f; } if (bufferedCommands > preferredBufferedCommandCount) { frameTimeScale = 0.99f; } } // Increment interpolation time m_RenderTime.AddDuration(frameDuration * frameTimeScale); // Force interp time to not exeede server time if (m_RenderTime.tick >= m_NetworkClient.serverTime) { m_RenderTime.SetTime(m_NetworkClient.serverTime, 0); } // hard catchup if (m_RenderTime.tick < m_NetworkClient.serverTime - 10) { m_RenderTime.SetTime(m_NetworkClient.serverTime - 8, 0); } // Throttle up to catch up if (m_RenderTime.tick < m_NetworkClient.serverTime - 1) { m_RenderTime.AddDuration(frameDuration * 0.01f); } // If predicted time has entered a new tick the stored commands should be sent to server if (m_PredictedTime.tick > prevTick) { var oldestCommandToSend = Mathf.Max(prevTick, m_PredictedTime.tick - NetworkConfig.commandClientBufferSize); for (int tick = oldestCommandToSend; tick < m_PredictedTime.tick; tick++) { m_PlayerModule.StoreCommand(tick); m_PlayerModule.SendCommand(tick); } m_PlayerModule.ResetInput(userInputEnabled); m_PlayerModule.StoreCommand(m_PredictedTime.tick); } // Store command m_PlayerModule.StoreCommand(m_PredictedTime.tick); }
static void OnSceneOpen(Scene scene, OpenSceneMode mode) { GameDebug.Log("OPENED Scene: " + scene.name + "\nPath: " + scene.path); }
void EnterBrowsingState() { GameDebug.Assert(m_clientWorld == null); m_ClientState = ClientState.Browsing; }
static void OnSceneClose(Scene scene) { GameDebug.Log("CLOSED Scene: " + scene.name + "\nPath: " + scene.path); }
public Instance(EntityManager entityManager, Entity owner, PlayableGraph graph, Entity animStateOwner, AnimGraph_StateSelector settings) { m_settings = settings; m_graph = graph; m_EntityManager = entityManager; m_Owner = owner; m_AnimStateOwner = animStateOwner; 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, animStateOwner); 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()); }
public void Awake() { GameDebug.Assert(game == null); DontDestroyOnLoad(gameObject); game = this; m_StopwatchFrequency = System.Diagnostics.Stopwatch.Frequency; m_Clock = new System.Diagnostics.Stopwatch(); m_Clock.Start(); var buildInfo = FindObjectOfType <BuildInfo>(); if (buildInfo != null) { _buildId = buildInfo.buildId; } var commandLineArgs = new List <string>(System.Environment.GetCommandLineArgs()); #if UNITY_STANDALONE_LINUX m_isHeadless = true; #else m_isHeadless = commandLineArgs.Contains("-batchmode"); #endif var consoleRestoreFocus = commandLineArgs.Contains("-consolerestorefocus"); if (m_isHeadless) { #if UNITY_STANDALONE_WIN string consoleTitle; var overrideTitle = ArgumentForOption(commandLineArgs, "-title"); if (overrideTitle != null) { consoleTitle = overrideTitle; } else { consoleTitle = Application.productName + " Console"; } consoleTitle += " [" + System.Diagnostics.Process.GetCurrentProcess().Id + "]"; var consoleUI = new ConsoleTextWin(consoleTitle, consoleRestoreFocus); #elif UNITY_STANDALONE_LINUX var consoleUI = new ConsoleTextLinux(); #else UnityEngine.Debug.Log("WARNING: starting without a console"); var consoleUI = new ConsoleNullUI(); #endif Console.Init(consoleUI); } else { var consoleUI = Instantiate(Resources.Load <ConsoleGUI>("Prefabs/ConsoleGUI")); DontDestroyOnLoad(consoleUI); Console.Init(consoleUI); m_DebugOverlay = Instantiate(Resources.Load <DebugOverlay>("DebugOverlay")); DontDestroyOnLoad(m_DebugOverlay); m_DebugOverlay.Init(); var hdpipe = RenderPipelineManager.currentPipeline as HDRenderPipeline; if (hdpipe != null) { hdpipe.DebugLayer2DCallback = DebugOverlay.Render; hdpipe.DebugLayer3DCallback = DebugOverlay.Render3D; } m_GameStatistics = new GameStatistics(); } // If -logfile was passed, we try to put our own logs next to the engine's logfile var engineLogFileLocation = "."; var logfileArgIdx = commandLineArgs.IndexOf("-logfile"); if (logfileArgIdx >= 0 && commandLineArgs.Count >= logfileArgIdx) { engineLogFileLocation = System.IO.Path.GetDirectoryName(commandLineArgs[logfileArgIdx + 1]); } var logName = m_isHeadless ? "game_" + DateTime.UtcNow.ToString("yyyyMMdd_HHmmss_fff") : "game"; GameDebug.Init(engineLogFileLocation, logName); ConfigVar.Init(); Console.EnqueueCommandNoHistory("exec -s " + k_UserConfigFilename); // Default is to allow no frame cap, i.e. as fast as possible if vsync is disabled Application.targetFrameRate = -1; if (m_isHeadless) { Application.targetFrameRate = serverTickRate.IntValue; QualitySettings.vSyncCount = 0; // Needed to make targetFramerate work; even in headless mode #if !UNITY_STANDALONE_LINUX if (!commandLineArgs.Contains("-nographics")) { GameDebug.Log("WARNING: running -batchmod without -nographics"); } #endif } else { RenderSettings.Init(); } // Out of the box game behaviour is driven by boot.cfg unless you ask it not to if (!commandLineArgs.Contains("-noboot")) { Console.EnqueueCommandNoHistory("exec -s " + k_BootConfigFilename); } var forceClientSystem = commandLineArgs.Contains("-forceclientsystems"); if (!m_isHeadless || forceClientSystem) { m_SoundSystem = new SoundSystem(); m_SoundSystem.Init(audioMixer); m_SoundSystem.MountBank(defaultBank); GameObject go = (GameObject)GameObject.Instantiate(Resources.Load("Prefabs/ClientFrontend", typeof(GameObject))); UnityEngine.Object.DontDestroyOnLoad(go); clientFrontend = go.GetComponentInChildren <ClientFrontend>(); } sqpClient = new SQP.SQPClient(); GameDebug.Log("FPS Sample initialized"); #if UNITY_EDITOR GameDebug.Log("Build type: editor"); #elif DEVELOPMENT_BUILD GameDebug.Log("Build type: development"); #else GameDebug.Log("Build type: release"); #endif GameDebug.Log("BuildID: " + buildId); GameDebug.Log("Cwd: " + System.IO.Directory.GetCurrentDirectory()); SimpleBundleManager.Init(); GameDebug.Log("SimpleBundleManager initialized"); levelManager = new LevelManager(); levelManager.Init(); GameDebug.Log("LevelManager initialized"); inputSystem = new InputSystem(); GameDebug.Log("InputSystem initialized"); // TODO (petera) added Instantiate here to avoid making changes to asset file. // Feels like maybe SO is not really the right tool here. config = Instantiate((GameConfiguration)Resources.Load("GameConfiguration")); GameDebug.Log("Loaded game config"); // Game loops Console.AddCommand("preview", CmdPreview, "Start preview mode"); Console.AddCommand("serve", CmdServe, "Start server listening"); Console.AddCommand("client", CmdClient, "client: Enter client mode. Looking for servers"); Console.AddCommand("boot", CmdBoot, "Go back to boot loop"); Console.AddCommand("connect", CmdConnect, "connect <ip>: Connect to server on ip (default: localhost)"); Console.AddCommand("menu", CmdMenu, "show the main menu"); Console.AddCommand("load", CmdLoad, "Load level"); Console.AddCommand("quit", CmdQuit, "Quits"); Console.AddCommand("screenshot", CmdScreenshot, "Capture screenshot. Optional argument is destination folder or filename."); Console.AddCommand("crashme", (string[] args) => { GameDebug.Assert(false); }, "Crashes the game next frame "); Console.AddCommand("saveconfig", CmdSaveConfig, "Save the user config variables"); Console.AddCommand("loadconfig", CmdLoadConfig, "Load the user config variables"); #if UNITY_STANDALONE_WIN Console.AddCommand("windowpos", CmdWindowPosition, "Position of window. e.g. windowpos 100,100"); #endif Console.SetOpen(true); Console.ProcessCommandLineArguments(commandLineArgs.ToArray()); PushCamera(bootCamera); }