Пример #1
0
        /// <summary>
        /// Load new models from folder
        /// </summary>
        /// <param name="folderPath"></param>
        public void ImportFromPath(string folderPath)
        {
            try
            {
                foreach (var file in Directory.GetFiles(folderPath, "*.uvm"))
                {
                    var name = Path.GetFileNameWithoutExtension(file);
                    if (name == null)
                    {
                        continue;
                    }
                    name = name.Replace('\'', ' ');
                    using (var reader = Query("SELECT updated FROM models WHERE id ='{0}'", name))
                    {
                        if (reader.Read() && reader.GetDateTime(0) >= File.GetLastWriteTimeUtc(file))
                        {
                            continue;
                        }
                    }

                    // import the model
                    Delete(name);
                    Save(VoxelModel.LoadFromFile(file));
                }
            }
            catch (Exception x)
            {
                Logger.Error("Models import failed. {0}", x.Message);
            }
        }
Пример #2
0
    public override void Initialize()
    {
        var voxFilePath = GetPathInStreamingAssets(Monu1Path);
        var voxFile     = _magicaReader.LoadFile(voxFilePath);

        _model = voxFile.ToVolume();
    }
Пример #3
0
 public IEnumerable <VoxelModel> Enumerate()
 {
     foreach (var file in Directory.EnumerateFiles(_folder, "*.uvm"))
     {
         var model = VoxelModel.LoadFromFile(file);
         yield return(model);
     }
 }
Пример #4
0
    void saveMesh(GameObject gameObject, AssetImportContext ctx, Settings settings, VoxelModel model)
    {
        var   ChunkModels = model.SplitModelInChunkLModel(factor: FactorSize);
        int   i           = 0;
        float size        = (4 << FactorSize) * settings.SizeShared;

        for (int x = 0; x < ChunkModels.Item2.x; x++)
        {
            for (int y = 0; y < ChunkModels.Item2.y; y++)
            {
                for (int z = 0; z < ChunkModels.Item2.z; z++)
                {
                    if (ChunkModels.Item1[x, y, z].Only0)
                    {
                        continue;
                    }
                    var meshBulder = new MeshGenerator(settings, ChunkModels.Item1[x, y, z]);
                    if (ChunkOptimized)
                    {
                        meshBulder.NeighbourChunck = new Tuple <SurfaceAction, Array3UshortOpt>[6]
                        {
                            z + 1 < ChunkModels.Item2.z ? new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.RenderBasedOnNeighbourChunk, ChunkModels.Item1[x, y, z + 1]) :
                            new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.Render, default),    // front
                            z - 1 >= 0 ? new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.RenderBasedOnNeighbourChunk, ChunkModels.Item1[x, y, z - 1]) :
                            new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.Render, default),    // back
                            y + 1 < ChunkModels.Item2.y ? new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.RenderBasedOnNeighbourChunk, ChunkModels.Item1[x, y + 1, z]) :
                            new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.Render, default),    // top
                            y - 1 >= 0 ? new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.RenderBasedOnNeighbourChunk, ChunkModels.Item1[x, y - 1, z]) :
                            new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.Render, default),    // buttom
                            x - 1 >= 0 ? new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.RenderBasedOnNeighbourChunk, ChunkModels.Item1[x - 1, y, z]) :
                            new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.Render, default),    // right
                            x + 1 < ChunkModels.Item2.x ? new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.RenderBasedOnNeighbourChunk, ChunkModels.Item1[x + 1, y, z]) :
                            new Tuple <SurfaceAction, Array3UshortOpt>(SurfaceAction.Render, default),    // left
                        }
                    }
                    ;
                    meshBulder.GenerateMesh(fileName + "_childMesh_" + i);
                    if (meshBulder.mesh.vertexCount == 0)
                    {
                        continue;
                    }
                    var child = new GameObject(fileName + "_child_" + i);
                    child.transform.parent   = gameObject.transform;
                    child.transform.position = new Vector3(x * size, y * size, z * size);
                    child.AddComponent <MeshRenderer>().materials = settings.GetMaterials();
                    child.AddComponent <MeshFilter>().mesh        = meshBulder.mesh;
                    if (GenerateCollider)
                    {
                        var collideBuilder = new ColliderGenerator(child.transform, ChunkModels.Item1[x, y, z], settings);
                        collideBuilder.GenerateCollider();
                    }

                    ctx.AddObjectToAsset(fileName + "_childMesh_" + i, meshBulder.mesh);
                    i++;
                }
            }
        }
    }
Пример #5
0
 public VoxelModel Load(string name)
 {
     if (Contains(name))
     {
         var model = VoxelModel.LoadFromFile(Path.Combine(_folder, name, ".uvm"));
         return(model);
     }
     return(null);
 }
Пример #6
0
    public void Start()
    {
        pos = WorldGrid.instance.GridPos(transform.position);

        WorldGrid.instance.AddBuilding(this);
        model      = GetComponent <VoxelModel>();
        progress   = woodRequired > 0 ? woodProvided / (float)woodRequired : 1;
        modelDepth = (int)(model.MaxDepth() * progress);
        UpdateModel();
    }
Пример #7
0
 /// <summary>
 /// Saves a new model to the storage
 /// </summary>
 /// <param name="model"></param>
 void IVoxelModelStorage.Save(VoxelModel model)
 {
     CheckName(model.Name);
     using (var ms = new MemoryStream())
     {
         Serializer.Serialize(ms, model);
         var bytes = ms.ToArray();
         InsertBlob(string.Format("INSERT INTO models (id,data) VALUES ('{0}', @blob)", model.Name), bytes);
     }
 }
Пример #8
0
    public override void ApplyDamage(GameObject source)
    {
        base.ApplyDamage(source);

        if (--m_Health <= 0)
        {
            VoxelModel model = GetComponentInChildren <VoxelModel>();
            VoxelDebrisController.Main.SpawnDebris(model.m_VoxelData, transform, (transform.position - source.transform.position), m_DebrisSkip);
            Destroy(gameObject);
        }
    }
Пример #9
0
        /// <summary>
        /// Removes a frame from the model, free dx resources
        /// </summary>
        /// <param name="index"></param>
        public void RemoveFrameAt(int index)
        {
            var vf = _visualFrames[index];

            vf.IndexBuffer.Dispose();
            vf.VertexBuffer.Dispose();

            VoxelModel.RemoveFrameAt(index);

            ArrayHelper.RemoveAt(ref _visualFrames, index);
        }
Пример #10
0
 private void Start()
 {
     model    = GetComponent <VoxelModel>();
     velocity = new Vector3(
         horizontalVelocity * (Random.value - .5f) * 2,
         verticalVelocity,
         horizontalVelocity * (Random.value - .5f) * 2);
     transform.position += new Vector3(
         noise * (Random.value - .5f) * 2,
         0,
         noise * (Random.value - .5f) * 2);
     transform.position -= velocity / fallDelay;
 }
Пример #11
0
        /// <summary>
        /// Saves a new model to the storage
        /// </summary>
        /// <param name="model"></param>
        public void Save(VoxelModel model)
        {
            CheckName(model.Name);
            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, model);
                var bytes = ms.ToArray();

                if (Contains(model.Name))
                {
                    Delete(model.Name);
                }

                InsertBlob(string.Format("INSERT INTO models (id, updated, data) VALUES ('{0}', datetime('now'), @blob)", model.Name), bytes);
            }
        }
Пример #12
0
    public void OnDrop(Vector3 sprayDirection)
    {
        if (m_Owner != null && m_Owner.CompareTag("Player"))
        {
            GameController.Main.CreateWorldspaceText("-" + m_DisplayName, m_Owner.transform.position, Color.red);
        }

        VoxelModel model = GetComponentInChildren <VoxelModel>();

        if (model != null)
        {
            model.CreateDebris(sprayDirection);
        }

        Destroy(gameObject);
    }
Пример #13
0
    private void Awake()
    {
        _cameraTransform = _camera.transform;

        _voxelGeometryController    = new VoxelGeometryController(8, GetMaxVerticesCount());
        _voxelBuilderController     = new VoxelBuilderController();
        _voxelPhysicsController     = new VoxelPhysicsController();
        _fallingConstructionFactory = new FallingConstructionFactory(_fallingChunksTransform, 32);

        _camera.Hitted += OnHitted;

        var magicaVoxelReader = new MagicaReader();
        var path       = GetPathInStreamingAssets(_volumePath);
        var magicaFile = magicaVoxelReader.LoadFile(path);

        _voxelModel = magicaFile.ToModel(_volumeSize);

        var chunkSize   = _chunkSize;
        var chunksCount = _chunkDrawSize.x * _chunkDrawSize.y * _chunkDrawSize.z;

        Debug.Log($"chunksCount = {chunksCount}");

        for (var i = 0; i < chunksCount; i++)
        {
            var chunkPositionNormalized = VoxelUtility.GetVoxelPosition(i, _chunkDrawSize);
            var chunkIndex      = VoxelChunkUtility.GetIndex(chunkPositionNormalized);
            var chunkPosition   = chunkPositionNormalized * chunkSize;
            var chunkGameObject = new GameObject();
            var chunkView       = chunkGameObject.AddComponent <VolumeChunk>();

            chunkGameObject.name = $"VolumeChunk[{i}]";

            chunkView.SetPosition(new Vector3(chunkPosition.x, chunkPosition.y, chunkPosition.z));
            chunkView.SetParent(_volumeChunksTransform);
            chunkView.SetMaterial(_chunkMaterial);
            chunkView.SetLayer(VolumeChunk.VolumeLayer);

            _chunks[chunkIndex] = chunkView;

            var geometryRequest = GetGeometryRequestById(chunkIndex);
            _chunkRequestQueue.Push(geometryRequest);
        }

        _chunkRenderer = new VoxelChunkRenderer(_cameraTransform, _chunks, _volumeSize, _chunkSize, _chunkDrawSize);
        _chunkRenderer.ChunkUpdated += OnChunkUpdated;
    }
Пример #14
0
        public void CreateModel()
        {
            EntityFactory.InitializeProtobufInheritanceHierarchy();
            var conf =
                WorldConfiguration.LoadFromFile(@"C:\Dev\Utopia\Utopia\Resources\Shared.Resources\Config\Island.realm");

            try
            {
                var model = VoxelModel.GenerateTreeModel(0, conf.TreeBluePrints[0]);

                model.SaveToFile(@"C:\Dev\Utopia\Setup\Output\Tree.uvm");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.StackTrace);
            }
        }
Пример #15
0
    public static byte[] Serialize(VoxelModel model)
    {
        string data = "";

        data += model.Name + "\n";

        //Adds a comma separated list of dimensions: 2,2,2
        data += model.Size.x + "," + model.Size.y + "," + model.Size.z + "\n";

        //Adds a comma separated list of values: 0,0,2,3
        for (int i = 0; i < model.Data.Length; i++)
        {
            data += i + (i < model.Data.Length - 1 ? "," : "");
        }

        return(Encoding.ASCII.GetBytes(data));
    }
Пример #16
0
    public void OnDamaged(GameObject source)
    {
        Vector3 sprayDirection = source.transform.forward;
        bool    isDead         = false;

        // No weapons remaining
        if (m_LeftHandWeapon == null && m_RightHandWeapon == null)
        {
            VoxelModel model = GetComponentInChildren <VoxelModel>();
            if (model != null)
            {
                Vector3 direction = transform.position - source.transform.position;
                model.CreateDebris(direction);
            }

            isDead = true;
            Destroy(gameObject);
        }
        // Only 1 weapon in right hand
        else if (m_LeftHandWeapon == null)
        {
            DropWeapon(m_RightHandWeapon, sprayDirection);
        }
        // Only 1 weapon in left hand
        else if (m_RightHandWeapon == null)
        {
            DropWeapon(m_LeftHandWeapon, sprayDirection);
        }
        // Both weapons, so pick at random
        else
        {
            int rand = Random.Range(0, 2);

            if (rand == 0)
            {
                DropWeapon(m_RightHandWeapon, sprayDirection);
            }
            else
            {
                DropWeapon(m_LeftHandWeapon, sprayDirection);
            }
        }

        GameController.Main.OnCharacterDamage(this, isDead);
    }
Пример #17
0
    public void Init()
    {
        Debug.Log("VoxelMesh.Init");
        //center = new Vector3(CenterX, CenterY, CenterZ);
        blockManager = new BlockManager();
        blockManager.create(SpaceX * Const.ChunkSize, SpaceY * Const.ChunkSize, SpaceZ * Const.ChunkSize, new BlockTypeFun());
        if (model == null)
        {
            model = new VoxelModel();
        }
        else
        {
            for (int i = 0; i < model.sizeX; i++)
            {
                for (int j = 0; j < model.sizeY; j++)
                {
                    for (int k = 0; k < model.sizeZ; k++)
                    {
                        short b = model.blocks[k * model.sizeX * model.sizeY + j * model.sizeX + i];
                        if (b != (short)BlockTypeEnum.Air)
                        {
                            blockManager.setBlock(i + model.originX, j + model.originY, k + model.originZ, b);
                        }
                    }
                }
            }
        }

        rtm = new RayCastManager();
        rtm.create(blockManager.SizeX, blockManager.SizeY, blockManager.SizeZ);
        for (int x = 0; x < SpaceX * Const.ChunkSize; x++)
        {
            for (int y = 0; y < SpaceY * Const.ChunkSize; y++)
            {
                for (int z = 0; z < SpaceZ * Const.ChunkSize; z++)
                {
                    rtm.setBlock(x, y, z, blockManager.getBlock(x, y, z) != 0 ? RayCastBlockType.All : RayCastBlockType.Nothing);
                }
            }
        }
        bDirty      = true;
        curOperator = Operator.DeleteBlock;
    }
Пример #18
0
        /// <summary>
        /// Request a missing model from the server
        /// </summary>
        /// <param name="name"></param>
        public void DownloadModel(string name)
        {
            logger.Info("Downloading model: {0}", name);

            try
            {
                var req      = WebRequest.Create(string.Format("http://utopiarealms.com/models/{0}/download", Uri.EscapeDataString(name)));
                var response = req.GetResponse();

                using (var stream = response.GetResponseStream())
                {
                    var voxelModel = VoxelModel.LoadFromStream(stream);

                    lock (_syncRoot)
                    {
                        if (_models.ContainsKey(voxelModel.Name))
                        {
                            _models.Remove(voxelModel.Name);
                        }

                        var model = new VisualVoxelModel(voxelModel, VoxelMeshFactory);
                        model.BuildMesh();
                        _models.Add(voxelModel.Name, model);
                        _pendingModels.Remove(voxelModel.Name);
                    }

                    _receivedModels.Enqueue(voxelModel);
                    VoxelModelStorage.Save(voxelModel);
                }

                response.Close();
            }
            catch (Exception x)
            {
                logger.Error("Unable to download the model: {0}", x.Message);
            }
        }
Пример #19
0
        /// <summary>
        /// Allows to fetch all models
        /// </summary>
        /// <returns></returns>
        public IEnumerable <VoxelModel> Enumerate()
        {
            using (var reader = Query("SELECT data FROM models"))
            {
                while (reader.Read())
                {
                    VoxelModel model = null;

                    try
                    {
                        model = ((byte[])reader.GetValue(0)).Deserialize <VoxelModel>();
                    }
                    catch (InvalidDataException x)
                    {
                        Logger.Error("Unable to load model: " + x.Message);
                    }

                    if (model != null)
                    {
                        yield return(model);
                    }
                }
            }
        }
Пример #20
0
 private void ExecutePhysics(Vector3Int destroyedPosition, Vector3Int chunkSize, VoxelModel model)
 {
     /*
      * var request = new VoxelPhysicsRequest
      * {
      * initialPosition = destroyedPosition
      * };
      *
      * var result = _voxelPhysicsController.Execute(request, model);
      *
      * if (result.isDestroyed)
      * {
      * var fallingVoxelList = result.fallingVoxelList;
      * var fallingVoxelDictionary = result.fallingVoxelDictionary;
      * var fallingVoxelsBounds = result.fallingVoxelBounds;
      * var fallingVoxelsPivot = fallingVoxelsBounds.Center;
      * var volumeSize = model.Size;
      *
      * var minChunkPosition = new Vector3Int(
      * fallingVoxelsBounds.min.x / chunkSize.x - 1,
      * fallingVoxelsBounds.min.y / chunkSize.y - 1,
      * fallingVoxelsBounds.min.z / chunkSize.z - 1);
      *
      * var maxChunkPosition = new Vector3Int(
      * fallingVoxelsBounds.max.x / chunkSize.x + 1,
      * fallingVoxelsBounds.max.y / chunkSize.y + 1,
      * fallingVoxelsBounds.max.z / chunkSize.z + 1);
      *
      * var chunkLimit = new Vector3Int(
      * volumeSize.x / chunkSize.x,
      * volumeSize.y / chunkSize.y,
      * volumeSize.z / chunkSize.z);
      *
      * for (var x = minChunkPosition.x; x < maxChunkPosition.x; x++) // TODO: to single for loop
      * {
      * for (var y = minChunkPosition.y; y < maxChunkPosition.y; y++)
      * {
      * for (var z = minChunkPosition.z; z < maxChunkPosition.z; z++)
      * {
      * var chunkPosition = new Vector3Int(x, y, z);
      *
      * if (chunkPosition.x >= 0 && chunkPosition.x < chunkLimit.x &&
      *  chunkPosition.y >= 0 && chunkPosition.y < chunkLimit.y &&
      *  chunkPosition.z >= 0 && chunkPosition.z < chunkLimit.z)
      * {
      *  var chunkIndex = VoxelChunkUtility.GetChunkIndex(chunkPosition, chunkSize, volumeSize);
      *
      *  var geometryRequest = TestGeometryRequestUtility.CreateFallingRequest(chunkIndex);
      *  _chunkRequestQueue.Push(geometryRequest);
      * }
      * }
      * }
      * }
      *
      * var fallingVoxelsCount = fallingVoxelList.Count;
      * var chunksCount = (float) (chunkSize.x * chunkSize.y * chunkSize.z);
      * var fallingChunksCount = Mathf.CeilToInt(fallingVoxelsCount / chunksCount);
      * var fallingConstruction = _fallingConstructionFactory.Create(fallingChunksCount);
      * fallingConstruction.SetPosition(fallingVoxelsPivot);
      * fallingConstruction.SetMaterial(_chunkMaterial);
      *
      * _fallingConstructionControllers.Add(fallingConstruction.Id, fallingConstruction);
      *
      * var previousStart = 0;
      * var previousEnd = 0;
      *
      * for (var i = 0; i < fallingChunksCount; i++)
      * {
      * var freeChunkIndex = i;
      *
      * var start = previousEnd;
      * var end = start + (int)chunksCount;
      *
      * var geometryRequest = GetGeometryFallingRequestById(fallingConstruction.Id, freeChunkIndex);
      * geometryRequest.fallingVoxelsList = fallingVoxelList;
      * geometryRequest.fallingVoxelsDictionary = fallingVoxelDictionary;
      * geometryRequest.fallingVoxelsStartIndex = start;
      * geometryRequest.fallingVoxelsEndIndex = end;
      * geometryRequest.pivot = new Vector3(0.5f, 0.5f, 0.5f);
      * geometryRequest.offset = fallingVoxelsPivot;
      *
      * _fallingRequestQueue.Push(geometryRequest);
      *
      * previousStart = start;
      * previousEnd = end;
      * }
      * }*/
 }
Пример #21
0
        public static VoxelGeometryFallingRequest CreateFallingRequest(int constructionIndex, int chunkIndex, VoxelModel model)
        {
            var request = new VoxelGeometryFallingRequest
            {
                constructionIndex     = constructionIndex,
                chunkIndex            = chunkIndex,
                scale                 = 1f,
                pivot                 = new Vector3(0.0f, 0.0f, 0.0f),
                model                 = model,
                faceColorMultipliers  = FaceColorMultipliers,
                edgeColorMultiplier   = new Vector3(0.07f, 0.08f, 0.12f),
                cornerColorMultiplier = new Vector3(-0.14f, -0.25f, -0.4f)
            };

            return(request);
        }
Пример #22
0
 public void Clear()
 {
     model = new VoxelModel();
 }
Пример #23
0
 //Given a VoxelModel, creates the particle systems and writes the particle data to them
 public void Build(VoxelModel model)
 {
     Particles = model.BuildParticles();
 }
Пример #24
0
        public static VoxelGeometryVolumeRequest CreateVolumeRequest(int chunkIndex,
                                                                     Vector3Int chunkSize, VoxelModel model, Vector3Int chunkDimensions)
        {
            var position = VoxelUtility.GetVoxelPosition(chunkIndex, chunkDimensions);

            var request = new VoxelGeometryVolumeRequest
            {
                chunkPosition         = new Vector3Int(position.x, position.y, position.z),
                chunkSize             = chunkSize,
                scale                 = 1f,
                pivot                 = new Vector3(0.0f, 0.0f, 0.0f),
                model                 = model,
                faceColorMultipliers  = FaceColorMultipliers,
                edgeColorMultiplier   = new Vector3(0.07f, 0.08f, 0.12f),
                cornerColorMultiplier = new Vector3(-0.14f, -0.25f, -0.4f)
            };

            return(request);
        }
Пример #25
0
    public static VoxelModel ToModel(this MagicaFile magicaFile, Vector3Int volumeSize)
    {
        var magicaChunks = magicaFile.Chunks;
        var volume       = new VoxelModel(volumeSize, magicaFile.Palette);

        var minPosition = new Vector3Int(int.MaxValue, int.MaxValue, int.MaxValue);
        var maxPosition = new Vector3Int(int.MinValue, int.MinValue, int.MinValue);
        var magicaSize  = new Vector3();

        for (var chunkIndex = 0; chunkIndex < magicaChunks.Length; chunkIndex++)
        {
            var magicaChunk     = magicaChunks[chunkIndex];
            var defaultPosition = magicaChunk.position;
            var chunkSize       = magicaChunk.size;
            var chunkPosition   = defaultPosition - chunkSize / 2;

            magicaChunk.position = chunkPosition;

            for (var i = 0; i < 3; i++)
            {
                if (chunkPosition[i] < minPosition[i])
                {
                    minPosition[i] = chunkPosition[i];
                }
            }

            for (var i = 0; i < 3; i++)
            {
                if (chunkPosition[i] + chunkSize[i] > maxPosition[i])
                {
                    maxPosition[i] = chunkPosition[i] + chunkSize[i];
                }
            }

            for (var i = 0; i < 3; i++)
            {
                magicaSize[i] = maxPosition[i] - minPosition[i];
            }

            magicaChunks[chunkIndex] = magicaChunk;
        }

        foreach (var chunk in magicaChunks)
        {
            var voxels             = chunk.voxels;
            var chunkPosition      = new Vector3Int(chunk.position.x, chunk.position.y, chunk.position.z);
            var positionAdjustment = chunkPosition - minPosition;
            var rotation           = chunk.rotation;
            var size = chunk.size;

            foreach (var magicaVoxel in voxels)
            {
                var voxelPosition = new Vector3Int(magicaVoxel.x, magicaVoxel.y, magicaVoxel.z);

                for (var i = 0; i < 3; i++)
                {
                    var multiplier = rotation[i];

                    if (multiplier != 1)
                    {
                        var value = voxelPosition[i] * multiplier;
                        voxelPosition[i] = size[i] + value - 1;
                    }
                }

                var position = voxelPosition + positionAdjustment;
                var index    = VoxelUtility.GetVoxelIndex(position, volumeSize);

                var voxel = new VoxelEntity
                {
                    colorIndex = magicaVoxel.colorIndex,
                    data       = 100
                };

                volume.SetVoxel(index, voxel);
            }
        }

        return(volume);
    }
Пример #26
0
        private void AddVoxelEntity(EntityCollectionEventArgs e)
        {
            var voxelEntity = e.Entity as IVoxelEntity;

            if (voxelEntity == null)
            {
                return; //My static entity is not a Voxel Entity => Not possible to render it so !!!
            }
            //Create the Voxel Model Instance for the Item
            VisualVoxelModel model = null;

            if (!string.IsNullOrEmpty(voxelEntity.ModelName))
            {
                model = _voxelModelManager.GetModel(voxelEntity.ModelName, false);
            }
            if (model != null && voxelEntity.ModelInstance == null) //The model blueprint is existing, and I need to create an instance of it !
            {
                var treeGrowing = e.Entity as TreeGrowingEntity;
                if (treeGrowing != null)
                {
                    if (treeGrowing.Scale > 0)
                    {
                        // we need to use generated voxel model
                        TreeBpSeed key;
                        key.TreeTypeId = treeGrowing.TreeTypeId;
                        key.TreeSeed   = treeGrowing.TreeRndSeed;

                        VisualVoxelModel treeModel;

                        if (_cachedTrees.TryGetValue(key, out treeModel))
                        {
                            model = treeModel;
                        }
                        else
                        {
                            var voxelModel = VoxelModel.GenerateTreeModel(treeGrowing.TreeRndSeed,
                                                                          _visualWorldParameters.WorldParameters.Configuration.TreeBluePrintsDico[
                                                                              treeGrowing.TreeTypeId]);

                            model = new VisualVoxelModel(voxelModel, _voxelModelManager.VoxelMeshFactory);
                            model.BuildMesh();

                            _cachedTrees.Add(key, model);
                        }
                    }
                }

                var treeSoul = e.Entity as TreeSoul;
                if (treeSoul != null)
                {
                    TreeBpSeed key;
                    key.TreeTypeId = treeSoul.TreeTypeId;
                    key.TreeSeed   = treeSoul.TreeRndSeed;

                    _cachedTrees.Remove(key);
                }


                voxelEntity.ModelInstance = new VoxelModelInstance(model.VoxelModel);

                //Assign state in case of growing entity !
                var growingEntity = e.Entity as PlantGrowingEntity;
                if (growingEntity != null)
                {
                    voxelEntity.ModelInstance.SetState(growingEntity.GrowLevels[growingEntity.CurrentGrowLevelIndex].ModelState);
                }

                var visualVoxelEntity = new VisualVoxelEntity(voxelEntity, _voxelModelManager);
                //Get default world translation
                Matrix instanceTranslation = Matrix.Translation(voxelEntity.Position.AsVector3());

                //Apply special rotation to the creation instance
                Quaternion instanceRotation = Quaternion.Identity;
                if (voxelEntity is IRndYRotation && ((IRndYRotation)voxelEntity).RndRotationAroundY)
                {
                    instanceRotation = Quaternion.RotationAxis(Vector3.UnitY, (float)(_rnd.NextDouble() * MathHelper.TwoPi));
                }
                else if (voxelEntity is IItem)
                {
                    var item = voxelEntity as IItem;
                    instanceRotation = item.Rotation;
                }

                //Apply special scaling to created entity (By default all blue print are 16 times too big.
                Matrix instanceScaling = Matrix.Scaling(1.0f / 16.0f);

                if (treeGrowing != null && treeGrowing.Scale > 0)
                {
                    instanceScaling = Matrix.Scaling(treeGrowing.Scale);
                }

                //Create the World transformation matrix for the instance.
                //We take the Model instance world matrix where we add a Rotation and scaling proper to the instance
                visualVoxelEntity.VoxelEntity.ModelInstance.World    = instanceScaling * instanceTranslation;
                visualVoxelEntity.VoxelEntity.ModelInstance.Rotation = instanceRotation;

                var result = GetCube(visualVoxelEntity.VoxelEntity.Position.ToCubePosition());


                if (result.IsValid)
                {
                    visualVoxelEntity.BlockLight = result.Cube.EmissiveColor;
                }
                else
                {
                    visualVoxelEntity.BlockLight = new ByteColor(255, 255, 255, 255);
                }


                if (visualVoxelEntity.VisualVoxelModel.Initialized == false)
                {
                    visualVoxelEntity.VisualVoxelModel.BuildMesh();
                }

                if (voxelEntity.ModelInstance.CanPlay("Idle"))
                {
                    voxelEntity.ModelInstance.Play("Idle", true);
                }

                lock (_syncRoot)
                {
                    List <VisualVoxelEntity> list;
                    if (_visualVoxelEntities.TryGetValue(voxelEntity.ModelName, out list))
                    {
                        list.Add(visualVoxelEntity);
                    }
                    else
                    {
                        _visualVoxelEntities.Add(voxelEntity.ModelName, new List <VisualVoxelEntity> {
                            visualVoxelEntity
                        });
                    }
                }

                var lightEntity = e.Entity as ILightEmitterEntity;
                if (e.AtChunkCreationTime == false && lightEntity != null)
                {
                    //Get the Cube where is located the entity
                    var entityWorldPosition = lightEntity.Position;
                    var entityBlockPosition = new Vector3I(MathHelper.Floor(entityWorldPosition.X),
                                                           MathHelper.Floor(entityWorldPosition.Y),
                                                           MathHelper.Floor(entityWorldPosition.Z));
                    //new TerraCubeWithPosition(entityBlockPosition, WorldConfiguration.CubeId.Air, _visualWorldParameters.WorldParameters.Configuration),
                    this.UpdateOrder = 1;
                    var cubeRange = new Range3I
                    {
                        Position = new Vector3I(entityBlockPosition.X, 0, entityBlockPosition.Z),
                        Size     = Vector3I.One
                    };
                    _chunkEntityImpactManager.CheckImpact(this, cubeRange);
                }
            }
        }
Пример #27
0
 public void Initialize(VoxelModel model)
 {
 }
Пример #28
0
 public void Save(VoxelModel model)
 {
     model.SaveToFile(model.Name + ".uvm");
 }
Пример #29
0
 public VisualVoxelModel(VoxelModel model, VoxelMeshFactory voxelMeshFactory)
 {
     _model            = model;
     _voxelMeshFactory = voxelMeshFactory;
 }
Пример #30
0
        public void EntityGrowCheck(UtopiaTime now, GrowingEntity entity, ServerChunk chunk, Random random)
        {
            if (entity.LastGrowUpdate.IsZero)
            {
                return;
            }

            var checkTimeSpan = now - entity.LastGrowUpdate;

            bool updated;
            bool rotten;

            // grow time left at the current season
            var tillTheEndOfSeason = UtopiaTimeSpan.FromSeasons(1d - entity.LastGrowUpdate.TotalSeasons % 1d);

            if (checkTimeSpan <= tillTheEndOfSeason)
            {
                // small grow update
                updated = GrowSeasonLogic(entity, now.Season, checkTimeSpan, random, chunk, out rotten);

                if (rotten)
                {
                    return;
                }
            }
            else
            {
                // grow at the end of the first season
                updated = GrowSeasonLogic(entity, now.Season, tillTheEndOfSeason, random, chunk, out rotten);

                if (rotten)
                {
                    return;
                }

                // align time to the beginning of next season
                checkTimeSpan -= tillTheEndOfSeason;

                while (checkTimeSpan.TotalSeconds > 0)
                {
                    var seasonCheckSpan = checkTimeSpan.TotalSeasons > 0 ? UtopiaTimeSpan.FromSeasons(1) : checkTimeSpan;

                    updated = GrowSeasonLogic(entity, (now - checkTimeSpan).Season, seasonCheckSpan, random, chunk, out rotten) || updated;

                    if (rotten)
                    {
                        return;
                    }

                    checkTimeSpan -= seasonCheckSpan;
                }
            }

            if (updated)
            {
                if (entity is PlantGrowingEntity)
                {
                    if (chunk != null)
                    {
                        chunk.Entities.RemoveById(entity.StaticId);
                        chunk.Entities.Add(entity);
                    }
                }
                var tree = entity as TreeGrowingEntity;
                if (tree != null)
                {
                    var treeBlueprint = _server.EntityFactory.Config.TreeBluePrintsDico[tree.TreeTypeId];

                    if (tree.CurrentGrowTime > treeBlueprint.GrowTime)
                    {
                        // the tree is ready

                        var model = VoxelModel.GenerateTreeModel(tree.TreeRndSeed, treeBlueprint);

                        // create tree blocks
                        var rootOffset = model.States[0].PartsStates[0].Translation;
                        var cursor     = _server.LandscapeManager.GetCursor(tree.Position);
                        var frame      = model.Frames[0];
                        var range      = new Range3I(new Vector3I(), frame.BlockData.ChunkSize);

                        using (cursor.TransactionScope())
                        {
                            foreach (var position in range)
                            {
                                var value = frame.BlockData.GetBlock(position);
                                if (value == 0)
                                {
                                    continue;
                                }
                                var blockType = value == 1 ? treeBlueprint.TrunkBlock : treeBlueprint.FoliageBlock;
                                var worldPos  = (Vector3I)(tree.Position + rootOffset) + position;
                                cursor.GlobalPosition = worldPos;
                                if (cursor.Read() == WorldConfiguration.CubeId.Air)
                                {
                                    cursor.Write(blockType);
                                }
                            }
                        }

                        // create tree soul
                        var soul = _server.EntityFactory.CreateEntity <TreeSoul>();
                        soul.Position    = tree.Position;
                        soul.TreeRndSeed = tree.TreeRndSeed;
                        soul.TreeTypeId  = tree.TreeTypeId;

                        chunk.Entities.Add(soul);

                        // remove the growing tree
                        chunk.Entities.RemoveById(tree.StaticId);
                    }
                    else
                    {
                        // just make the model bigger
                        tree.Scale = (float)tree.CurrentGrowTime.TotalSeconds / treeBlueprint.GrowTime.TotalSeconds;
                        chunk.Entities.RemoveById(tree.StaticId);
                        chunk.Entities.Add(tree);
                    }
                }
            }
        }
Пример #31
0
Файл: View.cs Проект: gdgeek/fly
 public VoxelMesh createMesh(VoxelModel model)
 {
     VoxelMesh mesh =  _manager.create (model);
     _cage.push (mesh);
     return mesh;
 }