Esempio n. 1
0
        protected override void OnUpdate()
        {
            var disconnectData = group.GetSharedComponentDataArray <OnDisconnected>();

            Debug.LogWarningFormat("Disconnected from SpatialOS with reason: \"{0}\"",
                                   disconnectData[0].ReasonForDisconnect);
        }
Esempio n. 2
0
    protected override void OnUpdate()
    {
        if (flag)
        {
            return;
        }

        flag = true;

        ComponentGroup planetGroup = GetComponentGroup(typeof(Planet), typeof(PlanetNoise));
        ComponentGroup dataGroup   = GetComponentGroup(typeof(PlanetSharedData));

        ComponentDataArray <Planet>                 planetArray = planetGroup.GetComponentDataArray <Planet>();
        ComponentDataArray <PlanetNoise>            noiseArray  = planetGroup.GetComponentDataArray <PlanetNoise>();
        SharedComponentDataArray <PlanetSharedData> dataArray   = dataGroup.GetSharedComponentDataArray <PlanetSharedData>();

        GameObject prefab = dataArray[0].nodePrefab;

        for (int i = 0; i < planetArray.Length; ++i)
        {
            Planet        planet = planetArray[i];
            PlanetNoise   noise  = noiseArray[i];
            HyperDistance r      = planet.radius;

            for (int n = 0; n < 20; ++n)
            {
                Entity      nodeEntity = EntityManager.Instantiate(prefab);
                TerrainNode node       = EntityManager.GetComponentData <TerrainNode>(nodeEntity);
                node.level        = 0;
                node.planetData   = planet;
                node.noiseData    = noise;
                node.built        = 0;
                node.divided      = 0;
                node.hyperDistant = 1;

                int idx = n * 3;
                node.corner1 = icoVerts[idx];
                node.corner2 = icoVerts[idx + 1];
                node.corner3 = icoVerts[idx + 2];
                EntityManager.SetComponentData(nodeEntity, node);

                HyperPosition pos = math.normalize(node.corner1 + node.corner2 + node.corner3) * r;

                PrecisePosition prspos = new PrecisePosition {
                    pos = pos.prs
                };
                EntityManager.SetComponentData(nodeEntity, prspos);

                OctantPosition octpos = new OctantPosition {
                    pos = pos.oct
                };
                EntityManager.SetComponentData(nodeEntity, octpos);
            }
        }
    }
Esempio n. 3
0
        protected override void OnUpdate()
        {
            transformGroup.SetFilter(TransformInternal.ComponentAuthority.Authoritative);

            var rateLimitedConfigArray    = transformGroup.GetSharedComponentDataArray <RateLimitedSendConfig>();
            var transformArray            = transformGroup.GetComponentDataArray <TransformInternal.Component>();
            var transformToSendArray      = transformGroup.GetComponentDataArray <TransformToSend>();
            var lastTransformSentArray    = transformGroup.GetComponentDataArray <LastTransformSentData>();
            var ticksSinceLastUpdateArray = transformGroup.GetComponentDataArray <TicksSinceLastTransformUpdate>();

            for (int i = 0; i < transformArray.Length; ++i)
            {
                var lastTransformSent = lastTransformSentArray[i];
                lastTransformSent.TimeSinceLastUpdate += Time.deltaTime;
                lastTransformSentArray[i]              = lastTransformSent;

                if (lastTransformSent.TimeSinceLastUpdate <
                    1.0f / rateLimitedConfigArray[i].MaxTransformUpdateRateHz)
                {
                    continue;
                }

                var transform = transformArray[i];

                var transformToSend = transformToSendArray[i];

                var currentTransform = new TransformInternal.Component
                {
                    Location       = (transformToSend.Position - worker.Origin).ToImprobableLocation(),
                    Rotation       = transformToSend.Orientation.ToImprobableQuaternion(),
                    Velocity       = transformToSend.Velocity.ToImprobableVelocity(),
                    PhysicsTick    = transform.PhysicsTick + ticksSinceLastUpdateArray[i].NumberOfTicks,
                    TicksPerSecond = tickRate.PhysicsTicksPerRealSecond
                };

                if (!(TransformUtils.HasChanged(currentTransform.Location, transform.Location) ||
                      TransformUtils.HasChanged(currentTransform.Rotation, transform.Rotation)))
                {
                    continue;
                }

                lastTransformSent.TimeSinceLastUpdate = 0.0f;
                lastTransformSent.Transform           = transform;
                lastTransformSentArray[i]             = lastTransformSent;

                transformArray[i] = currentTransform;

                ticksSinceLastUpdateArray[i] = new TicksSinceLastTransformUpdate
                {
                    NumberOfTicks = 0
                };
            }
        }
            protected override JobHandle OnUpdate(JobHandle inputDeps)
            {
                var job = new SteeringJob()
                {
                    Positions      = group.GetComponentDataArray <Position>(),
                    Movements      = group.GetComponentDataArray <MovementData>(),
                    SharedSteering = group.GetSharedComponentDataArray <SteeringSharedData>()[0],
                    Steerings      = group.GetComponentDataArray <SteeringData>()
                };

                return(job.Schedule(group.GetComponentDataArray <SteeringData>().Length, 16, inputDeps));
            }
        protected override void OnUpdate()
        {
            var disconnectData = group.GetSharedComponentDataArray <OnDisconnected>();

            if (disconnectData.Length != 1)
            {
                worker.LogDispatcher.HandleLog(LogType.Error,
                                               new LogEvent($"{typeof(WorkerEntityTag)} should only be present on a single entity"));
            }

            OnDisconnected?.Invoke(disconnectData[0].ReasonForDisconnect);
        }
        private JobHandle ScheduleMembershipDebugJob(JobHandle inputDeps)
        {
            var handle = inputDeps;
            var length = _membershipDebugGroup.CalculateLength();

            if (length > 0)
            {
                handle = new MembershipDebugJob
                {
                    EntityArray   = _membershipDebugGroup.GetEntityArray(),
                    PhysicsObject = _membershipDebugGroup.GetSharedComponentDataArray <PhysicsObject>()[0]
                }.Schedule(length, 64, inputDeps);
            }
            return(handle);
        }
Esempio n. 7
0
 public void Initialize(
     ComponentGroup group,
     UnityEngine.Vector3 [] vertices,
     UnityEngine.Vector3 [] normals,
     NativeCounter.Concurrent counter
     )
 {
     Particles = group.GetComponentDataArray <Particle>();
     Positions = group.GetComponentDataArray <Position>();
     Triangles = group.GetComponentDataArray <Triangle>();
     Variants  = group.GetSharedComponentDataArray <SimpleParticle>();
     Vertices  = UnsafeUtility.AddressOf(ref vertices[0]);
     Normals   = UnsafeUtility.AddressOf(ref normals[0]);
     Counter   = counter;
 }
Esempio n. 8
0
        protected override void OnUpdate()
        {
            var source = group.GetComponentDataArray <CountData>();
            var range  = group.GetSharedComponentDataArray <RangeData>();

            for (int i = 0; i < source.Length; i++)
            {
                var countData = source[i];
                if (range[i].max < countData.count)
                {
                    countData.count = range[i].min;
                    source[i]       = countData;
                }
            }
        }
        protected override void OnUpdate()
        {
            var sharedComponents = m_MissingRenderBounds.GetSharedComponentDataArray <RenderMesh>();
            var entities         = m_MissingRenderBounds.GetEntityArray();

            for (int i = 0; i != sharedComponents.Length; i++)
            {
                var meshRenderer = sharedComponents[i];
                if (meshRenderer.mesh != null)
                {
                    PostUpdateCommands.AddComponent(entities[i], new RenderBounds {
                        Value = meshRenderer.mesh.bounds
                    });
                }
            }
        }
Esempio n. 10
0
        protected override void OnUpdate()
        {
            var sprites = group.GetComponentDataArray <AnimationSpriteData>();
            var anims   = group.GetSharedComponentDataArray <AnimationData>();

            float delta = UnityEngine.Time.deltaTime;

            for (int i = 0; i < sprites.Length; i++)
            {
                AnimationSpriteData sprite = sprites[i];
                AnimationData       anim   = anims[i];

                Process(ref sprite, ref anim, delta);

                sprites[i] = sprite;
            }
        }
        protected override void OnUpdate()
        {
            //TODO m_Group.SetFilter(new STNetworkEntityProperty() { IsControllable = true }); //< we only want to process controllable entities

            var entityInputs      = m_Group.GetComponentDataArray <STDefault_EntityInput>();
            var networkProperties = m_Group.GetSharedComponentDataArray <NetworkEntity>();

            for (int i = 0; i < entityInputs.Length; i++)
            {
                var entityInput = entityInputs[i];

                entityInput.Direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
                entityInput.SpaceKey  = new STInputKey(Input.GetButtonDown("Jump"), Input.GetButtonUp("Jump"), Input.GetButton("Jump"));
                //entityInput.ShiftKey = new STInputKey(Input.GetButtonDown("Sprint"), Input.GetButtonUp("Sprint"), Input.GetButton("Sprint"));

                entityInputs[i] = entityInput;
            }
        }
Esempio n. 12
0
        protected override void OnUpdate()
        {
            m_Group.SetFilter(new NetworkEntity()
            {
                IsLocal = true
            });
            var networkComponents = m_Group.GetSharedComponentDataArray <NetworkEntity>();
            var inputComponents   = m_Group.GetComponentDataArray <FreeMovementInputReceiver>();

            for (int i = 0; i != networkComponents.Length; i++)
            {
                var netComponent   = networkComponents[i];
                var inputComponent = inputComponents[i];

                if (netComponent.LocalControlId == 0) //< We only work with the first player for now
                {
                }
            }
        }
        protected override void OnUpdate()
        {
            positionGroup.SetFilter(Position.ComponentAuthority.Authoritative);

            var rateLimitedConfigArray = positionGroup.GetSharedComponentDataArray <RateLimitedSendConfig>();
            var positionArray          = positionGroup.GetComponentDataArray <Position.Component>();
            var transformArray         = positionGroup.GetComponentDataArray <TransformInternal.Component>();
            var lastSentPositionArray  = positionGroup.GetComponentDataArray <LastPositionSentData>();

            for (int i = 0; i < positionArray.Length; ++i)
            {
                var position = positionArray[i];

                var lastPositionSent = lastSentPositionArray[i];
                lastPositionSent.TimeSinceLastUpdate += Time.deltaTime;
                lastSentPositionArray[i]              = lastPositionSent;

                if (lastPositionSent.TimeSinceLastUpdate <
                    1.0f / rateLimitedConfigArray[i].MaxPositionUpdateRateHz)
                {
                    continue;
                }

                var transform = transformArray[i];

                var coords = transform.Location.ToCoordinates();

                if (!TransformUtils.HasChanged(coords, position.Coords))
                {
                    continue;
                }

                position.Coords  = coords;
                positionArray[i] = position;

                lastPositionSent.TimeSinceLastUpdate = 0.0f;
                lastPositionSent.Position            = position;
                lastSentPositionArray[i]             = lastPositionSent;
            }
        }
Esempio n. 14
0
        protected virtual void OnRender(ref int[] sort)
        {
            var sprites = group.GetComponentDataArray <AnimationSpriteData>();
            var pos     = group.GetComponentDataArray <PositionData>();
            var meshes  = group.GetSharedComponentDataArray <SpriteMeshesData>();

            cmd.Clear();


            cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, UnityEngine.GL.GetGPUProjectionMatrix(camera.projectionMatrix, false));

            //for(int i=0; i<sprites.Length; i++)
            for (int indx = 0; indx < sort.Length; indx++)
            {
                int i = sort[indx];
                AnimationSpriteData sprite   = sprites[i];
                PositionData        position = pos[i];
                SpriteMeshesData    mesh     = meshes[i];

                cmd.DrawMesh(mesh.Meshes[sprite.spriteIndx], UnityEngine.Matrix4x4.Translate(position.Value), material);
            }
        }
Esempio n. 15
0
        protected override void OnUpdate()
        {
            var collisionPositions = _targetsComponentGroup.GetComponentDataArray <Position>();
            var collisions         = _targetsComponentGroup.GetSharedComponentDataArray <Collision>();
            var entities           = _targetsComponentGroup.GetEntityArray();
            var explosions         = new NativeList <Position>(Allocator.Temp);

            for (var i = 0; i < _group.Length; i++)
            {
                var bulletPosition  = _group.Positions[i];
                var bulletCollision = _group.Collisions[i];
                if (CheckBulletCollision(_group.Entites[i], bulletPosition, bulletCollision,
                                         collisionPositions, collisions, entities))
                {
                    explosions.Add(bulletPosition);
                }
            }

            for (var i = 0; i < explosions.Length; i++)
            {
                CreateExplosion(explosions[i].Value);
            }
            explosions.Dispose();
        }
Esempio n. 16
0
            protected override JobHandle OnUpdate(JobHandle inputDeps)
            {
                if (groupToInit.GetEntityArray().Length == 0)
                {
                    return(inputDeps);
                }
                var sharedIdxs = new List <SharedComponentIndexToAddComponentData>(20);

                EntityManager.GetAllUniqueSharedComponentData(sharedIdxs);
                for (int i = 0, length = sharedIdxs.Count; i < length; ++i)
                {
                    var sharedIdx = sharedIdxs[i];
                    groupToInit.SetFilter(sharedIdx);
                    if (groupToInit.GetEntityArray().Length == 0)
                    {
                        continue;
                    }
                    var entities      = new NativeArray <Entity>(groupToInit.GetEntityArray().ToArray(), Allocator.TempJob);
                    var neuralNetwork = neuralNetworkGroup.GetSharedComponentDataArray <NeuralNetworkComponentData>()[sharedIdx.Index];
                    var inputCount    = neuralNetwork.PerceptronPerLayerCount[0];


                    neuralNetwork.Inputs = new NativeArray <float>(inputCount * entities.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
                    int perceptronCount = inputCount, connectionCount = 0, previousCount = perceptronCount;
                    for (int j = 1, length2 = neuralNetwork.PerceptronPerLayerCount.Length; j < length2; ++j)
                    {
                        int perceptronPerLayer = neuralNetwork.PerceptronPerLayerCount[j];
                        connectionCount += previousCount * perceptronPerLayer;
                        perceptronCount += perceptronPerLayer;
                        previousCount    = perceptronPerLayer;
                    }
                    neuralNetwork.ConnectionCountPerNetwork = connectionCount;
                    neuralNetwork.PerceptronCountPerNetwork = perceptronCount;
                    neuralNetwork.ResultCountPerNetwork     = perceptronCount - inputCount;
                    neuralNetwork.PerceptronCount           = (perceptronCount * entities.Length);
                    neuralNetwork.Results     = new NativeArray <float>((perceptronCount * entities.Length) - (inputCount * entities.Length), Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
                    neuralNetwork.Connections = new NativeArray <float>(connectionCount * entities.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
                    var randomNumbers = new NativeList <float>(connectionCount * entities.Length, Allocator.TempJob);
                    for (int j = 0, count = connectionCount * entities.Length; j < count; ++j)
                    {
                        randomNumbers.Add(UnityEngine.Random.Range(-neuralNetwork.WeightRange, neuralNetwork.WeightRange));
                    }

                    var job = new InitConnection {
                        PerceptronPerLayer   = neuralNetwork.PerceptronPerLayerCount,
                        Connections          = neuralNetwork.Connections,
                        RandomNumbers        = randomNumbers,
                        ConnectionPerNetwork = connectionCount
                    };
                    var handle = job.ScheduleBatch(perceptronCount * entities.Length, perceptronCount, inputDeps);

                    JobHandle.ScheduleBatchedJobs();

                    handle.Complete();

                    for (int j = 0, entityCount = entities.Length; j < entityCount; ++j)
                    {
                        var entity = entities[j];
                        EntityManager.AddSharedComponentData(entity, neuralNetwork);
                        EntityManager.AddComponentData(entity, new InitializedComponentData());
                        EntityManager.RemoveComponent <SharedComponentIndexToAddComponentData>(entity);
                        EntityManager.RemoveComponent <InitializeNeuralNetworkComponentData>(entity);
                    }

                    randomNumbers.Dispose();
                    entities.Dispose();
                }
                return(inputDeps);
            }
Esempio n. 17
0
        protected override void OnUpdate()
        {
            interpolationGroup.SetFilter(TransformInternal.ComponentAuthority.NotAuthoritative);

            var interpolationConfigArray = interpolationGroup.GetSharedComponentDataArray <InterpolationConfig>();
            var bufferedTransformArray   = interpolationGroup.GetBufferArray <BufferedTransform>();
            var spatialEntityIdArray     = interpolationGroup.GetComponentDataArray <SpatialEntityId>();
            var transformComponentArray  = interpolationGroup.GetComponentDataArray <TransformInternal.Component>();
            var lastTransformArray       = interpolationGroup.GetComponentDataArray <DeferredUpdateTransform>();

            for (int i = 0; i < transformComponentArray.Length; ++i)
            {
                var config               = interpolationConfigArray[i];
                var transformBuffer      = bufferedTransformArray[i];
                var lastTransformApplied = lastTransformArray[i].Transform;

                if (transformBuffer.Length >= config.MaxLoadMatchedBufferSize)
                {
                    transformBuffer.Clear();
                }

                if (transformBuffer.Length == 0)
                {
                    var currentTransformComponent = transformComponentArray[i];
                    if (currentTransformComponent.PhysicsTick <= lastTransformApplied.PhysicsTick)
                    {
                        continue;
                    }

                    lastTransformArray[i] = new DeferredUpdateTransform
                    {
                        Transform = currentTransformComponent
                    };

                    var transformToInterpolateTo = ToBufferedTransform(currentTransformComponent);

                    uint ticksToFill = math.max((uint)config.TargetBufferSize, 1);

                    if (ticksToFill > 1)
                    {
                        var transformToInterpolateFrom = ToBufferedTransformAtTick(lastTransformApplied,
                                                                                   transformToInterpolateTo.PhysicsTick - ticksToFill + 1);

                        transformBuffer.Add(transformToInterpolateFrom);

                        for (uint j = 0; j < ticksToFill - 2; ++j)
                        {
                            transformBuffer.Add(InterpolateValues(transformToInterpolateFrom, transformToInterpolateTo,
                                                                  j + 1));
                        }
                    }

                    transformBuffer.Add(transformToInterpolateTo);
                    continue;
                }

                var updates =
                    updateSystem
                    .GetEntityComponentUpdatesReceived <TransformInternal.Update>(spatialEntityIdArray[i].EntityId);

                for (int j = 0; j < updates.Count; ++j)
                {
                    var update = updates[j].Update;
                    UpdateLastTransform(ref lastTransformApplied, update);
                    lastTransformArray[i] = new DeferredUpdateTransform
                    {
                        Transform = lastTransformApplied
                    };

                    if (!update.PhysicsTick.HasValue)
                    {
                        continue;
                    }

                    var transformToInterpolateTo = ToBufferedTransform(lastTransformApplied);

                    var  transformToInterpolateFrom = transformBuffer[transformBuffer.Length - 1];
                    uint lastTickId = transformToInterpolateFrom.PhysicsTick;

                    // This could go backwards if authority changes quickly between two workers with different loads
                    if (lastTickId >= transformToInterpolateTo.PhysicsTick)
                    {
                        continue;
                    }

                    uint ticksToFill = math.max(transformToInterpolateTo.PhysicsTick - lastTickId, 1);

                    for (uint k = 0; k < ticksToFill - 1; ++k)
                    {
                        transformBuffer.Add(InterpolateValues(transformToInterpolateFrom, transformToInterpolateTo,
                                                              k + 1));
                    }

                    transformBuffer.Add(transformToInterpolateTo);
                }
            }
        }
Esempio n. 18
0
    private JobHandle ScheduleCounting(JobHandle inputDeps)
    {
        switch (_config.Method)
        {
        case TestMethod.InstancedByteComponent:
            if (_config.InterestingStateCount == 1)
            {
                return(new CountSpecificInstancedByteStateJob
                {
                    Components = _groupWithInstancedByteComponent.Components,
                    StateToCheckFor = 0
                }.Schedule(_groupWithInstancedByteComponent.Length, 64, inputDeps));
            }
            else
            {
                FillStatesToCheckFor();
                return(new CountMultipleInstancedByteStatesJob
                {
                    Components = _groupWithInstancedByteComponent.Components,
                    StatesToCheckFor = _statesToCheckFor
                }.Schedule(_groupWithInstancedByteComponent.Length, 64, inputDeps));
            }

        case TestMethod.AddRemoveInstancedComponent:
            return(new CountExistingComponentsJob
            {
            }.Schedule(_groupWithInstancedBinaryComponent.Length, 64, inputDeps));

        case TestMethod.AddRemoveSharedComponent:
            return(new CountExistingComponentsJob
            {
            }.Schedule(_groupWithSharedBinaryComponent.Length, 64, inputDeps));

        case TestMethod.SetValueSharedComponentForEachFilter:
            var uniques = new List <SharedByteState>();
            EntityManager.GetAllUniqueSharedComponentDatas(uniques);
            var filter = _byteStateGroup.CreateForEachFilter(uniques);
            for (int i = 0; i < filter.Length; i++)
            {
                if (_config.InterestingStateCount > uniques[i].State)
                {
                    var interestingCount = _byteStateGroup.GetEntityArray(filter, i).Length;
                    var forEachHandle    = new CountExistingComponentsJob
                    {
                    }.Schedule(interestingCount, 64, inputDeps);
                    filter.Dispose();
                    return(forEachHandle);
                }
            }
            filter.Dispose();
            return(inputDeps);

        case TestMethod.SetValueSharedComponentSetFilter:
            if (_config.InterestingStateCount == 1)
            {
                var handle = ScheduleCountForFilterWithState(0, inputDeps);
                _byteStateGroup.ResetFilter();
                return(handle);
            }
            else
            {
                var filterHandles = new NativeList <JobHandle>(_config.InterestingStateCount, Allocator.Temp);
                for (int i = 0; i < _config.InterestingStateCount; i++)
                {
                    filterHandles.Add(ScheduleCountForFilterWithState(i, inputDeps));
                }
                var combinedFilterHandles = JobHandle.CombineDependencies(filterHandles);
                _byteStateGroup.ResetFilter();
                filterHandles.Dispose();
            }
            return(inputDeps);

        case TestMethod.SetValueSharedComponentNoFilter:
            var length = _byteStateGroup.CalculateLength();
            if (length > 0)
            {
                if (_config.InterestingStateCount == 1)
                {
                    return(new CountSpecificSharedByteStateJob
                    {
                        Components = _byteStateGroup.GetSharedComponentDataArray <SharedByteState>(),
                        StateToCheckFor = 0
                    }.Schedule(length, 64, inputDeps));
                }
                else
                {
                    FillStatesToCheckFor();
                    return(new CountMultipleSharedByteStatesJob
                    {
                        Components = _byteStateGroup.GetSharedComponentDataArray <SharedByteState>(),
                        StatesToCheckFor = _statesToCheckFor
                    }.Schedule(length, 64, inputDeps));
                }
            }
            return(inputDeps);

        default:
            return(inputDeps);
        }
    }
Esempio n. 19
0
    protected override void OnUpdate()
    {
        for (int i = meshCreationSets.Count - 1; i >= 0; --i)
        {
            if (meshCreationSets[i].jobHandle.IsCompleted)
            {
                meshCreationSets[i].jobHandle.Complete();

                if (EntityManager.Exists(meshCreationSets[i].entity))
                {
                    Mesh mesh = new Mesh();

                    mesh.vertices  = meshCreationSets[i].verts.ToArray();
                    mesh.triangles = meshCreationSets[i].tris.ToArray();
                    mesh.RecalculateNormals();

                    HPMeshInstanceRenderer r = EntityManager.GetSharedComponentData <HPMeshInstanceRenderer>(meshCreationSets[i].entity);

                    r.mesh = mesh;

                    EntityManager.SetSharedComponentData(meshCreationSets[i].entity, r);

                    TerrainNode node = EntityManager.GetComponentData <TerrainNode>(meshCreationSets[i].entity);

                    if (node.level != 0 && EntityManager.Exists(node.parentEntity))
                    {
                        TerrainNode parentNode = EntityManager.GetComponentData <TerrainNode>(node.parentEntity);

                        if (parentNode.divided == 1)
                        {
                            ++parentNode.childrenBuilt;
                            if (parentNode.childrenBuilt == 4)
                            {
                                HPMeshInstanceRenderer parentR = EntityManager.GetSharedComponentData <HPMeshInstanceRenderer>(node.parentEntity);
                                parentR.mesh = null;
                                EntityManager.SetSharedComponentData(node.parentEntity, parentR);
                            }

                            EntityManager.SetComponentData(node.parentEntity, parentNode);
                        }
                    }
                }

                meshCreationSets[i].verts.Dispose();
                meshCreationSets[i].tris.Dispose();

                meshCreationSets.RemoveAt(i);
            }
        }



        ComponentGroup nodeGroup = GetComponentGroup(typeof(TerrainNode), typeof(HPMeshInstanceRenderer), typeof(PrecisePosition), typeof(OctantPosition));
        ComponentGroup camGroup  = GetComponentGroup(typeof(Flycam), typeof(PrecisePosition), typeof(Rotation), typeof(OctantPosition));
        ComponentGroup dataGroup = GetComponentGroup(typeof(PlanetSharedData));

        SharedComponentDataArray <PlanetSharedData> planetDataArray = dataGroup.GetSharedComponentDataArray <PlanetSharedData>();

        PlanetSharedData[] dataArray = new PlanetSharedData[planetDataArray.Length];
        for (int i = 0; i < dataArray.Length; ++i)
        {
            dataArray[i] = planetDataArray[i];
        }

        EntityArray entityTempArray = nodeGroup.GetEntityArray();

        Entity[] entityArray = new Entity[entityTempArray.Length];
        for (int i = 0; i < entityArray.Length; ++i)
        {
            entityArray[i] = entityTempArray[i];
        }

        SharedComponentDataArray <HPMeshInstanceRenderer> meshCDArray = nodeGroup.GetSharedComponentDataArray <HPMeshInstanceRenderer>();

        HPMeshInstanceRenderer[] meshArray = new HPMeshInstanceRenderer[meshCDArray.Length];
        for (int i = 0; i < meshArray.Length; ++i)
        {
            meshArray[i] = meshCDArray[i];
        }

        ComponentDataArray <TerrainNode> nodeCDArray = nodeGroup.GetComponentDataArray <TerrainNode>();

        TerrainNode[] nodeArray = new TerrainNode[nodeCDArray.Length];
        for (int i = 0; i < nodeCDArray.Length; ++i)
        {
            nodeArray[i] = nodeCDArray[i];
        }

        ComponentDataArray <PrecisePosition> nodePosArray = nodeGroup.GetComponentDataArray <PrecisePosition>();

        PrecisePosition[] posArray = new PrecisePosition[nodePosArray.Length];
        for (int i = 0; i < nodePosArray.Length; ++i)
        {
            posArray[i] = nodePosArray[i];
        }

        ComponentDataArray <OctantPosition> nodeOctArray = nodeGroup.GetComponentDataArray <OctantPosition>();

        OctantPosition[] octArray = new OctantPosition[nodePosArray.Length];
        for (int i = 0; i < nodeOctArray.Length; ++i)
        {
            octArray[i] = nodeOctArray[i];
        }

        ComponentDataArray <PrecisePosition> camPosArray = camGroup.GetComponentDataArray <PrecisePosition>();
        float3 camPos = camPosArray[0].pos;
        ComponentDataArray <OctantPosition> camOctArray = camGroup.GetComponentDataArray <OctantPosition>();
        int3 camOct = camOctArray[0].pos;

        float octantSize = HyperposStaticReferences.OctantSize;


        for (int i = 0; i < meshArray.Length; ++i)
        {
            if (nodeArray[i].built == 1 && nodeArray[i].divided == 0)
            {
                if (nodeArray[i].level < nodeArray[i].planetData.maxNodeLevels)
                {
                    float3        corner0      = nodeArray[i].corner1;
                    float3        corner1      = nodeArray[i].corner2;
                    float3        corner2      = nodeArray[i].corner3;
                    HyperDistance sphereRadius = nodeArray[i].planetData.radius;

                    HyperPosition corner0Pos = corner0 * sphereRadius;
                    HyperPosition corner1Pos = corner1 * sphereRadius;

                    HyperDistance distToSubdivide = MathUtils.Distance(corner0Pos, corner1Pos)
                                                    * (PERCENT_DIST_TO_SUBDIVIDE_AT / 100f);

                    HyperPosition centerPos = GetNodeCenter(nodeArray[i]);

                    //if (UnityEngine.Random.Range(0, 20) == 2)
                    //    Debug.Log(MathUtils.ToString(distToSubdivide) + "\n" + MathUtils.ToString(centerPos));
                    if (InSubdivideDist(camOct, camPos, centerPos.oct, centerPos.prs, distToSubdivide.oct, distToSubdivide.prs))
                    {
                        //Debug.Log(MathUtils.ToString(distToSubdivide) + "\n" + MathUtils.ToString(centerPos)
                        //    + "\n" + camOct + " " + camPos);
                        Subdivide(entityArray[i], nodeArray[i], meshArray[i], dataArray[0],
                                  distToSubdivide.prs, distToSubdivide.oct, centerPos.prs, centerPos.oct);
                    }
                }
                if (nodeArray[i].level > 0 && EntityManager.Exists(nodeArray[i].parentEntity))
                {
                    HPMeshInstanceRenderer parentR
                        = EntityManager.GetSharedComponentData <HPMeshInstanceRenderer>(nodeArray[i].parentEntity);
                    //float dist = math.distance(camPos, nodeArray[i].parentCenter);
                    //HyperDistance dist = MathUtils.Distance(camOct, camPos,
                    //    nodeArray[i].parentOctantCenter, nodeArray[i].parentPreciseCenter);

                    //if (parentR.mesh != null
                    //    && (dist.octantDist < nodeArray[i].parentOctantSubdivideDist
                    //        || (dist.octantDist == nodeArray[i].parentOctantSubdivideDist && dist.preciseDist < nodeArray[i].parentPreciseSubdivideDist)))
                    if (!InSubdivideDist(camOct, camPos, nodeArray[i].parentOctantCenter, nodeArray[i].parentPreciseCenter,
                                         nodeArray[i].parentOctantSubdivideDist, nodeArray[i].parentPreciseSubdivideDist))
                    {
                        EntityManager.DestroyEntity(entityArray[i]);
                    }
                }
            }
            else if (nodeArray[i].built == 0 && nodeArray[i].divided == 1)
            {
                float3        corner0      = nodeArray[i].corner1;
                float3        corner1      = nodeArray[i].corner2;
                float3        corner2      = nodeArray[i].corner3;
                HyperDistance sphereRadius = nodeArray[i].planetData.radius;

                HyperPosition corner0Pos = corner0 * sphereRadius;
                HyperPosition corner1Pos = corner1 * sphereRadius;

                HyperDistance distToSubdivide = MathUtils.Distance(corner0Pos, corner1Pos) * (PERCENT_DIST_TO_SUBDIVIDE_AT / 100f);
                HyperPosition centerPos       = GetNodeCenter(nodeArray[i]);

                if (!InSubdivideDist(camOct, camPos, centerPos.oct, centerPos.prs, distToSubdivide.oct, distToSubdivide.prs))
                {
                    nodeArray[i].divided       = 0;
                    nodeArray[i].childrenBuilt = 0;
                    EntityManager.SetComponentData(entityArray[i], nodeArray[i]);
                }
            }
            else if (nodeArray[i].built == 0 && nodeArray[i].divided == 0)
            {
                nodeArray[i].built = 1;

                Planet planetData = nodeArray[i].planetData;

                // rez is the number of vertices on one side of the mesh/triangle
                // the part in parentheses is called the "Mersenne Number"
                int rez = 2 + ((int)Mathf.Pow(2, planetData.meshSubdivisions) - 1);
                // nTris is the number of tris in the mesh
                int t     = rez - 2;
                int nTris = (t * (t + 1)) + (rez - 1);
                // nVerts is the number of vertices in the mesh
                // it is the formula for the "Triangle Sequence" of numbers
                int nVerts = (rez * (rez + 1)) / 2;

                NativeArray <Vector3> verts = new NativeArray <Vector3>(nVerts, Allocator.Persistent);
                NativeArray <int>     tris  = new NativeArray <int>(nTris * 3, Allocator.Persistent);

                HyperPosition centerPos = GetNodeCenter(nodeArray[i]);
                HyperPosition camHyp    = new HyperPosition {
                    prs = camPos, oct = camOct
                };
                HyperDistance dist = MathUtils.Distance(centerPos, camHyp);

                //if (dist > planetData.hyperdistanceThreshold)
                //{
                //    nodeArray[i].hyperDistant = 1;
                //    if(!EntityManager.HasComponent<HyperdistantMarker>(entityArray[i]))
                //        EntityManager.AddComponent(entityArray[i], typeof(HyperdistantMarker));
                //}
                //else
                //{
                //    nodeArray[i].hyperDistant = 0;
                //    if (EntityManager.HasComponent<HyperdistantMarker>(entityArray[i]))
                //        EntityManager.RemoveComponent(entityArray[i], typeof(HyperdistantMarker));
                //}

                MeshBuildJob job = new MeshBuildJob();
                job.node    = nodeArray[i];
                job.corner0 = nodeArray[i].corner3;
                job.corner1 = nodeArray[i].corner2;
                job.corner2 = nodeArray[i].corner1;
                job.rez     = rez;
                job.nTris   = nTris;
                job.nVerts  = nVerts;
                job.verts   = verts;
                job.tris    = tris;

                JobHandle handle = job.Schedule();
                JobHandle.ScheduleBatchedJobs();

                MeshCreationSet mcs = new MeshCreationSet();
                mcs.entity    = entityArray[i];
                mcs.jobHandle = handle;
                mcs.verts     = verts;
                mcs.tris      = tris;
                meshCreationSets.Add(mcs);

                EntityManager.SetComponentData(entityArray[i], nodeArray[i]);
            }
        }
    }
Esempio n. 20
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (!initialized)
        {
            Initialize();
            initialized = true;
        }

        if (uninitializedPlayfieldGroup.CalculateLength() == 0)
        {
            return(inputDeps);
        }

        resultPositions.Clear();
        playfieldIndex.Clear();

        SharedComponentDataArray <Playfield> playfieldArray = uninitializedPlayfieldGroup.GetSharedComponentDataArray <Playfield>();
        EntityArray entityArray = uninitializedPlayfieldGroup.GetEntityArray();
        Playfield   playfield   = entityManager.GetSharedComponentData <Playfield>(entityArray[0]);

        for (int i = 0; i < playfieldArray.Length; i++)
        {
            playfieldIndex.TryAdd(playfieldArray[i].index, i);
        }

        JobHandle combinedHandle = new JobHandle();
        int       totalNumCells  = 0;

        for (int i = 0; i < playfieldArray.Length; i++)
        {
            int size = playfieldArray[i].width * playfieldArray[i].height;
            totalNumCells += size;
            JobHandle pHandle = new PlayfieldCellPositionJob {
                width          = playfieldArray[i].width,
                height         = playfieldArray[i].height,
                playfieldIndex = i,
                cellDatas      = positions.ToConcurrent(),
            }.Schedule(size, 64, inputDeps);

            if (i == 0)
            {
                combinedHandle = pHandle;
            }
            else
            {
                combinedHandle = JobHandle.CombineDependencies(combinedHandle, pHandle);
            }
        }

        JobHandle qlHandle = new NativeQueueToNativeListJob <CellData> {
            queue    = positions,
            out_list = resultPositions,
        }.Schedule(combinedHandle);

        JobHandle pijHandle = new PlayfieldCellCreationJob {
            commandBuffer          = initBarrier.CreateCommandBuffer().ToConcurrent(),
            positions              = resultPositions,
            playfieldCellArchetype = playfieldCellArchetype,
            playfieldArray         = playfieldArray,
            playfieldIndex         = playfieldIndex,
        }.Schedule(totalNumCells, 64, qlHandle);

        JobHandle pfjHandle = new PlayfieldFinalizeJob {
            commandBuffer = finalizeBarrier.CreateCommandBuffer().ToConcurrent(),
            playfields    = entityArray,
        }.Schedule(entityArray.Length, 64, pijHandle);

        return(pfjHandle);
    }