public Entity CreateClientProjectile(Entity projectileEntity)
    {
        var projectileData = m_entityManager.GetComponentData <ProjectileData>(projectileEntity);

        // Create client projectile
        var pool             = pools[projectileData.projectileTypeRegistryIndex];
        var instanceIndex    = Reserve(pool);
        var gameObjectEntity = pool.instances[instanceIndex];

        gameObjectEntity.gameObject.SetActive(true);

        var clientProjectileEntity = gameObjectEntity.Entity;
        var clientProjectile       = m_entityManager.GetComponentObject <ClientProjectile>(clientProjectileEntity);

        GameDebug.Assert(clientProjectile.projectile == Entity.Null, "Entity not null");
        clientProjectile.projectile = projectileEntity;
        clientProjectile.SetVisible(false);

        if (ProjectileModuleClient.logInfo.IntValue > 0)
        {
            GameDebug.Log(string.Format("Creating clientprojectile {0} for projectile {1}]", clientProjectile, projectileEntity));
        }

        // Add clientProjectileOwner to projectile
        var clientProjectileOwner = new ClientProjectileOwner
        {
            clientProjectile = clientProjectileEntity
        };

        m_entityManager.AddComponentData(projectileEntity, clientProjectileOwner);

        return(clientProjectileEntity);
    }
示例#2
0
 void OnConnect(int connectionId)
 {
     if (m_Connection != null && m_Connection.connectionId == connectionId)
     {
         GameDebug.Assert(connectionState == ConnectionState.Connecting);
     }
 }
示例#3
0
    public GameWorld(string name = "world")
    {
        if (gameobjectHierarchy.IntValue == 1)
        {
            m_sceneRoot = new GameObject(name);
            GameObject.DontDestroyOnLoad(m_sceneRoot);
        }

#if UNITY_EDITOR
        // When running in editor the world could be created, so we silently keep it.
        m_ECSWorld = World.Active != null ? World.Active : new World(name);
#else
        GameDebug.Assert(World.Active == null);
        m_ECSWorld = new World(name);
#endif


        World.Active    = m_ECSWorld;
        m_EntityManager = m_ECSWorld.GetOrCreateManager <EntityManager>();

        GameDebug.Assert(m_EntityManager.IsCreated);

        worldTime.tickRate = 60;

        nextTickTime = Game.frameTime;

        s_Worlds.Add(this);

        m_destroyDespawningSystem = m_ECSWorld.CreateManager <DestroyDespawning>();
    }
示例#4
0
    EffectTypeData RegisterImpactType(VisualEffectAsset template)
    {
        GameDebug.Assert(!m_EffectTypeData.ContainsKey(template));

        GameObject go = new GameObject(template.name);

        go.transform.parent     = m_rootGameObject.transform;
        go.transform.position   = Vector3.zero;
        go.transform.rotation   = Quaternion.identity;
        go.transform.localScale = Vector3.one;
        var vfx = go.AddComponent <VisualEffect>();

        vfx.visualEffectAsset = template;
        vfx.Reinit();
        vfx.Stop();

        var data = new EffectTypeData
        {
            visualEffect   = vfx,
            eventAttribute = vfx.CreateVFXEventAttribute(),
        };

        m_EffectTypeData.Add(template, data);

        return(data);
    }
示例#5
0
    public void RetrieveCommand(uint tick)
    {
        var localPlayerState = m_world.EntityManager.GetComponentData <LocalPlayer>(m_LocalPlayer);

        GameDebug.Assert(localPlayerState.playerEntity != null, "No player state set");
        if (localPlayerState.controlledEntity == Entity.Null)
        {
            return;
        }

        if (!m_world.EntityManager.HasComponent <PlayerControlled.State>(localPlayerState.controlledEntity))
        {
            return;
        }

        var buf = m_world.EntityManager.GetBuffer <UserCommand>(m_LocalPlayer);

        var userCommand = m_world.EntityManager.GetComponentData <PlayerControlled.State>(localPlayerState.controlledEntity);

        // Normally we can expect commands to be present, but if client has done hardcatchup commands might not have been generated yet
        // so we just use the defaultCommand

        var command = UserCommand.defaultCommand;
        var found   = buf.GetDataAtTick(tick, out command);

        //GameDebug.Assert(found, "Failed to find command for tick:{0}", tick);

        userCommand.prevCommand = userCommand.command;
        userCommand.command     = command;

        m_world.EntityManager.SetComponentData(localPlayerState.controlledEntity, userCommand);
    }
    protected bool CanSendPackage(ref BitOutputStream output)
    {
        if (!outstandingPackages.Available(outSequence)) // running out here means we hit 64 packs without any acks from client...
        {
            // We have too many outstanding packages. We need the other end to send something to us, so we know he
            // is alive. This happens for example when we break the client in the debugger while the server is still
            // sending messages but potentially it could also happen in extreme cases of congestion or package loss.
            // We will try to send empty packages with low frequency to see if we can get the connection up and running again

            if (Game.frameTime >= chokedTimeToNextPackage)
            {
                chokedTimeToNextPackage = Game.frameTime + NetworkConfig.netChokeSendInterval.FloatValue;

                // Treat the last package as lost
                int chokedSequence;
                var info = outstandingPackages.TryGetByIndex(outSequence % outstandingPackages.Capacity, out chokedSequence);
                GameDebug.Assert(info != null);

                NotifyDelivered(chokedSequence, info, false);

                counters.chokedPackagesOut++;

                info.Reset();
                outstandingPackages.Remove(chokedSequence);

                // Send empty package
                TPackageInfo emptyPackage;
                BeginSendPackage(ref output, out emptyPackage);
                CompleteSendPackage(emptyPackage, ref output);
            }
            return(false);
        }
        return(true);
    }
示例#7
0
    static void AddTranslateScaleChains(TranslateScale.TranslateScaleChain translateScaleChain)
    {
        if (!translateScaleChain.HasValidData())
        {
            return;
        }

        GameDebug.Assert(s_SourceJoints.length < k_MaxDrivers, "You are trying to add more translate scale chains then there is allocated space for.");
        GameDebug.Assert(s_DrivenJoints.length + translateScaleChain.drivenJoints.Count <= k_MaxDrivenJoints, "You are trying to add more driven joint then there is allocated space for.");

        s_SourceJoints.Add(translateScaleChain.driver);
        s_SourceData[s_DriverIndex] = new SourceData
        {
            bindpose = translateScaleChain.bindpose
        };

        for (var j = 0; j < translateScaleChain.drivenJoints.Count; j++)
        {
            if (translateScaleChain.drivenJoints[j].joint != null)
            {
                s_DrivenJoints.Add(translateScaleChain.drivenJoints[j].joint);
                s_TargetData[s_DrivenIndex] = new TargetData
                {
                    sourceIndex   = s_DriverIndex,
                    bindpose      = translateScaleChain.drivenJoints[j].bindpose,
                    stretchFactor = translateScaleChain.drivenJoints[j].strectchFactor,
                    scaleFactor   = translateScaleChain.drivenJoints[j].scaleFactor
                };
                s_DrivenIndex++;
            }
        }

        s_DriverIndex++;
    }
示例#8
0
    public void Initialize(EntityManager entityManager, Entity owner, Entity character)
    {
        m_Animator = entityManager.GetComponentObject <Animator>(owner);

        m_Animator.fireEvents = fireAnimationEvents;

        GameDebug.Assert(animStateDefinition != null, "No animStateDefinition defined for AnimStateController:" + this.name);

        Profiler.BeginSample("Create graph");
        m_PlayableGraph = PlayableGraph.Create(name);
        Profiler.EndSample();

#if UNITY_EDITOR
        GraphVisualizerClient.Show(m_PlayableGraph);
#endif

        Profiler.BeginSample("Instantiate playables");
        m_animGraph = animStateDefinition.Instantiate(entityManager, owner, m_PlayableGraph, character);
        Profiler.EndSample();

        m_animGraphLogic = m_animGraph as IGraphLogic;

        m_PlayableGraph.Play();

        var outputPlayable = Playable.Null;
        var outputPort     = 0;
        m_animGraph.GetPlayableOutput(0, ref outputPlayable, ref outputPort);

        // Set graph output
        var animationOutput = AnimationPlayableOutput.Create(m_PlayableGraph, "Animator", m_Animator);
        animationOutput.SetSourcePlayable(outputPlayable);
        animationOutput.SetSourceOutputPort(outputPort);
    }
示例#9
0
        public TwoBoneIkAnimNode(Animator animator, Skeleton skeleton, PlayableGraph graph, AnimGraph_TwoBoneIk settings)
        {
            m_graph = graph;

            var targetBone = skeleton.bones[skeleton.GetBoneIndex(settings.targetBone.GetHashCode())];
            var drivenBone = skeleton.bones[skeleton.GetBoneIndex(settings.drivenBone.GetHashCode())];


            // Setup settings
            var ikSettings = new TwoBoneIKJob.IkChain();

            ikSettings.target.target          = targetBone;
            ikSettings.target.readFrom        = TwoBoneIKJob.TargetType.Stream;
            ikSettings.driven.type            = TwoBoneIKJob.IkType.Generic;
            ikSettings.driven.genericEndJoint = drivenBone;
//            ikSettings.driven.humanoidLimb = AvatarIKGoal.LeftFoot;

            // Create job
            var leftArmIkJob = new TwoBoneIKJob();
            var initialized  = leftArmIkJob.Setup(animator, ikSettings, typeof(AnimStateController),
                                                  "leftArmIK.weight.value", "leftArmIK.weight.propertyOffset", "leftArmIK.target.offset");

            GameDebug.Assert(initialized, "Failed to initialize TwoBoneIKJob");
            m_ikPlayable = AnimationScriptPlayable.Create(graph, leftArmIkJob, 1);
            m_ikPlayable.SetInputWeight(0, 1);
        }
示例#10
0
    public void WriteBytesOffset(byte[] data, int srcIndex, int offset, int length)
    {
        GameDebug.Assert(data != null);

        NetworkUtils.MemCopy(data, srcIndex, m_Buffer, offset, length);
        m_CurrentByteIdx += length;
    }
示例#11
0
    protected override void OnUpdate()
    {
        // Add entities that needs change to buffer (as we cant destroy/create while iterating)
        var gameEntityTypeArray = Group.GetComponentDataArray <PresentationOwnerData>();
        var entityArray         = Group.GetEntityArray();

        m_entityBuffer.Clear();
        m_typeDataBuffer.Clear();
        for (int i = 0; i < gameEntityTypeArray.Length; i++)
        {
            var typeData = gameEntityTypeArray[i];

            if (typeData.variation == typeData.currentVariation)
            {
                continue;
            }

            m_entityBuffer.Add(entityArray[i]);
            m_typeDataBuffer.Add(typeData);
        }

        for (int i = 0; i < m_entityBuffer.Count; i++)
        {
            var entity   = m_entityBuffer[i];
            var typeData = m_typeDataBuffer[i];

            var replicatedData = EntityManager.GetComponentData <ReplicatedEntityData>(entity);

            WeakAssetReference presentationGuid;
            var found = m_presentationRegistry.GetPresentation(replicatedData.assetGuid, out presentationGuid);

            if (!found)
            {
                continue;
            }



//            var registryEntry = m_assetRegistry.GetEntry(replicatedData.assetGuid);
//
//            if (registryEntry == null)
//                continue;
//
//            if (registryEntry.factory == null)
//                continue;

            //var presentation = registryEntry.factory.CreateVariation(EntityManager, m_resourceManager, m_world, entity, 0);

            var presentation = m_resourceManager.CreateEntity(presentationGuid);
            GameDebug.Assert(presentation != Entity.Null, "failed to create presentation");


            typeData.currentVariation       = typeData.variation;
            typeData.currentVariationEntity = presentation;
            EntityManager.SetComponentData(entity, typeData);

            var presentationEntity = EntityManager.GetComponentObject <PresentationEntity>(presentation);
            presentationEntity.ownerEntity = entity;
        }
    }
示例#12
0
    public void SendChatAnnouncement(CharBufView message)
    {
        var time    = (Game.Clock.ElapsedMilliseconds - m_StartTime) / 1000;
        var minutes = (int)time / 60;
        var seconds = (int)time % 60;

        var formatted_length = StringFormatter.Write(ref _buf, 0, "<color=#ffffffff>[{0}:{1:00}]</color><color=#ffa500ff> {2}</color>", minutes, seconds, message);

        unsafe
        {
            fixed(char *ptr = message.buf)
            {
                GameDebug.Assert(message.length <= NativeString512.MaxLength);
                var msg = new NativeString512();

                msg.CopyFrom(ptr, (ushort)message.length);

                var connectionEntities = m_ConnectionQuery.ToEntityArray(Allocator.TempJob);

                for (int i = 0; i < connectionEntities.Length; ++i)
                {
                    var connectionEntity = connectionEntities[i];
                    m_RpcChatQueue.Schedule(EntityManager.GetBuffer <OutgoingRpcDataStreamBufferComponent>(connectionEntity), new RpcChatMessage {
                        Message = msg
                    });
                }

                connectionEntities.Dispose();
            }
        }
    }
示例#13
0
        public Instance(EntityManager entityManager, Entity owner, PlayableGraph graph, AnimGraph_CameraNoise settings)
        {
            m_Settings      = settings;
            m_graph         = graph;
            m_EntityManager = entityManager;
            m_Owner         = owner;

            GameDebug.Assert(entityManager.HasComponent <Animator>(owner), "Owner has no Animator component");
            var animator = entityManager.GetComponentObject <Animator>(owner);

            GameDebug.Assert(entityManager.HasComponent <Skeleton>(owner), "Owner has no Skeleton component");
            var skeleton = entityManager.GetComponentObject <Skeleton>(owner);

            var cameraBone        = skeleton.bones[skeleton.GetBoneIndex(settings.cameraBone.GetHashCode())];
            var characterRootBone = skeleton.bones[skeleton.GetBoneIndex(settings.characterRootBone.GetHashCode())];

            var cameraNoiseSettings = new CameraNoiseJob.EditorSettings();

            cameraNoiseSettings.cameraBone        = cameraBone;
            cameraNoiseSettings.characterRootBone = characterRootBone;
            cameraNoiseSettings.jobSettings       = settings.cameraNoiseJobSettings;

            var noiseJob    = new CameraNoiseJob();
            var initialized = noiseJob.Setup(animator, cameraNoiseSettings);

            GameDebug.Assert(initialized, "Failed to initialize AimDragJob");
            m_NoisePlayable = AnimationScriptPlayable.Create(graph, noiseJob, 1);
            m_NoisePlayable.SetInputWeight(0, 1);
        }
示例#14
0
    public void Register(int entityId, Entity entity, INetworkSerializable[] serializableArray)
    {
        // Grow to make sure there is room for entity
        if (entityId >= m_replicatedData.Count)
        {
            var count     = entityId - m_replicatedData.Count + 1;
            var emptyData = new ReplicatedData();
            for (var i = 0; i < count; i++)
            {
                m_replicatedData.Add(emptyData);
            }
        }

        GameDebug.Assert(m_replicatedData[entityId].entity == Entity.Null, "ReplicatedData has entity set:{0}", m_replicatedData[entityId].entity);

        // Sort serializables by type name so server and client agree on order
        networkSerializables.Clear();
        networkSerializables.AddRange(serializableArray);
        networkSerializables.Sort((p1, p2) => p1.GetType().Name.CompareTo(p2.GetType().Name));

        var data = new ReplicatedData
        {
            entity            = entity,
            serializableArray = networkSerializables.ToArray()
        };

        m_replicatedData[entityId] = data;
    }
示例#15
0
    static void AddTwistChain(Twist.TwistChain twistChain)
    {
        if (!twistChain.HasValidData())
        {
            return;
        }

        GameDebug.Assert(s_SourceJoints.length < k_MaxSetups, "You are trying to add more twist joint chains then there is allocated space for.");
        GameDebug.Assert(s_TwistJoints.length + twistChain.twistJoints.Count <= k_MaxTwistJoints, "You are trying to add more twist joint then there is allocated space for.");

        s_SourceJoints.Add(twistChain.driver);
        s_SourceData[s_SetupIndex] = new SourceData
        {
            bindpose = twistChain.bindpose
        };

        for (var j = 0; j < twistChain.twistJoints.Count; j++)
        {
            if (twistChain.twistJoints[j].joint != null)
            {
                s_TwistJoints.Add(twistChain.twistJoints[j].joint);
                s_TargetData[s_TwistIndex] = new TargetData
                {
                    sourceIndex = s_SetupIndex,
                    twistFactor = twistChain.twistJoints[j].factor
                };
                s_TwistIndex++;
            }
        }

        s_SetupIndex++;
    }
示例#16
0
        public static void GenerateHuffmanCodes(byte[] symboLCodes, int symbolCodesOffset, byte[] symbolLengths, int symbolLengthsOffset, int alphabetSize, int maxCodeLength)
        {
            GameDebug.Assert(alphabetSize <= 256);
            GameDebug.Assert(maxCodeLength <= 8);

            var lengthCounts = new byte[maxCodeLength + 1];
            var symbolList   = new byte[maxCodeLength + 1, alphabetSize];

            //byte[] symbol_list[(MAX_HUFFMAN_CODE_LENGTH + 1u) * MAX_NUM_HUFFMAN_SYMBOLS];
            for (int symbol = 0; symbol < alphabetSize; symbol++)
            {
                int length = symbolLengths[symbol + symbolLengthsOffset];
                GameDebug.Assert(length <= maxCodeLength);
                symbolList[length, lengthCounts[length]++] = (byte)symbol;
            }

            uint nextCodeWord = 0;

            for (int length = 1; length <= maxCodeLength; length++)
            {
                int length_count = lengthCounts[length];
                for (int i = 0; i < length_count; i++)
                {
                    int symbol = symbolList[length, i];
                    GameDebug.Assert(symbolLengths[symbol + symbolLengthsOffset] == length);
                    symboLCodes[symbol + symbolCodesOffset] = (byte)ReverseBits(nextCodeWord++, length);
                }
                nextCodeWord <<= 1;
            }
        }
示例#17
0
        public Instance(EntityManager entityManager, Entity owner, PlayableGraph graph, Entity animStateOwner, AnimGraph_Banking settings)
        {
            m_Settings       = settings;
            m_EntityManager  = entityManager;
            m_Owner          = owner;
            m_AnimStateOwner = animStateOwner;

            GameDebug.Assert(entityManager.HasComponent <Animator>(owner), "Owner has no Animator component");
            var animator = entityManager.GetComponentObject <Animator>(owner);

            GameDebug.Assert(entityManager.HasComponent <Skeleton>(owner), "Owner has no Skeleton component");
            var skeleton = entityManager.GetComponentObject <Skeleton>(owner);

            GameDebug.Assert(entityManager.HasComponent <CharPredictedStateData>(m_AnimStateOwner), "Owner has no CharPredictedState component");

            var bankTransform = skeleton.bones[skeleton.GetBoneIndex(settings.bankTransform.GetHashCode())];

            var bankingSettings = new BankingJob.EditorSettings();

            bankingSettings.bankTransform = bankTransform;
            bankingSettings.settings      = settings.bankingSettings;

            var bankingJob = new BankingJob();

            m_HeadLeftRightMuscles  = new NativeArray <MuscleHandle>(2, Allocator.Persistent);
            m_SpineLeftRightMuscles = new NativeArray <MuscleHandle>(3, Allocator.Persistent);
            var initialized = bankingJob.Setup(animator, bankingSettings, 2312, m_HeadLeftRightMuscles, m_SpineLeftRightMuscles);

            GameDebug.Assert(initialized, "Failed to initialize BankingJob");
            m_Playable = AnimationScriptPlayable.Create(graph, bankingJob);
        }
示例#18
0
    public void WriteUIntPacked(long value)
    {
        GameDebug.Assert(value >= 0);

        int outputBits    = 1;
        int numPrefixBits = 0;

        while (value >= (1L << outputBits))  // RUTODO: Unroll this and merge with bit output. How do we actually verify inlining in C#?
        {
            value      -= (1L << outputBits);
            outputBits += 2;
            numPrefixBits++;
        }
        WriteBits(1u << numPrefixBits, numPrefixBits + 1);

        if (outputBits > 32)
        {
            WriteBits((uint)value, 32);
            WriteBits((uint)(value >> 32), outputBits - 32);
        }
        else
        {
            WriteBits((uint)value, outputBits);
        }
    }
    private void OnEnable()
    {
        var gameObjectEntity = GetComponent <GameObjectEntity>();
        var entityManager    = gameObjectEntity.EntityManager;
        var abilityEntity    = gameObjectEntity.Entity;

        // Default components
        entityManager.AddComponentData(abilityEntity, new CharacterAbility());
        entityManager.AddComponentData(abilityEntity, new AbilityControl());

        // Ability components

        var guid      = Guid.Parse(grenadePrefab.guid);
        var byteArray = guid.ToByteArray();

        GameDebug.Assert(byteArray.Length == 16, "Guid byte array length:{0}. SHould be 16", byteArray.Length);
        settings.SetGrenadePrefabGuid(byteArray);
        entityManager.AddComponentData(abilityEntity, settings);
        entityManager.AddComponentData(abilityEntity, new LocalState());
        entityManager.AddComponentData(abilityEntity, new PredictedState());
        entityManager.AddComponentData(abilityEntity, new InterpolatedState());


        // Setup replicated ability
        var replicatedAbility = entityManager.GetComponentObject <ReplicatedAbility>(abilityEntity);

        replicatedAbility.predictedHandlers       = new IPredictedDataHandler[2];
        replicatedAbility.predictedHandlers[0]    = new PredictedEntityHandler <AbilityControl>(entityManager, abilityEntity);
        replicatedAbility.predictedHandlers[1]    = new PredictedEntityHandler <PredictedState>(entityManager, abilityEntity);
        replicatedAbility.interpolatedHandlers    = new IInterpolatedDataHandler[1];
        replicatedAbility.interpolatedHandlers[0] = new InterpolatedEntityHandler <InterpolatedState>(entityManager, abilityEntity);
    }
示例#20
0
    protected override void OnUpdate()
    {
        var requestArray = DespawnGroup.ToComponentDataArray <CharacterDespawnRequest>(Allocator.Persistent);

        if (requestArray.Length == 0)
        {
            requestArray.Dispose();
            return;
        }

        Profiler.BeginSample("HandleCharacterDespawnRequests");

        var requestEntityArray = DespawnGroup.ToEntityArray(Allocator.Persistent);

        for (var i = 0; i < requestArray.Length; i++)
        {
            var request = requestArray[i];

            GameDebug.Assert(EntityManager.HasComponent <Character.State>(request.characterEntity), "Character despawn requst entity is not a character");

            Inventory.Server_DestroyAll(EntityManager, PostUpdateCommands, request.characterEntity);

            GameDebug.Log(World, Character.ShowLifetime, "Despawning character:{0}", request.characterEntity);

            PrefabAssetManager.DestroyEntity(EntityManager, request.characterEntity);
            PostUpdateCommands.DestroyEntity(requestEntityArray[i]);
            if (Character.ShowLifetime.IntValue > 0)
            {
                AnimationGraphHelper.DumpState(World);
            }
        }
        requestEntityArray.Dispose();
        requestArray.Dispose();
        Profiler.EndSample();
    }
示例#21
0
        public void ProcessSnapshot(ISnapshotConsumer consumer)
        {
            // Should we prune list for stuff that is also in despawns?
            foreach (var id in spawns)
            {
                GameDebug.Assert(entities[id].type != null, "Processing spawn of id {0} but type is null", id);
                consumer.ProcessEntitySpawn(serverTime, id, entities[id].type.typeId);
            }

            spawns.Clear();

            foreach (var id in updates)
            {
                var info = entities[id];
                GameDebug.Assert(info.type != null, "Processing update of id {0} but type is null", id);
                var reader = new NetworkReader(info.lastUpdate, info.type.schema);
                consumer.ProcessEntityUpdate(serverTime, id, ref reader);
            }

            updates.Clear();

            foreach (var id in despawns)
            {
                consumer.ProcessEntityDespawn(serverTime, id);
            }

            despawns.Clear();
        }
    public float SetBlendPosition(Vector2 position, bool updateGraph = true)
    {
        var count = m_Nodes.Count;

        for (var i = 0; i < count; i++)
        {
            m_Positions[i] = m_Nodes[i].position;
        }
        CalculateWeights(m_Positions, ref m_Weights, position);

        // Store results and calculate blendedClipLength
        m_BlendedClipLength = 0f;
        for (var i = 0; i < count; i++)
        {
            var node = m_Nodes[i];
            node.weight          = m_Weights[i];
            m_Nodes[i]           = node;
            m_BlendedClipLength += node.clipLength / m_Nodes[i].speed * node.weight;
        }

        GameDebug.Assert(m_BlendedClipLength > 0f, "blendedClipLength must be more that 0");
        m_BlendedClipLength /= masterSpeed;

        if (updateGraph)
        {
            UpdateGraph();
        }

        return(m_BlendedClipLength);
    }
示例#23
0
    public GameWorld(string name = "world")
    {
        if (gameobjectHierarchy.IntValue == 1)
        {
            m_sceneRoot = new GameObject(name);
            GameObject.DontDestroyOnLoad(m_sceneRoot);
        }

        m_ECSWorld      = new World(name);
        World.Active    = m_ECSWorld;
        m_EntityManager = m_ECSWorld.GetOrCreateManager <EntityManager>();

        //InjectionHookSupport.RegisterHook(new GameObjectArrayInjectionHook());
        //InjectionHookSupport.RegisterHook(new TransformAccessArrayInjectionHook());
        InjectionHookSupport.RegisterHook(new ComponentArrayInjectionHook());

        GameDebug.Assert(m_EntityManager.IsCreated);

        worldTime.tickRate = 60;

        nextTickTime = Game.frameTime;

        s_Worlds.Add(this);

        m_destroyDespawningSystem = m_ECSWorld.CreateManager <DestroyDespawning>();
    }
示例#24
0
    protected override void Update(Entity entity, CharacterPresentationSetup charPresentation, RagdollOwner ragdollOwner)
    {
        GameDebug.Assert(ragdollOwner.ragdollInstance != null, "Ragdoll instance is NULL for object: {0}", ragdollOwner.gameObject);
        GameDebug.Assert(EntityManager.Exists(charPresentation.character), "CharPresentation character does not exist");
        GameDebug.Assert(EntityManager.HasComponent <RagdollStateData>(charPresentation.character), "CharPresentation character does not have RagdollState");

        var ragdollState = EntityManager.GetComponentData <RagdollStateData>(charPresentation.character);

        if (ragdollState.ragdollActive == 0)
        {
            return;
        }

        switch (ragdollOwner.phase)
        {
        case RagdollOwner.Phase.Inactive:

            ragdollOwner.timeUntilStart -= m_world.frameDuration;

            if (ragdollOwner.timeUntilStart <= m_world.worldTime.tickInterval)
            {
                // Store bone transforms so they can be used to calculate bone velocity next frame
                for (int boneIndex = 0; boneIndex < ragdollOwner.targeteBones.Length; boneIndex++)
                {
                    if (ragdollOwner.targeteBones[boneIndex] == null)
                    {
                        continue;
                    }

                    ragdollOwner.lastBonePositions[boneIndex] = ragdollOwner.targeteBones[boneIndex].position;
                    ragdollOwner.lastBoneRotations[boneIndex] = ragdollOwner.targeteBones[boneIndex].rotation;
                }

                ragdollOwner.phase = RagdollOwner.Phase.PoseSampled;
            }

            break;

        case RagdollOwner.Phase.PoseSampled:

            IntializeRagdoll(ragdollOwner, true, ragdollState.impulse);
            ragdollOwner.phase = RagdollOwner.Phase.Active;

            break;

        case RagdollOwner.Phase.Active:

            for (int boneIndex = 0; boneIndex < ragdollOwner.targeteBones.Length; boneIndex++)
            {
                if (ragdollOwner.targeteBones[boneIndex] == null)
                {
                    continue;
                }

                ragdollOwner.targeteBones[boneIndex].position = ragdollOwner.ragdollSkeleton.bones[boneIndex].position;
                ragdollOwner.targeteBones[boneIndex].rotation = ragdollOwner.ragdollSkeleton.bones[boneIndex].rotation;
            }
            break;
        }
    }
示例#25
0
    public void SendData()
    {
        if (m_Connection == null || m_Connection.connectionState == ConnectionState.Disconnected)
        {
            return;
        }

        if (clientBlockOut.IntValue > 0)
        {
            return;
        }

        Profiler.BeginSample("NetworkClient.SendData");

#pragma warning disable 0162 // unreachable code
        switch (NetworkConfig.ioStreamType)
        {
        case NetworkCompression.IOStreamType.Raw:
            m_Connection.SendPackage <RawOutputStream>();
            break;

        case NetworkCompression.IOStreamType.Huffman:
            m_Connection.SendPackage <HuffmanOutputStream>();
            break;

        default:
            GameDebug.Assert(false);
        }
#pragma warning restore

        Profiler.EndSample();
    }
示例#26
0
    protected override void OnUpdate()
    {
        var requestArray = DespawnGroup.GetComponentDataArraySt <CharacterDespawnRequest>();

        if (requestArray.Length == 0)
        {
            return;
        }

        Profiler.BeginSample("HandleCharacterDespawnRequests");

        var requestEntityArray = DespawnGroup.GetEntityArraySt();

        for (var i = 0; i < requestArray.Length; i++)
        {
            var request = requestArray[i];

            var character = EntityManager
                            .GetComponentObject <Character>(request.characterEntity);
            GameDebug.Assert(character != null, "Character despawn requst entity is not a character");

            GameDebug.Log("Despawning character:" + character.name + " tick:" + m_world.worldTime.tick);

            m_world.RequestDespawn(character.gameObject, PostUpdateCommands);

            var charRepAll = EntityManager.GetComponentData <CharacterReplicatedData>(request.characterEntity);
            m_world.RequestDespawn(PostUpdateCommands, charRepAll.abilityCollection);

            PostUpdateCommands.DestroyEntity(requestEntityArray[i]);
        }

        Profiler.EndSample();
    }
    public HandleSpatialEffectRequests(GameWorld world, GameObject systemRoot, BundledResourceManager resourceSystem) : base(world)
    {
        var effectBundle = resourceSystem.GetResourceRegistry <SpatialEffectRegistry>();

        GameDebug.Assert(effectBundle != null, "No HitscanEffectRegistry defined in registry");

        m_Pools = new Pool[effectBundle.entries.Length];
        for (var i = 0; i < effectBundle.entries.Length; i++)
        {
            var entry    = effectBundle.entries[i];
            var resource = resourceSystem.LoadSingleAssetResource(entry.prefab.guid);
            GameDebug.Assert(resource != null);

            var prefab = resource as GameObject;
            GameDebug.Assert(prefab != null);

            var pool = new Pool();
            pool.instances = new SpatialEffectInstance[entry.poolSize];
            for (var j = 0; j < pool.instances.Length; j++)
            {
                var go = GameObject.Instantiate(prefab);

                if (systemRoot != null)
                {
                    go.transform.SetParent(systemRoot.transform, false);
                }

                pool.instances[j] = go.GetComponent <SpatialEffectInstance>();
                GameDebug.Assert(pool.instances[j], "Effect prefab does not have SpatialEffectInstance component");
            }

            m_Pools[i] = pool;
        }
    }
        public Instance(EntityManager entityManager, Entity owner, PlayableGraph graph, Entity animStateOwner, AnimGraph_DamageReaction settings)
        {
            m_settings       = settings;
            m_graph          = graph;
            m_EntityManager  = entityManager;
            m_Owner          = owner;
            m_AnimStateOwner = animStateOwner;

            m_rootMixer = AnimationLayerMixerPlayable.Create(graph, 2);
            m_rootMixer.SetInputWeight(0, 1f);

            // Setup blend mixer
            m_blendMixer = AnimationMixerPlayable.Create(graph, 4);
            GameDebug.Assert(m_settings.clips != null && m_settings.clips.Length > 0, "No animation clips added to damagereaction settings:{0}", settings.name);
            for (var i = 0; i < m_settings.clips.Length; i++)
            {
                var clipPlayable = AnimationClipPlayable.Create(graph, m_settings.clips[i]);
                clipPlayable.SetApplyFootIK(false);
                clipPlayable.Pause();
                graph.Connect(clipPlayable, 0, m_blendMixer, i);

                if (m_settings.clips[i].length > m_reactionAnimDuration)
                {
                    m_reactionAnimDuration = m_settings.clips[i].length;
                }
            }
            m_reactionAnimAngleSpan = 360 / m_blendMixer.GetInputCount();
            graph.Connect(m_blendMixer, 0, m_rootMixer, m_blendMixerPort);
            m_rootMixer.SetLayerAdditive(m_blendMixerPort, true);
        }
示例#29
0
文件: Game.cs 项目: nolovelost/le-mat
    public void RequestGameLoop(System.Type type, string[] args)
    {
        GameDebug.Assert(typeof(IGameLoop).IsAssignableFrom(type));

        m_RequestedGameLoopTypes.Add(type);
        m_RequestedGameLoopArguments.Add(args);
        GameDebug.Log("Game loop " + type + " requested");
    }
    public void SetFactory(int registryId, ReplicatedEntityFactory factory)
    {
        GameDebug.Assert(entries[registryId].prefab.guid == "", "GUID already set");
        GameDebug.Assert(entries[registryId].factory == null, "Factory already set");

        entries[registryId].factory = factory;
        EditorUtility.SetDirty(this);
    }