Beispiel #1
0
 protected virtual void TriggerLoaded(ChunkKey key, List <ITrigger> triggers)
 {
     if (OnTriggerLoaded != null)
     {
         OnTriggerLoaded(key, triggers);
     }
 }
Beispiel #2
0
 protected virtual void EntityGenerated(List <Entity> loaded, ChunkKey area)
 {
     if (OnEntityGenerated != null)
     {
         OnEntityGenerated(loaded, area);
     }
 }
Beispiel #3
0
        public VoxelTreeChunk(ChunkKey key, IIndexableTree <Index3D, TerrainVoxel> voxels)
        {
            Contracts.Requires.That(voxels != null);

            this.Key             = key;
            this.VoxelsLocalView = voxels;
        }
Beispiel #4
0
        private IChunk LoadChunk(ChunkKey key)
        {
            var path         = Utils.GetPathForChunk(Game, key);
            var fullFilePath = path + TargetFilename;

            if (!System.IO.File.Exists(fullFilePath))
            {
                return(null);
            }

            try
            {
                var file  = new FileStream(fullFilePath, FileMode.Open);
                var chunk = file.ReadChunk(Game.Engine);
                file.Close();
                file.Dispose();
                return(chunk);
            }
            catch (Exception e)
            {
                Logger.Write(string.Format("Unable to get {0} data ({1}) - assuming corrupt and will re-create", fullFilePath, e), LoggerLevel.Error);
                System.IO.File.Delete(fullFilePath);
                return(null);
            }
        }
Beispiel #5
0
 public void LoadTriggers(ChunkKey location)
 {
     lock (this)
     {
         _triggersToLoad.Add(location);
     }
 }
Beispiel #6
0
        // XXX: Consider revising foreign lookup support
        /// <summary>
        /// Gets a <see cref="ChunkRef"/> for a chunk at the given local coordinates relative to this region.
        /// </summary>
        /// <param name="lcx">The local X-coordinate of a chunk relative to this region.</param>
        /// <param name="lcz">The local Z-coordinate of a chunk relative to this region.</param>
        /// <returns>A <see cref="ChunkRef"/> at the given local coordinates, or null if no chunk exists.</returns>
        /// <remarks>The local coordinates do not strictly need to be within the bounds of the region.  If coordinates are detected
        /// as being out of bounds, the lookup will be delegated to the correct region and the lookup will be performed there
        /// instead.  This allows any <see cref="Region"/> to perform a similar task to <see cref="BetaChunkManager"/>, but with a
        /// region-local frame of reference instead of a global frame of reference.</remarks>
        public ChunkRef GetChunkRef(int lcx, int lcz)
        {
            if (!LocalBoundsCheck(lcx, lcz))
            {
                Region alt = GetForeignRegion(lcx, lcz);
                return((alt == null) ? null : alt.GetChunkRef(ForeignX(lcx), ForeignZ(lcz)));
            }

            int cx = lcx + _rx * XDIM;
            int cz = lcz + _rz * ZDIM;

            ChunkKey k = new ChunkKey(cx, cz);
            ChunkRef c = _cache.Fetch(k);

            if (c != null)
            {
                return(c);
            }

            c = ChunkRef.Create(this, lcx, lcz);
            if (c != null)
            {
                _cache.Insert(c);
            }

            return(c);
        }
Beispiel #7
0
    private void sortIntoChunks(bool isCollision)
    {
        accumulateCounts(isCollision);

        _chunkLocations.Clear();
        int sum = 0;

        foreach (var pair in _chunkCounts)
        {
            _chunkLocations[pair.Key] = new ChunkLocation()
            {
                start = sum,
                end   = sum
            };
            sum += pair.Value;
        }

        float chunkScale = 1.0f / (isCollision ? PARTICLE_DIAMETER : MAX_SOCIAL_RANGE);

        for (int i = 0; i < _aliveParticles; i++)
        {
            var chunkKey      = new ChunkKey(ref _particlesFront[i].position, chunkScale);
            var chunkLocation = _chunkLocations[chunkKey];

            _particlesBack[chunkLocation.end] = _particlesFront[i];
            chunkLocation.end++;
            _chunkLocations[chunkKey] = chunkLocation;
        }
    }
Beispiel #8
0
 private bool IsValidChunkKey(ChunkKey chunkKey)
 {
     return(chunkKey.X >= _battleSettings.MinWidthIndex &&
            chunkKey.X <= _battleSettings.MaxWidthIndex &&
            chunkKey.Y >= _battleSettings.MinHeightIndex &&
            chunkKey.Y <= _battleSettings.MaxHeightIndex);
 }
Beispiel #9
0
        /// <summary>
        /// Deletes a chunk from the underlying data store at the given local coordinates relative to this region.
        /// </summary>
        /// <param name="lcx">The local X-coordinate of a chunk relative to this region.</param>
        /// <param name="lcz">The local Z-coordinate of a chunk relative to this region.</param>
        /// <returns>True if there is a chunk was deleted; false otherwise.</returns>
        /// <remarks>If the local coordinates are out of bounds for this region, the action will be forwarded to the correct region
        /// transparently.</remarks>
        public bool DeleteChunk(int lcx, int lcz)
        {
            if (!LocalBoundsCheck(lcx, lcz))
            {
                Region alt = GetForeignRegion(lcx, lcz);
                return((alt == null) ? false : alt.DeleteChunk(ForeignX(lcx), ForeignZ(lcz)));
            }

            RegionFile rf = GetRegionFile();

            if (!rf.HasChunk(lcx, lcz))
            {
                return(false);
            }

            rf.DeleteChunk(lcx, lcz);

            ChunkKey k = new ChunkKey(ChunkGlobalX(lcx), ChunkGlobalZ(lcz));

            _cache.Remove(k);

            if (ChunkCount() == 0)
            {
                _regionMan.DeleteRegion(X, Z);
            }

            return(true);
        }
Beispiel #10
0
        protected bool LoadEntities(ChunkKey area)
        {
            var name = Utils.GetPathForChunk(Game, area);

            name = Path.Combine(name, DataDir);

            if (!Directory.Exists(name))
            {
                return(false);
            }

            var entities = new List <Entity>();

            foreach (var filename in Directory.EnumerateFiles(name))
            {
                try
                {
                    var entity = LoadEntityFromFile(filename);
                    entities.Add(entity);
                }
                catch (Exception e)
                {
                    Logger.Write(String.Format("Unable to load entity in file {0} ({1})- skipping", filename, e), LoggerLevel.Error);
                }
            }

            OnEntityLoaded(entities, area);

            return(true);
        }
        private async Task <Model> DoGenerateModelAsync(ChunkKey key)
        {
            using (var mesh = await this.meshFactory.CreateAsync(key).DontMarshallContext())
            {
                if (mesh.Value.IsEmpty())
                {
                    return(null);
                }

                using (var transfer = await this.transferPool.TakeLoanAsync().DontMarshallContext())
                {
                    var model = new Model();
                    model.Add(this.material);

                    foreach (var splitMesh in DivisibleMesh.Split(this.maxVertices, mesh.Value))
                    {
                        transfer.Value.CopyIn(
                            splitMesh.Convert(vertex => vertex.ToXenko()), XenkoMeshConstants.VertexWindingOrder);

                        model.Add(this.proceduralMesh.Create(transfer.Value));
                    }

                    return(model);
                }
            }
        }
        public ContourChunkView(ChunkKey key, IBoundedReadOnlyIndexable <Index3D, TChunk> chunks)
        {
            IContourChunkViewContracts.Constructor(key, chunks);

            this.Key    = key;
            this.Chunks = chunks;
        }
Beispiel #13
0
    private void resolveCollisionsChunked(int i,
                                          ref Particle particle,
                                          ref SpeciesData speciesData,
                                          ChunkKey chunkKey,
                                          int offsetX,
                                          int offsetY,
                                          int offsetZ)
    {
        chunkKey.x = (ushort)(chunkKey.x + offsetX);
        chunkKey.y = (ushort)(chunkKey.y + offsetY);
        chunkKey.z = (ushort)(chunkKey.z + offsetZ);

        ChunkLocation location;

        if (_chunkLocations.TryGetValue(chunkKey, out location))
        {
            for (int j = location.start; j < location.end; j++)
            {
                DoParticleCollisionInteraction(ref particle,
                                               ref speciesData,
                                               ref _particlesBack[j],
                                               ref _speciesData[_particlesBack[j].species]);

                DoParticleCollisionInteraction(ref _particlesFront[j],
                                               ref _speciesData[_particlesFront[j].species],
                                               ref _particlesBack[i],
                                               ref speciesData);
            }
        }
    }
Beispiel #14
0
        public async Task <IChunkSubscription> SubscribeOnChunkUpdateAsync(ChunkKey key, Func <ChunkUpdate, Task> onUpdate)
        {
            var stream  = _streamProvider.GetStream <ChunkUpdate>(FormatChunkKey(key), ChunklerConstants.ChunkOutcomingUpdate);
            var handler = await stream.SubscribeAsync(new ChunkObserver(_logger, onUpdate));

            return(new ChunkSubscription(handler));
        }
Beispiel #15
0
 public void UnsubscribeFromChunk(ChunkKey key)
 {
     if (Subscriptions.Remove(key, out var subscription))
     {
         subscription.Dispose();
     }
 }
        public VoxelGridChunk(ChunkKey key, IBoundedIndexable <Index3D, TerrainVoxel> voxels)
        {
            Contracts.Requires.That(voxels != null);

            this.Key             = key;
            this.VoxelsLocalView = voxels;
            this.VoxelsStageView = new OffsetArray3D <TerrainVoxel>(voxels, voxels.Dimensions * key.Index);
        }
Beispiel #17
0
        public StageBounds(ChunkKey minChunkKey, Index3D dimensionsInChunks)
        {
            Contracts.Requires.That(dimensionsInChunks.IsAllPositive());

            this.InChunks         = new IndexingBounds3D(minChunkKey.Index, dimensionsInChunks);
            this.InOverheadChunks = new IndexingBounds2D(
                minChunkKey.Index.ProjectDownYAxis(), dimensionsInChunks.ProjectDownYAxis());
        }
        /// <summary>
        /// Performs a full chunk relight sequence on all modified chunks.
        /// </summary>
        public void RelightDirtyChunks()
        {
            //List<ChunkRef> dirty = new List<ChunkRef>();
            Dictionary <ChunkKey, ChunkRef> dirty = new Dictionary <ChunkKey, ChunkRef>();

            _cache.SyncDirty();

            IEnumerator <ChunkRef> en = _cache.GetDirtyEnumerator();

            while (en.MoveNext())
            {
                ChunkKey key = new ChunkKey(en.Current.X, en.Current.Z);
                dirty[key] = en.Current;
            }

            foreach (ChunkRef chunk in dirty.Values)
            {
                chunk.Blocks.ResetBlockLight();
                chunk.Blocks.ResetSkyLight();
            }

            foreach (ChunkRef chunk in dirty.Values)
            {
                chunk.Blocks.RebuildBlockLight();
                chunk.Blocks.RebuildSkyLight();
            }

            foreach (ChunkRef chunk in dirty.Values)
            {
                if (!dirty.ContainsKey(new ChunkKey(chunk.X, chunk.Z - 1)))
                {
                    ChunkRef east = chunk.GetEastNeighbor();
                    chunk.Blocks.StitchBlockLight(east.Blocks, BlockCollectionEdge.EAST);
                    chunk.Blocks.StitchSkyLight(east.Blocks, BlockCollectionEdge.EAST);
                }

                if (!dirty.ContainsKey(new ChunkKey(chunk.X, chunk.Z + 1)))
                {
                    ChunkRef west = chunk.GetWestNeighbor();
                    chunk.Blocks.StitchBlockLight(west.Blocks, BlockCollectionEdge.WEST);
                    chunk.Blocks.StitchSkyLight(west.Blocks, BlockCollectionEdge.WEST);
                }

                if (!dirty.ContainsKey(new ChunkKey(chunk.X - 1, chunk.Z)))
                {
                    ChunkRef north = chunk.GetNorthNeighbor();
                    chunk.Blocks.StitchBlockLight(north.Blocks, BlockCollectionEdge.NORTH);
                    chunk.Blocks.StitchSkyLight(north.Blocks, BlockCollectionEdge.NORTH);
                }

                if (!dirty.ContainsKey(new ChunkKey(chunk.X + 1, chunk.Z)))
                {
                    ChunkRef south = chunk.GetSouthNeighbor();
                    chunk.Blocks.StitchBlockLight(south.Blocks, BlockCollectionEdge.SOUTH);
                    chunk.Blocks.StitchSkyLight(south.Blocks, BlockCollectionEdge.SOUTH);
                }
            }
        }
Beispiel #19
0
 public void LoadEntities(ChunkKey area)
 {
     Logger.Write(string.Format("Loading entities in {0}", area), LoggerLevel.Info);
     lock (this)
     {
         _entitiesToLoad.Add(area);
         Monitor.PulseAll(this);
     }
 }
Beispiel #20
0
        public static string GetPathForChunk(IGame game, ChunkKey key)
        {
            var saveDir = Path.Combine(GetRootSaveDirectory(game), key.X.ToString(CultureInfo.InvariantCulture));

            saveDir = Path.Combine(saveDir, key.Y.ToString(CultureInfo.InvariantCulture));

            Directory.CreateDirectory(saveDir);
            return(saveDir);
        }
Beispiel #21
0
        public ChunkRef Fetch(ChunkKey key)
        {
            ChunkRef c;
            if (!_cache.TryGetValue(key, out c)) {
                return null;
            }

            return c;
        }
Beispiel #22
0
        private void EntitiesLoaded(List <Entity> entities, ChunkKey key)
        {
            if (OnEntityLoaded != null)
            {
                OnEntityLoaded(entities, key);
            }

            SaveEntities(entities);
        }
Beispiel #23
0
        protected void SaveChunk(ChunkKey chunkkey, byte[] data)
        {
            var path         = Utils.GetPathForChunk(Game, chunkkey);
            var fullFilePath = Path.Combine(path, TargetFilename);

            var file = new FileStream(fullFilePath, FileMode.Create);

            file.Write(data, 0, data.Length);
            file.Close();
            file.Dispose();
        }
 /// <inheritdoc />
 public async Task <TChunk> CreateAsync(ChunkKey key)
 {
     if (key.Index.IsIn(this.minKey, this.maxKey))
     {
         return(await this.interiorFactory.CreateAsync(key).DontMarshallContext());
     }
     else
     {
         return(this.exteriorFactory.Create(key));
     }
 }
Beispiel #25
0
 public async Task <int> ProcessChunkAction(ChunkKey key, ChunkAction action)
 {
     if (Subscriptions.TryGetValue(key, out var chunkHandlerSubscription))
     {
         return(await chunkHandlerSubscription.ChunkHandler.ProcessAsync(action));
     }
     else
     {
         throw new InvalidOperationException("Can't access chunk that not subscribed.");
     }
 }
Beispiel #26
0
 public async Task RequestChunkState(ChunkKey key)
 {
     if (Subscriptions.TryGetValue(key, out var chunkHandlerSubscription))
     {
         await SendChunkStateAsync(key, chunkHandlerSubscription);
     }
     else
     {
         throw new InvalidOperationException("Can't access chunk that not subscribed.");
     }
 }
Beispiel #27
0
        /// <inheritdoc/>
        public bool DeleteChunk(int cx, int cz)
        {
            new ChunkFile(_mapPath, cx, cz).Delete();

            ChunkKey k = new ChunkKey(cx, cz);

            _cache.Remove(k);
            _dirty.Remove(k);

            return(true);
        }
Beispiel #28
0
        public bool Insert(ChunkRef chunk)
        {
            ChunkKey key = new ChunkKey(chunk.X, chunk.Z);

            ChunkRef c;
            if (!_cache.TryGetValue(key, out c)) {
                _cache[key] = chunk;
                return true;
            }

            return false;
        }
Beispiel #29
0
        /// <inheritdoc/>
        public ChunkRef SetChunk(int cx, int cz, Chunk chunk)
        {
            DeleteChunk(cx, cz);
            chunk.SetLocation(cx, cz);
            chunk.Save(GetChunkOutStream(cx, cz));

            ChunkRef cr = ChunkRef.Create(this, cx, cz);
            ChunkKey k  = new ChunkKey(cx, cz);

            _cache[k] = cr;

            return(cr);
        }
 public static void Constructor <TChunk>(
     ChunkKey key, IBoundedReadOnlyIndexable <Index3D, TChunk> chunks)
     where TChunk : IKeyed <ChunkKey>
 {
     Contracts.Requires.That(chunks.AllAndSelfNotNull());
     Contracts.Requires.That(chunks.LowerBounds == new Index3D(-1));
     Contracts.Requires.That(chunks.UpperBounds == new Index3D(1));
     Contracts.Requires.That(chunks.Dimensions == new Index3D(3));
     Contracts.Requires.That(
         Index.Range(new Index3D(-1), new Index3D(3)).All(
             index => chunks[index].Key == new ChunkKey(key.Index + index)),
         $"Each chunk's offset in {nameof(chunks)} must match its Key's offset to {nameof(key)}.");
 }
    public override bool Equals(object o_)
    {
        ChunkKey o = o_ as ChunkKey;

        if (o == null)
        {
            return(false);
        }
        return
            (X == o.X &&
             Y == o.Y &&
             Z == o.Z &&
             Sub == o.Sub);
    }
Beispiel #32
0
        /// <inheritdoc/>
        public ChunkRef CreateChunk(int cx, int cz)
        {
            DeleteChunk(cx, cz);
            Chunk c = Chunk.Create(cx, cz);

            c.Save(GetChunkOutStream(cx, cz));

            ChunkRef cr = ChunkRef.Create(this, cx, cz);
            ChunkKey k  = new ChunkKey(cx, cz);

            _cache[k] = cr;

            return(cr);
        }
Beispiel #33
0
        private IBoundedDataBlockCollection GetChunk(int x, int z)
        {
            int cx = x / _xdim + (x >> 31);
            int cz = z / _zdim + (z >> 31);

            ChunkKey key = new ChunkKey(cx, cz);

            IBoundedDataBlockCollection chunk;
            if (!_chunks.TryGetValue(key, out chunk)) {
                chunk = OnResolveNeighbor(cx, 0, cz);
                _chunks[key] = chunk;
            }

            return chunk;
        }
Beispiel #34
0
        /// <summary>
        /// Deletes a chunk from the underlying data store at the given local coordinates relative to this region.
        /// </summary>
        /// <param name="lcx">The local X-coordinate of a chunk relative to this region.</param>
        /// <param name="lcz">The local Z-coordinate of a chunk relative to this region.</param>
        /// <returns>True if there is a chunk was deleted; false otherwise.</returns>
        /// <remarks>If the local coordinates are out of bounds for this region, the action will be forwarded to the correct region
        /// transparently.</remarks>
        public bool DeleteChunk(int lcx, int lcz)
        {
            if (!LocalBoundsCheck(lcx, lcz)) {
                Region alt = GetForeignRegion(lcx, lcz);
                return (alt == null) ? false : alt.DeleteChunk(ForeignX(lcx), ForeignZ(lcz));
            }

            RegionFile rf = GetRegionFile();
            if (!rf.HasChunk(lcx, lcz)) {
                return false;
            }

            rf.DeleteChunk(lcx, lcz);

            ChunkKey k = new ChunkKey(lcx, lcz);
            _cache.Remove(k);

            if (ChunkCount() == 0) {
                _regionMan.DeleteRegion(X, Z);
            }

            return true;
        }
 /// <summary>
 /// Removes a chunk from the cache.
 /// </summary>
 /// <param name="key">The key identifying which <see cref="ChunkRef"/> to try and remove.</param>
 /// <returns><c>True</c> if the chunk was in the LRU-portion of the cache and removed, <c>False</c> otherwise.</returns>
 /// <remarks>The chunk will also be removed from the dirty list, if it is currently in it.</remarks>
 public bool Remove (ChunkKey key)
 {
     _dirty.Remove(key);
     return _cache.Remove(key);
 }
Beispiel #36
0
        // XXX: Consider revising foreign lookup support
        /// <summary>
        /// Gets a <see cref="ChunkRef"/> for a chunk at the given local coordinates relative to this region.
        /// </summary>
        /// <param name="lcx">The local X-coordinate of a chunk relative to this region.</param>
        /// <param name="lcz">The local Z-coordinate of a chunk relative to this region.</param>
        /// <returns>A <see cref="ChunkRef"/> at the given local coordinates, or null if no chunk exists.</returns>
        /// <remarks>The local coordinates do not strictly need to be within the bounds of the region.  If coordinates are detected
        /// as being out of bounds, the lookup will be delegated to the correct region and the lookup will be performed there
        /// instead.  This allows any <see cref="Region"/> to perform a similar task to <see cref="BetaChunkManager"/>, but with a
        /// region-local frame of reference instead of a global frame of reference.</remarks>
        public ChunkRef GetChunkRef(int lcx, int lcz)
        {
            if (!LocalBoundsCheck(lcx, lcz)) {
                Region alt = GetForeignRegion(lcx, lcz);
                return (alt == null) ? null : alt.GetChunkRef(ForeignX(lcx), ForeignZ(lcz));
            }

            int cx = lcx + _rx * XDIM;
            int cz = lcz + _rz * ZDIM;

            ChunkKey k = new ChunkKey(cx, cz);
            ChunkRef c = _cache.Fetch(k);
            if (c != null) {
                return c;
            }

            c = ChunkRef.Create(this, lcx, lcz);
            if (c != null) {
                _cache.Insert(c);
            }

            return c;
        }