protected override void OnUpdate()
    {
        //We want to run this as parallel jobs so we need to add "AsParallelWriter" when creating
        //our command buffer
        var commandBuffer = m_EndFixedStepSimECB.CreateCommandBuffer().AsParallelWriter();

        //We must declare our local variables that we will use in our job
        var settings = GetSingleton <GameSettingsComponent>();

        //This time we query entities with components by using "WithAll" tag
        //This makes sure that we only grab entities with an AsteroidTag component so we don't affect other entities
        //that might have passed the perimeter of the cube
        Entities
        .WithAll <AsteroidTag>()
        .ForEach((Entity entity, int nativeThreadIndex, in Translation position) =>
        {
            //We check if the current Translation value is out of bounds
            if (Mathf.Abs(position.Value.x) > settings.levelWidth / 2 ||
                Mathf.Abs(position.Value.y) > settings.levelHeight / 2 ||
                Mathf.Abs(position.Value.z) > settings.levelDepth / 2)
            {
                //If it is out of bounds wee add the DestroyTag component to the entity and return
                commandBuffer.AddComponent(nativeThreadIndex, entity, new DestroyTag());
                return;
            }
        }).ScheduleParallel();

        //We add the dependencies to the CommandBuffer that will be playing back these structural changes (adding a DestroyTag)
        m_EndFixedStepSimECB.AddJobHandleForProducer(Dependency);
    }
Ejemplo n.º 2
0
    protected override void OnUpdate()
    {
        // Assign values to local variables captured in your job here, so that it has
        // everything it needs to do its work when it runs later.
        // For example,
        //     float deltaTime = Time.DeltaTime;

        // This declares a new kind of job, which is a unit of work to do.
        // The job is declared as an Entities.ForEach with the target components as parameters,
        // meaning it will process all entities in the world that have both
        // Translation and Rotation components. Change it to process the component
        // types you want.

        var commandBuffer = _commandBufferSystem.CreateCommandBuffer();

        var actualTime = Time.ElapsedTime;

        Entities.WithNone <Dead>().ForEach((in Entity entity, in DestroyAfterTime destroyAfterTime) =>
        {
            // Implement the work to perform for each entity here.
            // You should only access data that is local or that is a
            // field on this job. Note that the 'rotation' parameter is
            // marked as 'in', which means it cannot be modified,
            // but allows this job to run in parallel with other jobs
            // that want to read Rotation component data.
            // For example,
            //     translation.Value += math.mul(rotation.Value, new float3(0, 0, 1)) * deltaTime;

            if (actualTime - destroyAfterTime.BirthTime < destroyAfterTime.CountDown)
            {
                return;
            }

            commandBuffer.AddComponent <Dead>(entity);
        }).Schedule();
Ejemplo n.º 3
0
        protected override void OnUpdate()
        {
            var ecb = _endFixedECBSystem.CreateCommandBuffer();

            var jobHandle = new SelectionJob
            {
                SelectionVolumes = GetComponentDataFromEntity <SelectionColliderTag>(),
                Units            = GetComponentDataFromEntity <SelectableUnitTag>(),
                ECB = ecb
            }.Schedule(_stepPhysicsWorld.Simulation, ref _buildPhysicsWorld.PhysicsWorld, Dependency);

            jobHandle.Complete();

            var selectionEntity = GetSingletonEntity <SelectionColliderTag>();

            if (HasComponent <StepsToLiveData>(selectionEntity))
            {
                var stepsToLive = GetComponent <StepsToLiveData>(selectionEntity);
                stepsToLive.Value--;
                ecb.SetComponent(selectionEntity, stepsToLive);
                if (stepsToLive.Value <= 0)
                {
                    ecb.DestroyEntity(selectionEntity);
                }
            }
            else
            {
                ecb.AddComponent <StepsToLiveData>(selectionEntity);
                ecb.SetComponent(selectionEntity, new StepsToLiveData {
                    Value = 1
                });
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Handles starships spawning.
        /// </summary>
        protected override void OnUpdate()
        {
            var deltaTime = Time.DeltaTime;
            var ecb       = _ecbSystem.CreateCommandBuffer().AsParallelWriter();

            // Get a NativeArray that contains random generators for all threads from the RandomSystem that will be
            // used to randomize the spawning. We also have to use WithNativeDisableParallelForRestriction() to
            // disable the safety system that would prevent us to create a potential Race Condition.
            // We can do this because we know that each worker will be working with one specific element
            // of the Native Array and we won't dispose the array during the job execution.
            var randomArray = World.GetExistingSystem <RandomSystem>().RandomGenerators;

            Entities.WithNativeDisableParallelForRestriction(randomArray).ForEach(
                (Entity entity, int nativeThreadIndex, ref ShipSpawnerComponent shipSpawner,
                 ref StarshipConfigComponent shipConfig, ref TeamComponent team) => {
                var random = randomArray[nativeThreadIndex];     // Get random generator for this thread

                shipSpawner.SecondsFromLastSpawn += deltaTime;   // Increase the spawn timer
                if (shipSpawner.SecondsFromLastSpawn >= shipSpawner.SecondsBetweenSpawns)
                {
                    shipSpawner.SecondsFromLastSpawn = 0;     // Reset the spawn timer

                    // Instantiate an entity from the prefab and set its components
                    var shipEntity = ecb.Instantiate(nativeThreadIndex, shipSpawner.Prefab);
                    ecb.SetComponent(nativeThreadIndex, shipEntity, new Translation {
                        Value = shipSpawner.SpawnPosition
                    });
                    ecb.SetComponent(nativeThreadIndex, shipEntity, new MovementComponent {
                        // Randomize the heading of the spawned entity
                        Heading  = new float3(random.NextFloat(-1f, 1f), random.NextFloat(-1f, 1f), 0f),
                        Target   = shipSpawner.SpawnPosition,
                        MaxSpeed = shipConfig.MovementSpeed
                    });
                    ecb.SetComponent(nativeThreadIndex, shipEntity, new TeamComponent {
                        Team = team.Team, TeamColor = team.TeamColor
                    });
                    ecb.SetComponent(nativeThreadIndex, shipEntity,
                                     new TargetingComponent()
                    {
                        TargetingRadius = shipConfig.PursuitRadius, TargetEntity = entity, TargetLocked = false
                    });
                    ecb.SetComponent(nativeThreadIndex, shipEntity,
                                     new BoidComponent {
                        CellRadius               = shipConfig.CellRadius,
                        SeparationWeight         = shipConfig.SeparationWeight,
                        AlignmentWeight          = shipConfig.AlignmentWeight,
                        CohesionWeight           = shipConfig.CohesionWeight,
                        TargetWeight             = shipConfig.TargetWeight,
                        PursuitWeight            = shipConfig.PursuitWeight,
                        ObstacleAversionDistance = shipConfig.ObstacleAversionDistance,
                        SteeringSpeed            = shipConfig.SteeringSpeed
                    });
                }

                randomArray[nativeThreadIndex] = random;     // This has to be done here
            }).ScheduleParallel();

            _ecbSystem.AddJobHandleForProducer(Dependency);
        }
Ejemplo n.º 5
0
    protected override void OnUpdate()
    {
        CollisionWorld      collisionWorld = m_BuildPhysicsWorld.PhysicsWorld.CollisionWorld;
        EntityCommandBuffer commandBuffer  = m_EntityCommandBufferSystem.CreateCommandBuffer();

        Dependency = JobHandle.CombineDependencies(Dependency, m_EndFramePhysicsSystem.GetOutputDependency());

        Entities
        .WithName("RaycastWithCustomCollector")
        .WithBurst()
        .ForEach((Entity entity, ref Translation position, ref Rotation rotation, ref VisualizedRaycast visualizedRaycast) =>
        {
            var raycastLength = visualizedRaycast.RayLength;

            // Perform the Raycast
            var raycastInput = new RaycastInput
            {
                Start  = position.Value,
                End    = position.Value + (math.forward(rotation.Value) * visualizedRaycast.RayLength),
                Filter = CollisionFilter.Default
            };

            var collector = new IgnoreTransparentClosestHitCollector(collisionWorld);

            collisionWorld.CastRay(raycastInput, ref collector);

            var hit         = collector.ClosestHit;
            var hitDistance = raycastLength * hit.Fraction;

            // position the entities and scale based on the ray length and hit distance
            // visualization elements are scaled along the z-axis aka math.forward
            var newFullRayPosition = new float3(0, 0, raycastLength * 0.5f);
            var newFullRayScale    = new float3(1f, 1f, raycastLength);
            var newHitPosition     = new float3(0, 0, hitDistance);
            var newHitRayPosition  = new float3(0, 0, hitDistance * 0.5f);
            var newHitRayScale     = new float3(1f, 1f, raycastLength * hit.Fraction);

            commandBuffer.SetComponent(visualizedRaycast.HitPositionEntity, new Translation {
                Value = newHitPosition
            });
            commandBuffer.SetComponent(visualizedRaycast.HitRayEntity, new Translation {
                Value = newHitRayPosition
            });
            commandBuffer.SetComponent(visualizedRaycast.HitRayEntity, new NonUniformScale {
                Value = newHitRayScale
            });
            commandBuffer.SetComponent(visualizedRaycast.FullRayEntity, new Translation {
                Value = newFullRayPosition
            });
            commandBuffer.SetComponent(visualizedRaycast.FullRayEntity, new NonUniformScale {
                Value = newFullRayScale
            });
        }).Schedule();

        m_EntityCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
    protected override void OnUpdate()
    {
        Dependency = JobHandle.CombineDependencies(m_TriggerSystem.OutDependency, Dependency);

        var commandBuffer = m_CommandBufferSystem.CreateCommandBuffer();

        // Need this extra variable here so that it can
        // be captured by Entities.ForEach loop below
        var nonTriggerMask = m_NonTriggerMask;

        Entities
        .WithName("ChangeMaterialOnTriggerEnter")
        .WithoutBurst()
        .ForEach((Entity e, ref DynamicBuffer <StatefulTriggerEvent> triggerEventBuffer, ref TemporaryChangeMaterialOnTriggerComponent changeMaterial) =>
        {
            for (int i = 0; i < triggerEventBuffer.Length; i++)
            {
                var triggerEvent = triggerEventBuffer[i];
                var otherEntity  = triggerEvent.GetOtherEntity(e);

                // exclude other triggers and processed events
                if (triggerEvent.State == EventOverlapState.Stay || !nonTriggerMask.Matches(otherEntity))
                {
                    continue;
                }

                if (triggerEvent.State == EventOverlapState.Enter)
                {
                    var volumeRenderMesh           = EntityManager.GetSharedComponentData <RenderMesh>(e);
                    var overlappingRenderMesh      = EntityManager.GetSharedComponentData <RenderMesh>(otherEntity);
                    overlappingRenderMesh.material = volumeRenderMesh.material;

                    commandBuffer.SetSharedComponent(otherEntity, overlappingRenderMesh);
                }
                else
                {
                    // State == PhysicsEventState.Exit
                    if (changeMaterial.ReferenceEntity == Entity.Null)
                    {
                        continue;
                    }
                    var overlappingRenderMesh      = EntityManager.GetSharedComponentData <RenderMesh>(otherEntity);
                    var referenceRenderMesh        = EntityManager.GetSharedComponentData <RenderMesh>(changeMaterial.ReferenceEntity);
                    overlappingRenderMesh.material = referenceRenderMesh.material;


                    commandBuffer.SetSharedComponent(otherEntity, overlappingRenderMesh);
                }
            }
        }).Run();

        m_CommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
        protected override void OnUpdate( )
        {
            NativeArray <Entity> na_netNodes = group_netNodes.ToEntityArray(Allocator.TempJob);

            if (!isSystemInitialized)
            {
                if (na_netNodes.Length == 0)
                {
                    return;                             // Early exit.
                }
                isSystemInitialized = true;

                // nhm_entityIndex.Dispose () ;
                nhm_entityIndex = new NativeHashMap <Entity, int> (na_netNodes.Length, Allocator.Persistent);

                // Map node entities to hash map.
                for (int i = 0; i < na_netNodes.Length; i++)
                {
                    Entity nodeEntity = na_netNodes [i];
                    nhm_entityIndex.Add(nodeEntity, i);
                } // for

                // na_netNodes.Dispose () ;
            }

            EntityCommandBuffer.ParallelWriter ecbp = eecb.CreateCommandBuffer().AsParallelWriter();


            Dependency = new PathFindingJob()
            {
                na_netNodes = na_netNodes,

                nhm_entityIndex     = nhm_entityIndex,
                a_pathNodesPosition = GetComponentDataFromEntity <Translation> (true),
                pathNodeLinksBuffer = GetBufferFromEntity <PathNodeLinksBuffer> (true),

                pathPlannersHandle    = GetComponentTypeHandle <PathPlannerComponent> (false),
                pathNodesBufferHandle = GetBufferTypeHandle <PathNodesBuffer> (false),
            }.ScheduleParallel(group_pathPlanners, 1, Dependency);

            Entities
            .WithName("PathSearchedJob")
            .WithAll <IsAliveTag, PathPlannerComponent, CanFindPathTag> ()
            .ForEach((Entity entity, int entityInQueryIndex) =>
            {
                ecbp.RemoveComponent <CanFindPathTag> (entityInQueryIndex, entity);
            }).Schedule();

            eecb.AddJobHandleForProducer(Dependency);

            na_netNodes.Dispose(Dependency);
        }
Ejemplo n.º 8
0
        protected override void OnUpdate()
        {
            var commandBuffer = EndFixedStepSimulationEcbSystem.CreateCommandBuffer();

            Dependency = new ScoreBoxCollisionEventJob()
            {
                CommandBuffer = commandBuffer,
                ScoreBoxGroup = GetComponentDataFromEntity <ScoreBox>(true),
                PlayerGroup   = GetComponentDataFromEntity <Player>()
            }
            .Schedule(StepPhysicsWorldSystem.Simulation, ref BuildPhysicsWorldSystem.PhysicsWorld, this.Dependency);

            // Add the job as a dependency
            EndFixedStepSimulationEcbSystem.AddJobHandleForProducer(this.Dependency);
        }
Ejemplo n.º 9
0
    protected override void OnUpdate()
    {
        Dependency = JobHandle.CombineDependencies(m_TriggerSystem.OutDependency, Dependency);

        var commandBuffer = m_CommandBufferSystem.CreateCommandBuffer();

        // Need this extra variable here so that it can
        // be captured by Entities.ForEach loop below
        var nonTriggerMask = m_NonTriggerMask;


        Entities
        .WithName("PickUpOnTriggerEnter")
        .WithoutBurst()
        .ForEach((Entity e, ref DynamicBuffer <StatefulTriggerEvent> triggerEventBuffer, ref CollectibleTagComponent collectibleComponent) =>
        {
            for (int i = 0; i < triggerEventBuffer.Length; i++)
            {
                var triggerEvent = triggerEventBuffer[i];          // l'entity dell'oggetto collectible
                var otherEntity  = triggerEvent.GetOtherEntity(e); // l'oggetto dinamico che vi collide

                // exclude other triggers and processed events
                if (triggerEvent.State == EventOverlapState.Stay || !nonTriggerMask.Matches(otherEntity))
                {
                    continue;
                }

                if (triggerEvent.State == EventOverlapState.Enter && EntityManager.HasComponent <PlayerMovementSpeed>(otherEntity))
                {
                    var punteggioPlayer    = EntityManager.GetComponentData <PlayerScoreComponent>(otherEntity);
                    punteggioPlayer.score += collectibleComponent.points;

                    var ghostId = EntityManager.GetComponentData <GhostComponent>(otherEntity).ghostId;
                    // printa due volte perche' viene eseguito sulle simulazioni di client e su server
                    UnityEngine.Debug.Log(String.Format("Il player " + ghostId + " ha raccolto " + collectibleComponent.points + " punti. Tot punti player " + ghostId + ": " + punteggioPlayer.score));

                    // var deleteTag = new DeleteTagComponent();

                    // assolutamente necessari
                    commandBuffer.SetComponent(otherEntity, punteggioPlayer);
                    commandBuffer.AddComponent <DeleteTagComponent>(e, new DeleteTagComponent());
                }
            }
        }).Run();

        m_CommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
    protected override void OnUpdate()
    {
        var commandBufferParallel = m_CommandBufferSystem.CreateCommandBuffer().AsParallelWriter();

        var timeStep = Time.DeltaTime;
        var up       = math.up();

        var positions = GetComponentDataFromEntity <Translation>(true);

        Entities
        .WithName("ExplosionCountdown_Tick")
        .WithReadOnly(positions)
        .WithBurst()
        .ForEach((Entity entity, ref ExplosionCountdown explosion) =>
        {
            explosion.Countdown--;
            bool bang = explosion.Countdown <= 0;
            if (bang && !explosion.Source.Equals(Entity.Null))
            {
                explosion.Center = positions[explosion.Source].Value;
            }
        }).ScheduleParallel();


        Entities
        .WithName("ExplosionCountdown_Bang")
        .WithBurst()
        .ForEach((int entityInQueryIndex, Entity entity,
                  ref ExplosionCountdown explosion, ref PhysicsVelocity pv,
                  in PhysicsMass pm, in PhysicsCollider collider,
                  in Translation pos, in Rotation rot) =>
        {
            if (0 < explosion.Countdown)
            {
                return;
            }

            pv.ApplyExplosionForce(pm, collider, pos, rot,
                                   explosion.Force, explosion.Center, 0, timeStep, up);

            commandBufferParallel.RemoveComponent <ExplosionCountdown>(entityInQueryIndex, entity);
        }).Schedule();
Ejemplo n.º 11
0
    protected override void OnUpdate()
    {
        var commandBuffer = m_CommandBufferSystem.CreateCommandBuffer();

        // No need to be parallel, as only one entity per explosion cluster
        // shall have ChangeFilterCountdown
        Entities
        .WithName("ChangeFilterCountdown")
        .WithBurst()
        .ForEach((int entityInQueryIndex, ref Entity entity, ref PhysicsCollider collider, ref ChangeFilterCountdown tag) =>
        {
            if (--tag.Countdown > 0)
            {
                return;
            }

            collider.Value.Value.Filter = tag.Filter;
            commandBuffer.RemoveComponent <ChangeFilterCountdown>(entity);
        }).Schedule();
    }
    protected override void OnUpdate()
    {
        Dependency = JobHandle.CombineDependencies(m_TriggerSystem.OutDependency, Dependency);

        var commandBuffer = m_CommandBufferSystem.CreateCommandBuffer();

        // Need this extra variable here so that it can
        // be captured by Entities.ForEach loop below
        var nonTriggerMask = m_NonTriggerMask;

        Entities
        .WithName("ChangeMaterialOnTriggerEnter")
        .WithoutBurst()
        .WithAll <PersistentChangeMaterialOnTriggerTagComponent>()
        .ForEach((Entity e, ref DynamicBuffer <StatefulTriggerEvent> triggerEventBuffer) =>
        {
            for (int i = 0; i < triggerEventBuffer.Length; i++)
            {
                var triggerEvent = triggerEventBuffer[i];
                var otherEntity  = triggerEvent.GetOtherEntity(e);

                // exclude other triggers and processed events
                if (triggerEvent.State == EventOverlapState.Stay || !nonTriggerMask.Matches(otherEntity))
                {
                    continue;
                }

                // l'entity entra nel portale (trigger contatto fra entity dinamica e superficie portale statica)
                if (triggerEvent.State == EventOverlapState.Enter)
                {
                    var volumeRenderMesh           = EntityManager.GetSharedComponentData <RenderMesh>(e);
                    var overlappingRenderMesh      = EntityManager.GetSharedComponentData <RenderMesh>(otherEntity);
                    overlappingRenderMesh.material = volumeRenderMesh.material;

                    commandBuffer.SetSharedComponent(otherEntity, overlappingRenderMesh);
                }
            }
        }).Run();

        m_CommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
        protected override void OnUpdate()
        {
            float spawnTime = (float)Time.ElapsedTime;
            var   ecb       = ecbSystem.CreateCommandBuffer();

            Entities
            .WithName("FixedRateSpawner")
            .ForEach((in FixedRateSpawner spawner) =>
            {
                var projectileEntity = ecb.Instantiate(spawner.Prefab);
                var spawnPos         = spawner.SpawnPos;
                spawnPos.y          += 0.3f * math.sin(5.0f * spawnTime);
                ecb.SetComponent(projectileEntity, new Translation {
                    Value = spawnPos
                });
                ecb.SetComponent(projectileEntity, new Projectile
                {
                    SpawnTime = spawnTime,
                    SpawnPos  = spawnPos,
                });
            }).Schedule();
    protected override void OnUpdate()
    {
        //We need a command buffer because we are making a structural change (adding a DestroyTag)
        var commandBuffer = m_CommandBufferSystem.CreateCommandBuffer();

        //There is a dependency on our "ToEntityArrayAsync" because
        //we are depending on this to get done for us to run our .ForEach()
        JobHandle disconnectNCEsDep;

        //We query for all entities that have a NetworkStreamDisconnected component and save it in a native array
        var disconnectedNCEsNative = m_DisconnectedNCEQuery.ToEntityArrayAsync(Allocator.TempJob, out disconnectNCEsDep);
        //We will need to pull the NetworkIdComponent from these entities within our .ForEach so we
        //declare the local variable now
        var getNetworkIdComponentData = GetComponentDataFromEntity <NetworkIdComponent>();

        //We are going to save the JobHandle required from this .ForEach as "cleanPlayersJob"
        //We pass through our native array as read only, and ask .ForEach to dispose of our array on completion
        var cleanPlayersJob = Entities
                              .WithReadOnly(disconnectedNCEsNative)
                              .WithDisposeOnCompletion(disconnectedNCEsNative)
                              .WithAll <PlayerTag>()
                              .ForEach((Entity entity, in GhostOwnerComponent ghostOwner) => {
            //We navigate through our disconnected NCE's and see if any player entities match
            for (int i = 0; i < disconnectedNCEsNative.Length; i++)
            {
                if (getNetworkIdComponentData[disconnectedNCEsNative[0]].Value == ghostOwner.NetworkId)
                {
                    //If they do match we add a DestroyTag to delete
                    commandBuffer.AddComponent <DestroyTag>(entity);
                }
            }
        }).Schedule(JobHandle.CombineDependencies(Dependency, disconnectNCEsDep));

        //We set our Dependency of this sytem to cleanPlayersJob
        Dependency = cleanPlayersJob;

        //And we add our dependency to our command buffer
        m_CommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
Ejemplo n.º 15
0
        protected override void OnUpdate()
        {
            var ecb = _endFixedECBSystem.CreateCommandBuffer();

            var jobHandle = new SelectionJob
            {
                SelectionVolumes = GetComponentDataFromEntity <SelectionColliderTag>(),
                Units            = GetComponentDataFromEntity <SelectableUnitTag>(),
                ECB = ecb
            }.Schedule(_stepPhysicsWorld.Simulation, ref _buildPhysicsWorld.PhysicsWorld, Dependency);

            jobHandle.Complete();

            var selectionEntities = _activeSelectionQuery.ToEntityArray(Allocator.Temp);

            foreach (var selectionEntity in selectionEntities)
            {
                if (HasComponent <FramesToLiveData>(selectionEntity))
                {
                    var deletionData = GetComponent <FramesToLiveData>(selectionEntity);
                    deletionData.Value--;
                    ecb.SetComponent(selectionEntity, deletionData);
                    if (deletionData.Value <= 0)
                    {
                        ecb.AddComponent <DeleteEntityTag>(selectionEntity);
                    }
                }
                else
                {
                    ecb.AddComponent <FramesToLiveData>(selectionEntity);
                    ecb.SetComponent(selectionEntity, new FramesToLiveData {
                        Value = 1
                    });
                }
            }

            selectionEntities.Dispose();
        }
Ejemplo n.º 16
0
    protected unsafe override void OnUpdate()
    {
        var _physicsWorldSystem = World.DefaultGameObjectInjectionWorld.GetExistingSystem <Unity.Physics.Systems.BuildPhysicsWorld>();
        var _collisionWorld     = _physicsWorldSystem.PhysicsWorld.CollisionWorld;

        var _ecb = m_EntityCommandBufferSystem.CreateCommandBuffer();

        var _filter = new CollisionFilter()
        {
            BelongsTo    = ~0u,
            CollidesWith = ~0u, // all 1s, so all layers, collide with everything
            GroupIndex   = 0
        };

        SphereGeometry sphereGeometry = new SphereGeometry()
        {
            Center = float3.zero, Radius = 100
        };
        BlobAssetReference <Unity.Physics.Collider> sphereCollider = Unity.Physics.SphereCollider.Create(sphereGeometry, _filter);

        /*Vector3
         * Unity.Physics.ColliderCastInput input = new Unity.Physics.ColliderCastInput()
         * {
         *  Collider = (Unity.Physics.Collider*)sphereCollider.GetUnsafePtr(),
         *  Orientation = quaternion.identity,
         *  Start = RayFrom,
         *  End = RayTo
         * };*/

        /*Entities.
         *  ForEach((ref Translation _translation, in Entity _entity) =>
         *  {
         *      _ecb.AddComponent(_entity, new UnitSelected());
         *
         *  }).Schedule();*/
    }
Ejemplo n.º 17
0
    protected unsafe override void OnUpdate()
    {
        var _ecb                  = m_EntityCommandBufferSystem.CreateCommandBuffer();
        var _ecbo                 = m_EntityCommandBufferSystemo.CreateCommandBuffer();
        var _ecbEndSimilation     = m_endSimulationEntityCommandBufferSystem.CreateCommandBuffer();
        var _ecbBeginPresentation = m_beginPresentationEntityCommandBufferSystem.CreateCommandBuffer();

        var            _physicsWorldSystem = World.DefaultGameObjectInjectionWorld.GetExistingSystem <Unity.Physics.Systems.BuildPhysicsWorld>();
        CollisionWorld _collisionWorld     = _physicsWorldSystem.PhysicsWorld.CollisionWorld;
        var            _physicsWorld       = _physicsWorldSystem.PhysicsWorld;

        float3 _startPosition      = ECS_RTSControls.instance._startScreenPosition;
        float3 _endPosition        = ECS_RTSControls.instance._endScreenPosition;
        float3 _lowerLeftPosition  = ECS_RTSControls.instance._lowerLeftScreenPosition;
        float3 _upperRightPosition = ECS_RTSControls.instance._upperRightScreenPosition;

        Dependency = JobHandle.CombineDependencies(Dependency, m_EndFramePhysicsSystem.GetOutputDependency());

        if (_inputReady)
        {
            if (Input_Mouse_0_Up == true && Input_Mouse_0_Up != EntityManager.HasComponent <Input_Mouse_0_Up>(_inputEntity))
            {
                Input_Mouse_0_GetDown = true;
                Input_Mouse_0_Up      = false;
            }

            if (Input_Mouse_0_Up == false && (Input_Mouse_0_Up != EntityManager.HasComponent <Input_Mouse_0_Up>(_inputEntity)))
            {
                Input_Mouse_0_GetUp = true;
                Input_Mouse_0_Up    = true;
            }

            if (Input_Mouse_1_Up == true && (Input_Mouse_1_Up != EntityManager.HasComponent <Input_Mouse_1_Up>(_inputEntity)))
            {
                Input_Mouse_1_GetDown = true;
                Input_Mouse_1_Up      = false;
            }
            if (Input_Mouse_1_Up == false && (Input_Mouse_1_Up != EntityManager.HasComponent <Input_Mouse_1_Up>(_inputEntity)))
            {
                Input_Mouse_1_GetUp = true;
                Input_Mouse_1_Up    = true;
            }
        }
        else
        {
            if (_queryInput.CalculateEntityCount() > 0)
            {
                _inputEntity     = _queryInput.GetSingletonEntity();
                _inputReady      = true;
                Input_Mouse_0_Up = EntityManager.HasComponent <Input_Mouse_0_Up>(_inputEntity);
                Input_Mouse_1_Up = EntityManager.HasComponent <Input_Mouse_1_Up>(_inputEntity);
            }
        }

        if (Time.ElapsedTime > 4)
        {
            /*this.Dependency =  Entities.WithoutBurst().ForEach((in Translation _translation, in UnitSelected _unitSelected, in Selectable _selectable, in GrisTag _grisTag, in Entity _entity) =>
             * {
             *   var e = _ecbEndSimilation.Instantiate(PrefabConvert._DalleVerte);
             *   _ecbEndSimilation.SetComponent<Translation>(e, _translation);
             *   _ecbEndSimilation.DestroyEntity(_entity);
             *   Debug.Log("Unity3d : 'va te faire foutre'");
             *
             * }).Schedule(this.Dependency);*/
        }

        if (Input_Mouse_0_GetUp == true)
        {
            bool  selectOnlyOneEntity  = false;
            float selectionAreaMinSize = 10f;
            float selectionAreaSize    = math.distance(_lowerLeftPosition, _upperRightPosition);
            if (selectionAreaSize < selectionAreaMinSize)
            {
                // Selection area too small
                _lowerLeftPosition  += new float3(-1, -1, 0) * (selectionAreaMinSize - selectionAreaSize) * .5f;
                _upperRightPosition += new float3(+1, +1, 0) * (selectionAreaMinSize - selectionAreaSize) * .5f;
                selectOnlyOneEntity  = true;
            }

            // Deselect all selected Entities
            this.Dependency = Entities.WithAll <UnitSelected>().ForEach((Entity entity) => {
                _ecb.RemoveComponent <UnitSelected>(entity);
            }).Schedule(this.Dependency);



            Unity.Physics.RaycastHit _hit1 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit2 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit3 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit4 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit5 = new Unity.Physics.RaycastHit();

            var _ray1 = ECS_RTSControls.instance._ray1;
            var _ray2 = ECS_RTSControls.instance._ray2;
            var _ray3 = ECS_RTSControls.instance._ray3;
            var _ray4 = ECS_RTSControls.instance._ray4;
            var _ray5 = ECS_RTSControls.instance._ray5;

            /*RaycastInput _inputo = new RaycastInput()
             * {
             *  Start = _ray1.origin,
             *  End = _ray1.origin + _ray1.direction * 1000,
             *  Filter = new CollisionFilter()
             *  {
             *      BelongsTo = (uint)10 << 10,
             *      CollidesWith = (uint)7 << 8,
             *      GroupIndex = 8
             *  }
             * };*/

            GetRaycastHit(_collisionWorld, _ray1, _ray2, _ray3, _ray4, _ray5, out _hit1, out _hit2, out _hit3, out _hit4, out _hit5);


            var _filter = new CollisionFilter()
            {
                BelongsTo    = ~1u,
                CollidesWith = ~1u, // all 1s, so all layers, collide with everything
                GroupIndex   = 0
            };

            NativeList <ColliderCastHit> _allHits = new NativeList <ColliderCastHit>(Allocator.TempJob);


            _polygonCollider = Unity.Physics.PolygonCollider.CreateQuad(_hit1.Position, _hit2.Position, _hit3.Position, _hit4.Position, _filter);

            /*SphereGeometry sphereGeometry = new SphereGeometry() { Center = float3.zero, Radius = 3 };
             * _sphereCollider = Unity.Physics.SphereCollider.Create(sphereGeometry, _filter);*/
            /*
             * Unity.Physics.ColliderCastInput colliderCastInput = new ColliderCastInput()
             * {
             *  Collider = (Unity.Physics.Collider*)_sphereCollider.GetUnsafePtr(),
             *  Orientation = ECS_RTSControls.instance._camera.transform.rotation,
             *  Start = ECS_RTSControls.instance._camera.transform.position,
             *  End = _ray1.origin + _ray1.direction * 1000
             * };*/
            var _moyPoly = new float3((_hit1.Position.x + _hit2.Position.x + _hit3.Position.x + _hit4.Position.x) / 4,
                                      (_hit1.Position.y + _hit2.Position.y + _hit3.Position.y + _hit4.Position.y) / 4,
                                      (_hit1.Position.z + _hit2.Position.z + _hit3.Position.z + _hit4.Position.z) / 4);



            Debug.Log(_moyPoly + "_moyPoly");

            //var  _pouitCollider = BlobAssetReference<Unity.Physics.Collider>.Create(_polygonCollider.GetUnsafePtr(), 1);

            /* this.Dependency = Job.WithoutBurst().WithCode(() =>
             * {
             *   var e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit1.Position + new float3(0, 5, 0) });
             *   e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit2.Position + new float3(0, 5, 0) });
             *   e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit3.Position + new float3(0, 5, 0) });
             *   e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit4.Position + new float3(0, 5, 0) });
             * }).Schedule(this.Dependency);
             * Debug.Log(_dalleSelectedQuery.CalculateEntityCount() + "_dalleSelectedQueryCount");
             * Debug.Log(_dalleQuery.CalculateEntityCount() + "_dalleQueryCount");
             *
             * /*Mesh _mesh = new Mesh { }
             *
             * RenderMesh huiaef = new RenderMesh { mesh = }
             *
             * this.Dependency.Complete();*/

            ColliderCastJob _colliderCastJob = new ColliderCastJob();
            _colliderCastJob.CollectAllHits   = true;
            _colliderCastJob.Collider         = (Unity.Physics.Collider *)_polygonCollider.GetUnsafePtr();
            _colliderCastJob.ColliderCastHits = _allHits;
            _colliderCastJob.End         = new float3(0, -2, 0); // _moyPoly;
            _colliderCastJob.Orientation = quaternion.identity;  //ECS_RTSControls.instance._camera.transform.rotation;
            _colliderCastJob.Start       = /*_moyPoly +*/ new float3(0, 5, 0);
            _colliderCastJob.World       = _physicsWorld;
            Dependency = _colliderCastJob.ScheduleSingle(_query, this.Dependency);

            //World.GetOrCreateSystem<StepPhysicsWorld>().FinalSimulationJobHandle.Complete();

            this.Dependency.Complete();

            /*Debug.Log(_query.CalculateEntityCount() + "_queryMovestats");
             * Debug.Log(_allHits.Length + "_allHits.Length");*/
            this.Dependency = Job.WithoutBurst().WithDisposeOnCompletion(_allHits).WithCode(() =>
            {
                for (int i = 0; i < _allHits.Length; i++)
                {
                    _ecbEndSimilation.AddComponent(_allHits[i].Entity, new UnitSelected());
                }

                Debug.Log(_allHits.Length + "entityHits");
            }).Schedule(this.Dependency);

            this.Dependency.Complete();
        }

        if (Input_Mouse_1_Up == false)
        {
            if (Time.ElapsedTime > 2)
            {
                Debug.Log("yoloZoulou");
                this.Dependency = Entities.WithoutBurst().WithAll <PlaneLayer>().WithAll <Player1>().ForEach((Entity entity) => {
                    _ecb.DestroyEntity(entity);//.RemoveComponent<UnitSelected>(entity);
                }).Schedule(this.Dependency);
            }

            //Debug.Log(Input.GetMouseButtonDown(1));
            // Right mouse button down
            float3        targetPosition   = UtilsClass.GetMouseWorldPosition();
            List <float3> movePositionList = GetPositionListAround(targetPosition, new float[] { 10f, 20f, 30f }, new int[] { 5, 10, 20 });
            int           positionIndex    = 0;
            Entities.WithAll <UnitSelected>().ForEach((Entity entity, ref MoveStats _moveStats) => {
                /*moveTo.position = movePositionList[positionIndex];
                 * positionIndex = (positionIndex + 1) % movePositionList.Count;
                 * moveTo.move = true;*/
            }).Schedule();
        }
        //m_EntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
        World.GetOrCreateSystem <StepPhysicsWorld>().FinalSimulationJobHandle.Complete();
        this.Dependency.Complete();
        m_EntityCommandBufferSystemo.AddJobHandleForProducer(this.Dependency);
        m_endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
        m_EntityCommandBufferSystemo.AddJobHandleForProducer(this.Dependency);

        if (_polygonCollider.IsCreated)
        {
            _polygonCollider.Dispose();
        }
        if (_sphereCollider.IsCreated)
        {
            _sphereCollider.Dispose();
        }
        Input_Mouse_0_GetUp   = false;
        Input_Mouse_0_GetDown = false;
    }