Ejemplo n.º 1
0
    public GameObject spawnPrefab(GameObject g, PrefabData prefabData, Transform parent = null)
    {
        Vector3    pos      = new Vector3(prefabData.position.x, prefabData.position.y, prefabData.position.z);
        Vector3    scale    = new Vector3(prefabData.scale.x, prefabData.scale.y, prefabData.scale.z);
        Quaternion rotation = Quaternion.Euler(new Vector3(prefabData.rotation.x, prefabData.rotation.y, prefabData.rotation.z));


        GameObject newObj = Instantiate(g, pos + getMapOffset(), rotation, parent);

        newObj.transform.localScale = scale;

        return(newObj);
    }
Ejemplo n.º 2
0
        private IEnumerable <Entity> SpawnEntitiesUsingRandomDistribution(EntitySpawnPoint entitySpawnPoint, DstData dstData, DeterministicBatchGenerator deterministicBatchGenerator)
        {
            List <PrefabData> allowedPrefabs = filterAllowedPrefabs(dstData.prefabs, entitySpawnPoint);

            float rollingProbabilityDensity = allowedPrefabs.Sum(prefab => prefab.probability / entitySpawnPoint.Density);

            if (rollingProbabilityDensity <= 0)
            {
                yield break;
            }

            double randomNumber = deterministicBatchGenerator.NextDouble();

            if (rollingProbabilityDensity > 1f)
            {
                randomNumber *= rollingProbabilityDensity;
            }

            double     rollingProbability = 0;
            PrefabData selectedPrefab     = allowedPrefabs.FirstOrDefault(prefab =>
            {
                if (prefab.probability == 0)
                {
                    return(false);
                }

                float probabilityDensity = prefab.probability / entitySpawnPoint.Density;

                rollingProbability += probabilityDensity;

                return(rollingProbability >= randomNumber);
            });

            WorldEntityInfo worldEntityInfo;

            if (!ReferenceEquals(selectedPrefab, null) && worldEntitiesByClassId.TryGetValue(selectedPrefab.classId, out worldEntityInfo))
            {
                for (int i = 0; i < selectedPrefab.count; i++)
                {
                    IEnumerable <Entity> entities = CreateEntityWithChildren(entitySpawnPoint,
                                                                             worldEntityInfo.techType,
                                                                             worldEntityInfo.cellLevel,
                                                                             selectedPrefab.classId,
                                                                             deterministicBatchGenerator);
                    foreach (Entity entity in entities)
                    {
                        yield return(entity);
                    }
                }
            }
        }
Ejemplo n.º 3
0
    private void placeObject()
    {
        // Get schema for selected tile
        Asset tileSchema = getTileSchema(activeTile.name);

        Debug.Log(tileSchema);
        foreach (string tile_name in tileSchema.unstackable) // Satisfy tile overlap restrictions as defined in schema
        {
            // Raycast current tile stack
            Vector2      mousePos2D = new Vector2(gridPoint.x, gridPoint.y);
            Collider2D[] hitInfo    = Physics2D.OverlapPointAll(mousePos2D);
            foreach (Collider2D collider in hitInfo)
            {
                if (collider.gameObject.name == tile_name)
                {
                    Debug.Log(activeTile.name + " cannot be placed ontop of " + tile_name + "!");
                    return;
                }
            }
        }

        // Satisfy tile number limit in scene
        if (tileSchema.limit > 0) // limit = -1 means no limit
        {
            int count = 0;
            foreach (object obj in FindObjectsOfType <GameObject>())
            {
                if (((GameObject)obj).name == activeTile.name && ((GameObject)obj).layer != 2)  // Ignore objects in ignoreRaycast layer (cursor)
                {
                    count++;
                }
            }
            if (count >= tileSchema.limit)
            {
                Debug.Log("Limit reached for number of " + activeTile.name + " tiles!");
                return;
            }
        }

        GameObject go = Instantiate(activeTile, gridPoint, Quaternion.Euler(0, 0, 90 * tileRotationCount));

        go.name = activeTile.name;
        environmentList.Add(new Tuple <string, Vector3>("A Tile", gridPoint));

        PrefabData prefabData = new PrefabData();

        prefabData.name     = go.name;
        prefabData.position = gridPoint;
        prefabData.rotation = go.transform.rotation;
    }
Ejemplo n.º 4
0
    public void PopulateSpot(List <Coord> spots, PrefabSize size)
    {
        List <PrefabData>          prefabsAvaliable = new List <PrefabData>();
        List <EssentialPrefabData> essentials       = new List <EssentialPrefabData>();
        float combinedDensity = 0;

        foreach (EssentialPrefabData prefab in essentialLevelPrefabs)
        {
            if (prefab.prefabSize == size && spots.Count > 0)
            {
                int        randomChoice = Random.Range(0, spots.Count - 1);
                Vector3    position     = CoordToWorldSpace(spots[randomChoice]) + new Vector3(Random.Range(-prefab.prefabPlacementRandomness / 2, prefab.prefabPlacementRandomness / 2), 0, Random.Range(-prefab.prefabPlacementRandomness / 2, prefab.prefabPlacementRandomness / 2));
                Quaternion rotation     = prefab.RandomRotationOnY ? Quaternion.Euler(0, Random.Range(0, 360), 0) : Quaternion.identity;
                Instantiate(prefab.prefab, position, rotation, levelObjectHolder);
                spots.RemoveAt(randomChoice);
            }
        }

        foreach (PrefabData prefab in levelPrefabs)
        {
            if (prefab.prefabSize == size)
            {
                prefabsAvaliable.Add(prefab);
                combinedDensity += prefab.levelDensity;
            }
        }
        if (prefabsAvaliable.Count > 0)
        {
            foreach (Coord spot in spots)
            {
                float      randomChoice   = Random.Range(0, combinedDensity);
                PrefabData prefabChoice   = null;
                float      currentDensity = 0;
                foreach (PrefabData prefab in prefabsAvaliable)
                {
                    if (randomChoice <= currentDensity + prefab.levelDensity)
                    {
                        prefabChoice = prefab;
                        break;
                    }
                    currentDensity += prefab.levelDensity;
                }
                Vector3    position = CoordToWorldSpace(spot) + new Vector3(Random.Range(-prefabChoice.prefabPlacementRandomness / 2, prefabChoice.prefabPlacementRandomness / 2), 0, Random.Range(-prefabChoice.prefabPlacementRandomness / 2, prefabChoice.prefabPlacementRandomness / 2));;
                Quaternion rotation = prefabChoice.RandomRotationOnY?Quaternion.Euler(0, Random.Range(0, 360), 0):Quaternion.identity;
                Instantiate(prefabChoice.prefab, position, rotation, levelObjectHolder);
            }
        }
    }
Ejemplo n.º 5
0
        private IEnumerable <Entity> SpawnEntitiesUsingRandomDistribution(EntitySpawnPoint entitySpawnPoint, DstData dstData)
        {
            float rollingProbabilityDensity = dstData.prefabs.Sum(prefab => prefab.probability / entitySpawnPoint.Density);

            if (rollingProbabilityDensity <= 0)
            {
                yield break;
            }

            double randomNumber = random.NextDouble();

            if (rollingProbabilityDensity > 1f)
            {
                randomNumber *= rollingProbabilityDensity;
            }

            double     rollingProbability = 0;
            PrefabData selectedPrefab     = dstData.prefabs.FirstOrDefault(prefab =>
            {
                if (prefab.probability == 0)
                {
                    return(false);
                }

                float probabilityDensity = prefab.probability / entitySpawnPoint.Density;
                rollingProbability      += probabilityDensity;
                bool isValidSpawn        = IsValidSpawnType(prefab.classId, entitySpawnPoint.CanSpawnCreature);
                return(rollingProbability >= randomNumber && isValidSpawn);
            });

            WorldEntityInfo worldEntityInfo;

            if (!ReferenceEquals(selectedPrefab, null) && worldEntitiesByClassId.TryGetValue(selectedPrefab.classId, out worldEntityInfo))
            {
                for (int i = 0; i < selectedPrefab.count; i++)
                {
                    IEnumerable <Entity> entities = CreateEntityWithChildren(entitySpawnPoint,
                                                                             worldEntityInfo.techType,
                                                                             worldEntityInfo.cellLevel,
                                                                             selectedPrefab.classId);
                    foreach (Entity entity in entities)
                    {
                        yield return(entity);
                    }
                }
            }
        }
Ejemplo n.º 6
0
    public void SaveLevel()
    {
        LevelData levelData = new LevelData();

        levelData.prefabDataList = new List <PrefabData>();
        GameObject[] sceneObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
        foreach (object go in sceneObjects)
        {
            if (isLoadable((GameObject)go) && ((GameObject)go).layer != 2)
            {
                // Get schema for selected tile
                Asset tileSchema = getTileSchema(((GameObject)go).name);

                string     name     = ((GameObject)go).name;
                Quaternion rotation = ((GameObject)go).transform.rotation;
                Vector2    position = ((GameObject)go).transform.position;

                PrefabData prefabData = new PrefabData();
                prefabData.name     = name;
                prefabData.position = position;
                prefabData.rotation = rotation;

                List <MetaData> metaDataList = new List <MetaData>();
                foreach (Attribute attribute in tileSchema.attributes)
                {
                    MetaData metadata = new MetaData();
                    string   value    = getFieldValue((GameObject)go, attribute.component, attribute.field);
                    metadata.component   = attribute.component;
                    metadata.field_name  = attribute.field;
                    metadata.field_value = value;
                    metaDataList.Add(metadata);
                }
                prefabData.metadata = metaDataList.ToArray();
                levelData.prefabDataList.Add(prefabData);
            }
        }
        Debug.Log("Saved Level");
        string levelDataJson = JsonUtility.ToJson(levelData);

        Debug.Log(levelDataJson);

#if !UNITY_EDITOR && UNITY_WEBGL // Run this in production build
        SaveLevelData(levelDataJson);
#endif
    }
Ejemplo n.º 7
0
    /// <summary>
    /// Загружаем данные о префабах форм
    /// </summary>
    private void LoadPrefabPaths()
    {
        prefabPaths.Clear();
        formPaths.Clear();

        TextAsset  textAsset  = Resources.Load <TextAsset>("PrefabData");
        PrefabData prefabData = JsonUtility.FromJson <PrefabData>(textAsset.text);

        for (int i = 0; i < prefabData.framePaths.Count; i++)
        {
            prefabPaths.Add(prefabData.framePaths[i].prefabName, prefabData.framePaths[i].path);
        }

        for (int i = 0; i < prefabData.formPaths.Count; i++)
        {
            formPaths.Add(prefabData.formPaths[i].prefabName, prefabData.formPaths[i].path);
        }
    }
Ejemplo n.º 8
0
        private void AddCoresToPrefab(IEnumerable <GameCell> cells, PrefabData prefab)
        {
            int numCores = _randomization.GetInt(prefab.MinCores, prefab.MaxCores);

            if (numCores > 0)
            {
                var elements = new List <EncounterElement>(numCores);
                for (int i = 0; i < numCores; i++)
                {
                    elements.Add(new EncounterElement {
                        ObjectType = GameObjectType.Core, ObjectId = Actors.Core
                    });
                }


                EncountersService.AddEncounterElementsToCells(elements, cells, _randomization);
            }
        }
Ejemplo n.º 9
0
        public static void CreateAvatarAssetBundle(string assetBundlePath, GameObject avatarObject, string headObjectName, string haircutObjectName)
        {
            string prefabDir = "Assets/itseez3d_prefabs";

            Directory.CreateDirectory(prefabDir);

            PrefabData prefabData = CreatePrefab(prefabDir, avatarObject, headObjectName, haircutObjectName);

            UnityEngine.Object[] selection = new UnityEngine.Object[] { prefabData.createdPrefab };
            UnityEditor.BuildPipeline.BuildAssetBundle(prefabData.createdPrefab, selection, assetBundlePath,
                                                       UnityEditor.BuildAssetBundleOptions.CollectDependencies | UnityEditor.BuildAssetBundleOptions.CompleteAssets,
                                                       UnityEditor.BuildTarget.StandaloneWindows);

            foreach (string asset in prefabData.savedAssets)
            {
                UnityEditor.AssetDatabase.DeleteAsset(asset);
            }
        }
Ejemplo n.º 10
0
    public PrefabData addPrefab(string keyUrl, object resouce, bool DonnotClear = false)
    {
        if (pool.ContainsKey(keyUrl))
        {
            if (pool[keyUrl] is ErrorData)
            {
                pool.Remove(keyUrl);
            }
            else
            {
                Debug.Log("重复添加:" + keyUrl);
                return(pool[keyUrl] as PrefabData);
            }
        }
        PrefabData LoadPoolData = new PrefabData(keyUrl, resouce, DonnotClear);

        pool.Add(keyUrl, LoadPoolData);
        return(LoadPoolData);
    }
Ejemplo n.º 11
0
    public PrefabData addPrefab(string url, object resouce)
    {
        if (poolDic.ContainsKey(url))
        {
            if (poolDic[url] is ErrorData)
            {
                poolDic.Remove(url);
            }
            else
            {
                Debug.LogWarningFormat("重复添加资源到对象池{0}", url);
                return(poolDic[url] as PrefabData);
            }
        }
        PrefabData loadPoolData = new PrefabData(url, resouce);

        poolDic.Add(url, loadPoolData);
        return(loadPoolData);
    }
Ejemplo n.º 12
0
    void OnGUI()
    {
        if(manager == null) {
            Type asset = Type.GetType("AccessorManager");
            if(asset == null) return;
            manager = (IAccessorManager) Activator.CreateInstance(asset);
        }

        GameObject gameObject = Selection.activeGameObject;
        if(!gameObject){
            return;
        }

        TableViewerInfo viewerInfo = gameObject.GetComponent<TableViewerInfo>();
        if(!viewerInfo){
            return;
        }

        string folderPath = viewerInfo.folderPath;

        IList<ICellData> datas = new List<ICellData>();

        try {
            foreach(string filePath in Directory.GetFiles(folderPath)) {
                GameObject prefab = (GameObject) AssetDatabase.LoadAssetAtPath(filePath, typeof(GameObject));
                if(prefab != null) {
                    IDataAccessor accessor =  manager.GetDataAccessor(prefab);
                    ICellData data = new PrefabData(accessor, prefab, folderPath);
                    datas.Add (data);
                }
            }

            IContentProvider contentProvider = new ContentProvider(datas);
            viewer.ContentProvider = contentProvider;

            ICellProvider cellProvider = new TableCellProvider(viewerInfo.labels);
            viewer.CellProvider = cellProvider;

            viewer.OnGUI();
        } catch {
        }
    }
        public static VehicleInfo GetVehicleInfo(ref Randomizer randomizer, ItemClass m_class, ushort lineID, string prefabName)
        {
            PrefabData prefabData = Array.Find(VehiclePrefabs.instance.GetPrefabs(m_class.m_service, m_class.m_subService, m_class.m_level),
                                               item => item.ObjectName == prefabName);

            if (prefabData != null)
            {
                return(PrefabCollection <VehicleInfo> .GetPrefab((uint)prefabData.PrefabDataIndex));
            }
            Utils.LogWarning((object)("Unknown prefab: " + prefabName));
            VehicleManager instance = Singleton <VehicleManager> .instance;

            instance.RefreshTransferVehicles();

            int service    = (int)m_class.m_service;
            int subService = (int)m_class.m_subService;
            int level      = (int)m_class.m_level;

            return(instance.GetRandomVehicleInfo(ref randomizer, (ItemClass.Service)service, (ItemClass.SubService)subService, (ItemClass.Level)level));
        }
Ejemplo n.º 14
0
            /*
             * ボーンを移動する前に実行される
             * SetuperExpandOptionから呼び出し
             */
            public void BeforeMoveArmature()
            {
                if (expandOption.original_bones == null)
                {
                    return;
                }
                for (int i = 0; i < expandOption.original_bones.Length; i++)
                {
                    OriginalBone originalBone = expandOption.original_bones[i];

                    Transform fromBone = PrefabData.GetCloth().transform.Find(originalBone.from);
                    Transform toBone   = PrefabData.GetAvatar().transform.Find(originalBone.to);

                    if (fromBone != null && toBone != null)
                    {
                        AppendIDToBone(fromBone);

                        fromBone.SetParent(toBone);
                    }
                }
            }
Ejemplo n.º 15
0
    public void Save(ref WorldSerialization blob)
    {
        ActionProgressBar.UpdateProgress("Saving Prefabs", 0f);

        List <ProtoBuf.PrefabData> prefabList = new List <ProtoBuf.PrefabData>();

        PrefabData[] prefabData = UnityEngine.Object.FindObjectsOfType <PrefabData>();
        if (prefabData?.Length > 0)
        {
            for (int i = 0; i < prefabData.Length; i++)
            {
                PrefabData data = prefabData[i];

                if (prefabData == null || data.gameObject == null)
                {
                    continue;
                }

                prefabList.Add(data.GetPrefabData());
            }
        }

        blob.world.prefabs = prefabList;
    }
Ejemplo n.º 16
0
        private static PrefabData CreatePrefab(string prefabDir, GameObject avatarObject, string headObjectName, string haircutObjectName)
        {
            PrefabData prefabData = new PrefabData();

            avatarObject = GameObject.Instantiate(avatarObject);
            GameObject headObject = GetChildByName(avatarObject, headObjectName);
            GameObject hairObject = GetChildByName(avatarObject, haircutObjectName);

            if (headObject != null)
            {
                SkinnedMeshRenderer headMeshRenderer = headObject.GetComponentInChildren <SkinnedMeshRenderer> ();
                headMeshRenderer.material.mainTexture = InstantiateAndSaveAsset(headMeshRenderer.material.mainTexture, Path.Combine(prefabDir, "head_texture.mat"), ref prefabData.savedAssets);
                headMeshRenderer.material             = InstantiateAndSaveAsset(headMeshRenderer.material, Path.Combine(prefabDir, "head_material.mat"), ref prefabData.savedAssets);
                headMeshRenderer.sharedMesh           = InstantiateAndSaveAsset(headMeshRenderer.sharedMesh, Path.Combine(prefabDir, "headMesh.asset"), ref prefabData.savedAssets);
            }

            if (hairObject != null)
            {
                MeshFilter   hairMeshFilter   = hairObject.GetComponentInChildren <MeshFilter> ();
                MeshRenderer hairMeshRenderer = hairObject.GetComponentInChildren <MeshRenderer> ();
                hairMeshRenderer.material.mainTexture = InstantiateAndSaveAsset(hairMeshRenderer.material.mainTexture, Path.Combine(prefabDir, "hair_texture.mat"), ref prefabData.savedAssets);
                hairMeshRenderer.material             = InstantiateAndSaveAsset(hairMeshRenderer.material, Path.Combine(prefabDir, "hair_material.mat"), ref prefabData.savedAssets);
                hairMeshFilter.mesh = InstantiateAndSaveAsset(hairMeshFilter.mesh, Path.Combine(prefabDir, "hairMesh.asset"), ref prefabData.savedAssets);
            }

            UnityEditor.AssetDatabase.SaveAssets();

            GameObject.Destroy(avatarObject.GetComponentInChildren <RotateByMouse> ());

            string prefabPath = prefabDir + "/avatar.prefab";

            prefabData.createdPrefab = UnityEditor.PrefabUtility.CreatePrefab(prefabPath, avatarObject);
            prefabData.savedAssets.Add(prefabPath);
            GameObject.Destroy(avatarObject);
            return(prefabData);
        }
Ejemplo n.º 17
0
    public void load()
    {
        string     encodedString = File.ReadAllText(Application.dataPath + "/saveFile.json");
        JSONObject inpObject     = new JSONObject(encodedString);

        PrefabData inpData = new PrefabData();
        GameObject forTemp = new GameObject();

        for (int i = 0; i < 10; i++)
        {
            //each Data [0]=name [1,2,3]=position [4]=grav;

            if (inpObject[0][i][0] != null)
            {
                string name = inpObject[0][i][0].Print();
                //set position
                float px = inpObject[0][i][1].n;
                float py = inpObject[0][i][2].n;
                float pz = inpObject[0][i][3].n;
                //set rotation
                float rx = inpObject[0][i][4].n;
                float ry = inpObject[0][i][5].n;
                float rz = inpObject[0][i][6].n;
                // set scale
                float sx = inpObject[0][i][7].n;
                float sy = inpObject[0][i][8].n;
                float sz = inpObject[0][i][9].n;
                // set grav
                float grav = inpObject[0][i][10].n;

                //clear name
                string tempName = name;
                tempName = name.Replace("\"", "");
                name     = tempName;
                tempName = name.Replace("(", "");
                name     = tempName;
                tempName = name.Replace(")", "");
                name     = tempName;
                for (int zz = 0; zz < 10; zz++)
                {
                    tempName = name.Replace(zz.ToString(), "");
                    name     = tempName;
                }

                for (int c = 0; c < 10; c++)
                {
                    if (name == "Floor")
                    {
                        forTemp = Obj[0];
                    }
                    else if (name == "Trees")
                    {
                        forTemp = Obj[1];
                    }
                    else if (name == "Sepiroth Model")
                    {
                        forTemp = Obj[2];
                    }
                    else
                    {
                        break;
                    }
                }

                //temp = Object
                GameObject temp = Instantiate(forTemp) as GameObject;
                temp.transform.position    = new Vector3(px, py, pz);
                temp.transform.eulerAngles = new Vector3(rx, ry, rz);
                temp.transform.localScale  = new Vector3(sx, sy, sz);
                //Link Script Panel to Object
                GameObject   sp = Instantiate(ScriptPanel) as GameObject;
                ScriptActive sa = temp.GetComponent <ScriptActive>();
                sa.scriptBox = sp;
                //set grav


                //Add slot and Script to Panel
                int j = 0;

                while (inpObject[0][i][12][j]) // check scriptSlot if (it == null) -> stop
                {
                    //clear name
                    string word    = inpObject[0][i][12][j].Print();
                    string wordCut = word.Replace("(Clone)", "");
                    word    = wordCut;
                    wordCut = word.Replace("\"", "");
                    word    = wordCut;

                    //script
                    int choose = 0;
                    if (wordCut == "Scriptbox_Button")
                    {
                        choose = 0;
                    }
                    else if (wordCut == "Scriptbox_Movement")
                    {
                        choose = 1;
                    }
                    else if (wordCut == "Scriptbox_While")
                    {
                        choose = 2;
                    }
                    else
                    {
                    }

                    if (j == 1) //first
                    {
                        //add script
                        GameObject script = Instantiate(scriptList[choose], sp.transform); // create script from name and set its parent (scriptbox)
                    }
                    else
                    {
                        //add prev slot
                        //add script
                        GameObject slotNow = Instantiate(slot, sp.transform);
                        GameObject script  = Instantiate(scriptList[choose], sp.transform); // create script from name and set its parent (scriptbox)
                    }
                    //add slot
                    GameObject slotLast = Instantiate(slot, sp.transform);
                    j++;
                }
            }
            else
            {
                break;
            }

            for (int j = 0; j < 5; j++)
            {
                /*
                 * if (inpObject[0][i][j])
                 * {
                 *  Debug.Log(inpObject[0][i][j]);
                 * }
                 * else
                 * {
                 *  break;
                 * }
                 */
            }
        }
    }
Ejemplo n.º 18
0
    void Awake()
    {
        cam = Camera.main.GetComponent <EditorCamera>();

        // load in all the data for all the levels
        DirectoryInfo dirInfo = new DirectoryInfo(Application.streamingAssetsPath + "\\Levels\\");

        FileInfo[]      fileInfos = dirInfo.GetFiles("*.dat");
        BinaryFormatter bf        = new BinaryFormatter();
        Dictionary <string, LevelData> levelDatas = new Dictionary <string, LevelData>();
        List <string> prefabIndexes = new List <string>();

        List <int[]> prefabTop3 = new List <int[]>();

        for (int i = 0; i < fileInfos.Length; i++)
        {
            FileStream file = fileInfos[i].Open(FileMode.Open);
            LevelData  ld   = (LevelData)bf.Deserialize(file);
            levelDatas.Add(ld.name, ld);
            file.Close();
            // go through prefabs of every level to assign integers instead of string names, for efficient searching
            // instantiate empty top 3 array for later
            foreach (PrefabData pd in ld.prefabDatas)
            {
                if (!prefabIndexes.Contains(pd.name))
                {
                    prefabIndexes.Add(pd.name);
                    prefabTop3.Add(new int[] { 0, 0, 0 });
                }
                pd.index = prefabIndexes.IndexOf(pd.name);
            }
        }

        /******
         * Dictionary<string, LevelData> levelDatas can now used here for seed generation
         * String names may be useful for generator but makes it less efficient to search through later
         * This will eventually be changed into simple LevelData array levels
         *******/

        levels = new LevelData[levelDatas.Count];
        int index = 0;

        foreach (KeyValuePair <string, LevelData> ld in levelDatas)
        {
            levels[index] = ld.Value;
            index++;
        }

        prevIndexes = new int[5] {
            -1, -1, -1, -1, -1
        };
        level1Index = GetNextLevel();
        level2Index = GetNextLevel();
        level3Index = GetNextLevel();

        // go through every level to see how many of each prefab we need
        // only three levels will ever be active at one time so get top 3 amounts of each prefab
        foreach (LevelData ld in levels)
        {
            int[] prefabCount = new int[prefabIndexes.Count];
            for (int i = 0; i < prefabCount.Length; i++)
            {
                prefabCount[i] = 0;
            }
            foreach (PrefabData pd in ld.prefabDatas)
            {
                prefabCount[pd.index]++;
            }
            for (int i = 0; i < prefabCount.Length; i++)
            {
                int first    = prefabTop3[i][0];
                int second   = prefabTop3[i][1];
                int third    = prefabTop3[i][2];
                int smallest = Mathf.Min(first, Mathf.Min(second, third));
                if (prefabCount[i] > smallest)
                {
                    if (smallest == first)
                    {
                        prefabTop3[i][0] = prefabCount[i];
                    }
                    else if (smallest == second)
                    {
                        prefabTop3[i][1] = prefabCount[i];
                    }
                    else
                    {
                        prefabTop3[i][2] = prefabCount[i];
                    }
                }
            }
        }

        // instantiate all prefabs at corresponding index
        levelPieces = new LevelPiece[prefabIndexes.Count][];
        Dictionary <string, GameObject> prefabs = PrefabLoader.LoadAllPrefabsOfType <MonoBehaviour>("Assets/Resources/LevelPieces");

        for (int i = 0; i < prefabIndexes.Count; i++)
        {
            levelPieces[i] = new LevelPiece[prefabTop3[i][0] + prefabTop3[i][1] + prefabTop3[i][2]];
            for (int j = 0; j < levelPieces[i].Length; j++)
            {
                levelPieces[i][j]        = new LevelPiece();
                levelPieces[i][j].prefab = Instantiate(prefabs[prefabIndexes[i]]);
                levelPieces[i][j].prefab.SetActive(false);
                // when instantiated every name has (1), (2), etc so remove that
                levelPieces[i][j].prefab.name = levelPieces[i][j].prefab.name.Split('(')[0];
                // get references to transform and script so we don't have to get them each time
                levelPieces[i][j].transform = levelPieces[i][j].prefab.transform;
                levelPieces[i][j].script    = levelPieces[i][j].prefab.GetComponent <LevelPieceScript>();
                levelPieces[i][j].parent    = -1;
            }
        }

        LevelData level1 = levels[level1Index];
        LevelData level2 = levels[level2Index];
        LevelData level3 = levels[level3Index];

        for (int i = 0; i < level1.prefabDatas.Length; i++)
        {
            PrefabData pd = level1.prefabDatas[i];
            PlaceLevelPiece(level1Index, pd.index, 0, 0, pd.positionX, pd.positionY, pd.positionZ,
                            pd.rotationX, pd.rotationY, pd.rotationZ, pd.scaleX, pd.scaleY, pd.scaleZ, pd.extraValues);
        }

        for (int i = 0; i < level2.prefabDatas.Length; i++)
        {
            PrefabData pd = level2.prefabDatas[i];
            PlaceLevelPiece(level2Index, pd.index, level1.endpointX, level1.endpointY, pd.positionX, pd.positionY, pd.positionZ,
                            pd.rotationX, pd.rotationY, pd.rotationZ, pd.scaleX, pd.scaleY, pd.scaleZ, pd.extraValues);
        }

        for (int i = 0; i < level3.prefabDatas.Length; i++)
        {
            PrefabData pd = level3.prefabDatas[i];
            PlaceLevelPiece(level3Index, pd.index, level1.endpointX + level2.endpointX, level2.endpointY, pd.positionX,
                            pd.positionY, pd.positionZ, pd.rotationX, pd.rotationY, pd.rotationZ, pd.scaleX, pd.scaleY, pd.scaleZ, pd.extraValues);
        }
    }
 /// <summary>
 /// Checks to see if a prefab can fit before placement
 /// </summary>
 /// <param name="position">Prospected position</param>
 /// <param name="prefab">Prefab</param>
 /// <returns></returns>
 public bool IsPrefabValidPlacement(Vector2 position, PrefabData prefab)
 {
     return(new bool());
 }
Ejemplo n.º 20
0
        public static void ProcessIndividualObject(GameObject Object, ObjectMapData ObjectMapData,
                                                   Vector3?CoordinateOverride = null, bool UseInstance = false)
        {
            var RuntimeSpawned = Object.GetComponent <RuntimeSpawned>();

            if (RuntimeSpawned != null)
            {
                return;
            }

            PrefabData Prefab = new PrefabData();


            var Tracker = Object.GetComponent <PrefabTracker>();

            if (Tracker != null)
            {
                Prefab.PrefabID = Tracker.ForeverID;
                Prefab.ID       = IDStatic;
                IDStatic++;
                Prefab.Name   = Object.name;
                Prefab.Object = new IndividualObject();
                if (CoordinateOverride == null)
                {
                    Prefab.LocalPRS = Math.Round(Object.transform.localPosition.x, 2) + "┼" +
                                      Math.Round(Object.transform.localPosition.y, 2) + "┼" +
                                      Math.Round(Object.transform.localPosition.z, 2) + "┼";

                    if (Object.transform.localRotation.eulerAngles != Vector3.zero)
                    {
                        var Angles = Object.transform.localRotation.eulerAngles;
                        Prefab.LocalPRS = Prefab.LocalPRS + Math.Round(Angles.x, 2) + "ø" +
                                          Math.Round(Angles.y, 2) + "ø" +
                                          Math.Round(Angles.z, 2) + "ø";
                    }


                    if (Object.transform.localScale != Vector3.one)
                    {
                        var Angles = Object.transform.localScale;
                        Prefab.LocalPRS = Prefab.LocalPRS + Math.Round(Angles.x, 2) + "↔" +
                                          Math.Round(Angles.y, 2) + "↔" +
                                          Math.Round(Angles.z, 2) + "↔";
                    }
                }
                else
                {
                    var Position = CoordinateOverride.GetValueOrDefault(Vector3.zero);
                    Prefab.LocalPRS = Math.Round(Position.x, 2) + "┼" +
                                      Math.Round(Position.y, 2) + "┼" +
                                      Math.Round(Position.z, 2) + "┼";
                }


                RecursiveSaveObject(Prefab, "0", Prefab.Object,
                                    CustomNetworkManager.Instance.ForeverIDLookupSpawnablePrefabs[Tracker.ForeverID],
                                    Object.gameObject, ObjectMapData, CoordinateOverride, UseInstance);
                if (Prefab.Object.RemoveEmptys())
                {
                    Prefab.Object = null;
                }

                ObjectMapData.PrefabData.Add(Prefab);
            }
        }
Ejemplo n.º 21
0
        public static void FillOutClassData(PrefabData PrefabData, IndividualObject individualObject,
                                            GameObject PrefabEquivalent, GameObject gameObject, ObjectMapData ObjectMapData,
                                            Vector3?CoordinateOverride = null, bool UseInstance = false)
        {
            Dictionary <string, int> ClassCount = new Dictionary <string, int>();
            var PrefabComponents     = PrefabEquivalent.GetComponents <MonoBehaviour>().ToList();
            var gameObjectComponents = gameObject.GetComponents <MonoBehaviour>().ToList();

            for (int i = 0; i < PrefabComponents.Count; i++)
            {
                var PrefabMono = PrefabComponents[i];
                if (ClassCount.ContainsKey(PrefabMono.GetType().Name) == false)
                {
                    ClassCount[PrefabMono.GetType().Name] = 0;
                }
                ClassCount[PrefabMono.GetType().Name]++;

                var objectContainer = gameObjectComponents[i] as ObjectContainer;
                if (objectContainer != null)
                {
                    foreach (var objectBehaviour in objectContainer.GetStoredObjects().Select(obj => obj.GetComponent <ObjectBehaviour>()))
                    {
                        if (CoordinateOverride == null)
                        {
                            ProcessIndividualObject(objectBehaviour.gameObject, ObjectMapData,
                                                    gameObject.transform.localPosition, UseInstance);
                        }
                        else
                        {
                            ProcessIndividualObject(objectBehaviour.gameObject, ObjectMapData,
                                                    CoordinateOverride, UseInstance);
                        }
                    }
                }


                var itemStorage = gameObjectComponents[i] as ItemStorage;
                if (itemStorage != null)
                {
                    foreach (var objectBehaviour in itemStorage.GetItemSlots())
                    {
                        if (objectBehaviour.Item == null)
                        {
                            continue;
                        }
                        if (CoordinateOverride == null)
                        {
                            ProcessIndividualObject(objectBehaviour.Item.gameObject, ObjectMapData,
                                                    gameObject.transform.localPosition, UseInstance);
                        }
                        else
                        {
                            ProcessIndividualObject(objectBehaviour.Item.gameObject, ObjectMapData,
                                                    CoordinateOverride, UseInstance);
                        }
                    }
                }


                var OutClass = new ClassData();
                OutClass.ClassID = PrefabMono.GetType().Name + "@" + ClassCount[PrefabMono.GetType().Name];
                MonoToID[gameObjectComponents[i]] = PrefabData.ID + "@" + individualObject.ID + "@" + OutClass.ClassID;
                RecursiveSearchData(OutClass, "", PrefabMono, gameObjectComponents[i], UseInstance);

                if (OutClass.IsEmpty() == false)
                {
                    individualObject.ClassDatas.Add(OutClass);
                }
            }
        }
Ejemplo n.º 22
0
 public PojoPrefab(AssetUri uri, PrefabData data) : base(uri)
 {
     reload(data);
 }
Ejemplo n.º 23
0
 public override void reload(PrefabData data)
 {
 }
Ejemplo n.º 24
0
        private void SpawnEntities()
        {
            Log.Info("Spawning entities...");
            entitiesByAbsoluteCell = new Dictionary <AbsoluteEntityCell, List <Entity> >();
            Random random = new Random();

            foreach (EntitySpawnPoint entitySpawnPoint in entitySpawnPoints)
            {
                DstData dstData;
                if (!lootDistributionData.GetBiomeLoot(entitySpawnPoint.BiomeType, out dstData))
                {
                    continue;
                }

                float rollingProbabilityDensity = 0;

                PrefabData selectedPrefab = null;

                foreach (PrefabData prefab in dstData.prefabs)
                {
                    float probabilityDensity = prefab.probability / entitySpawnPoint.Density;
                    rollingProbabilityDensity += probabilityDensity;
                }
                double randomNumber       = random.NextDouble();
                double rollingProbability = 0;

                if (rollingProbabilityDensity > 0)
                {
                    if (rollingProbabilityDensity > 1f)
                    {
                        randomNumber *= rollingProbabilityDensity;
                    }

                    foreach (PrefabData prefab in dstData.prefabs)
                    {
                        float probabilityDensity = prefab.probability / entitySpawnPoint.Density;
                        rollingProbability += probabilityDensity;
                        //This is pretty hacky, it rerolls until its hits a prefab of a correct type
                        //What should happen is that we check wei first, then grab data from there
                        bool isValidSpawn = IsValidSpawnType(prefab.classId, entitySpawnPoint.CanSpawnCreature);
                        if (rollingProbability >= randomNumber && isValidSpawn)
                        {
                            selectedPrefab = prefab;
                            break;
                        }
                    }
                }

                if (!ReferenceEquals(selectedPrefab, null) && worldEntitiesByClassId.ContainsKey(selectedPrefab.classId))
                {
                    WorldEntityInfo worldEntityInfo = worldEntitiesByClassId[selectedPrefab.classId];

                    for (int i = 0; i < selectedPrefab.count; i++)
                    {
                        Entity spawnedEntity = new Entity(entitySpawnPoint.Position,
                                                          entitySpawnPoint.Rotation,
                                                          worldEntityInfo.techType,
                                                          Guid.NewGuid().ToString(),
                                                          (int)worldEntityInfo.cellLevel);

                        AbsoluteEntityCell absoluteCellId = new AbsoluteEntityCell(entitySpawnPoint.BatchId, entitySpawnPoint.CellId);

                        if (!entitiesByAbsoluteCell.ContainsKey(absoluteCellId))
                        {
                            entitiesByAbsoluteCell[absoluteCellId] = new List <Entity>();
                        }

                        entitiesByAbsoluteCell[absoluteCellId].Add(spawnedEntity);
                    }
                }
            }
        }
Ejemplo n.º 25
0
 private void Awake()
 {
     prefabs = prefabData;
 }
Ejemplo n.º 26
0
        public static void SimulationStep(ref TransportLine thisLine, ushort lineID)
        {
            //begin mod(+): change for initialization
            if (!TransportLineMod._init)
            {
                return;
            }
            //end mod

            TransportInfo info = thisLine.Info;

            if (thisLine.Complete)
            {
                //begin mod(*): moved this section to a separate method
                int num2 = CountLineActiveVehicles(lineID);
                //end mod
                bool flag1 = !Singleton <SimulationManager> .instance.m_isNightTime
                    ? (thisLine.m_flags & TransportLine.Flags.DisabledDay) == TransportLine.Flags.None
                    : (thisLine.m_flags & TransportLine.Flags.DisabledNight) == TransportLine.Flags.None;
                uint  range = 0;
                float num5  = 0.0f;
                int   num6  = 0;
                bool  flag2 = false;
                if ((int)thisLine.m_stops != 0)
                {
                    NetManager instance = Singleton <NetManager> .instance;
                    ushort     stops    = thisLine.m_stops;
                    ushort     num3     = stops;
                    int        num4     = 0;
                    while ((int)num3 != 0)
                    {
                        ushort num7 = 0;
                        if (flag1)
                        {
                            instance.m_nodes.m_buffer[(int)num3].m_flags &=
                                NetNode.Flags.OneWayOutTrafficLights | NetNode.Flags.UndergroundTransition |
                                NetNode.Flags.Created | NetNode.Flags.Deleted | NetNode.Flags.Original |
                                NetNode.Flags.End | NetNode.Flags.Middle | NetNode.Flags.Bend | NetNode.Flags.Junction |
                                NetNode.Flags.Moveable | NetNode.Flags.Untouchable | NetNode.Flags.Outside |
                                NetNode.Flags.Temporary | NetNode.Flags.Double | NetNode.Flags.Fixed |
                                NetNode.Flags.OnGround | NetNode.Flags.Ambiguous | NetNode.Flags.Water |
                                NetNode.Flags.Sewage | NetNode.Flags.ForbidLaneConnection |
                                NetNode.Flags.LevelCrossing | NetNode.Flags.OneWayIn | NetNode.Flags.Heating |
                                NetNode.Flags.Electricity | NetNode.Flags.Collapsed | NetNode.Flags.DisableOnlyMiddle |
                                NetNode.Flags.AsymForward | NetNode.Flags.AsymBackward |
                                NetNode.Flags.CustomTrafficLights;
                        }
                        else
                        {
                            instance.m_nodes.m_buffer[(int)num3].m_flags |= NetNode.Flags.Disabled;
                        }
                        for (int index = 0; index < 8; ++index)
                        {
                            ushort segment = instance.m_nodes.m_buffer[(int)num3].GetSegment(index);
                            if ((int)segment != 0 && (int)instance.m_segments.m_buffer[(int)segment].m_startNode ==
                                (int)num3)
                            {
                                num6 +=
                                    Mathf.Max((int)instance.m_segments.m_buffer[(int)segment].m_trafficLightState0,
                                              (int)instance.m_segments.m_buffer[(int)segment].m_trafficLightState1);
                                num5 += instance.m_segments.m_buffer[(int)segment].m_averageLength;
                                num7  = instance.m_segments.m_buffer[(int)segment].m_endNode;
                                if ((instance.m_segments.m_buffer[(int)segment].m_flags &
                                     NetSegment.Flags.PathLength) == NetSegment.Flags.None)
                                {
                                    flag2 = true;
                                    break;
                                }
                                break;
                            }
                        }
                        ++range;
                        num3 = num7;
                        if ((int)num3 != (int)stops)
                        {
                            if (++num4 >= 32768)
                            {
                                CODebugBase <LogChannel> .Error(LogChannel.Core,
                                                                "Invalid list detected!\n" + System.Environment.StackTrace);

                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (!flag2)
                {
                    thisLine.m_totalLength = num5;
                }
                if ((int)range != 0)
                {
                    thisLine.m_averageInterval = (byte)Mathf.Min((float)byte.MaxValue,
                                                                 (float)(((long)num6 + (long)(range >> 1)) / (long)range));
                }
                //begin mod(-): let's count maintenance once a week
                //end mod

                TransferManager.TransferReason vehicleReason = info.m_vehicleReason;
                if (vehicleReason != TransferManager.TransferReason.None)
                {
                    //begin mod: calculate target vehicle count or read saved value
                    int num3 = 0;
                    if (TransportLineMod._lineData[(int)lineID].BudgetControl || info.m_class.m_service == ItemClass.Service.Disaster)
                    {
                        num3 = !flag1 ? 0 : (!flag2 ? thisLine.CalculateTargetVehicleCount() : num2);
                        TransportLineMod._lineData[(int)lineID].TargetVehicleCount = num3;
                    }
                    else if (flag1)
                    {
                        num3 = TransportLineMod._lineData[(int)lineID].TargetVehicleCount;
                    }
                    //end mod
                    if (range != 0 && num2 < num3)
                    {
                        ushort stop = thisLine.GetStop(Singleton <SimulationManager> .instance.m_randomizer
                                                       .Int32((uint)thisLine.CountStops(lineID)));
                        if (info.m_vehicleReason != TransferManager.TransferReason.None && (int)stop != 0)
                        {
                            //begin mod(+): save offer as variable and directly invoke spawn if it's not evac line
                            TransferManager.TransferOffer offer =
                                new TransferManager.TransferOffer
                            {
                                Priority      = num3 - num2 + 1,
                                TransportLine = lineID,
                                Position      = Singleton <NetManager> .instance.m_nodes.m_buffer[(int)stop]
                                                .m_position,
                                Amount = 1,
                                Active = false
                            };
                            if (info.m_class.m_service == ItemClass.Service.Disaster)
                            {
                                Singleton <TransferManager> .instance.AddIncomingOffer(vehicleReason, offer);
                            }
                            else
                            {
                                HandleVehicleSpawn(lineID, info, num3, num2, offer);
                            }
                            //end mod
                        }
                    }
                    else if (num2 > num3)
                    {
                        //begin mod(*): encapsulate into method
                        TransportLineMod.RemoveActiveVehicle(lineID, false, num2);
                        //end mod
                    }
                }
            }
            if ((Singleton <SimulationManager> .instance.m_currentFrameIndex & 4095U) < 3840U)
            {
                return;
            }
            thisLine.m_passengers.Update();
            Singleton <TransportManager> .instance.m_passengers[(int)info.m_transportType].Add(ref thisLine.m_passengers);
            thisLine.m_passengers.Reset();


            //begin mod(+): update statistics + fetch maintenance costs
            if (thisLine.Complete)
            {
                ushort stops1 = thisLine.m_stops;
                ushort stop1  = stops1;
                do
                {
                    NetManagerMod.m_cachedNodeData[(int)stop1].StartNewWeek();
                    stop1 = TransportLine.GetNextStop(stop1);
                } while ((int)stops1 != (int)stop1 && (int)stop1 != 0);

                var          itemClass = info.m_class;
                PrefabData[] prefabs   = VehiclePrefabs.instance.GetPrefabs(itemClass.m_service, itemClass.m_subService, itemClass.m_level);
                int          amount    = 0;
                CountLineActiveVehicles(lineID, (num3) =>
                {
                    Vehicle vehicle       = VehicleManager.instance.m_vehicles.m_buffer[num3];
                    PrefabData prefabData = Array.Find(prefabs,
                                                       item => item.PrefabDataIndex == vehicle.Info.m_prefabDataIndex);
                    if (prefabData != null)
                    {
                        amount += prefabData.MaintenanceCost;
                        VehicleManagerMod.m_cachedVehicleData[num3].StartNewWeek(prefabData.MaintenanceCost);
                    }
                });
                if (amount != 0)
                {
                    Singleton <EconomyManager> .instance.FetchResource(EconomyManager.Resource.Maintenance, amount, info.m_class);
                }
                //end mod
            }
        }
Ejemplo n.º 27
0
 private void Awake()
 {
     Instance = this;
 }
    public IEnumerator GenerateObjects(ObjectType objectType, ObjectData objectData, ChunkData chunkData)
    {
        MapGenerator mapGenerator = new MapGenerator();

        float[,] map = new float[ProceduralTerrain.TerrainResolution, ProceduralTerrain.TerrainResolution];
        int   seed            = objectData.ObjectNoiseData.Seed;
        int   flatSearchRange = objectData.FlatSurfaceSearchRange;
        float flatSens        = objectData.FlatSurfaceSensitivity;

        PrefabData[] prefabDataArray = objectData.PrefabArray;
        float        density         = objectData.SpawnDensity;
        float        minSpawnHeight  = objectData.MinSpawnHeight;
        float        maxSpawnHeight  = objectData.MaxSpawnHeight;
        float        threshold       = objectData.SpawnThreshold;
        Vector2      position        = chunkData.position;

        List <GameObject> subChunks = new List <GameObject>();
        int objectsPlaced           = 0;
        int subChunkIndex           = 0;

        //Keep track of vertices so can group as efficiently as possible for combine mesh
        int vertexCount = 0;

        //Keep track of objects spawned
        int objectsSpawned = 0;
        //Max number of object per frame
        int maxSpawnsPerFrame = objectData.MaxSpawnsPerFrame;

        //Tag to tag objects with
        string tag;

        //Stop programming from running until thread has returned noisemap
        canContinue = false;

        //Start a new thread for requesting the noisemap
        mapGenerator.RequestNoiseMap(objectData.ObjectNoiseData, ProceduralTerrain.TerrainResolution, position, OnNoiseMapRecieved);
        //While there is no noise map, do not progress any further
        while (!canContinue)
        {
            mapGenerator.UpdateCallbacks();
            yield return(null);
        }
        canContinue = false;

        //Placable map for this object type based off of terrain flatness
        mapGenerator.RequestFlatTerrainMap(chunkData.terrainHeightMap, flatSearchRange, flatSens, OnFlatTerrainMapRecieved);
        //While there is no flat terrain map, do not progress any further
        while (!canContinue)
        {
            mapGenerator.UpdateCallbacks();
            yield return(null);
        }

        //Placable map based off of whether the location is valid (if there is another object there)
        bool[,] validPlacableMap;

        //If not detail type, normal placable map
        if (objectType != ObjectType.Detail)
        {
            validPlacableMap = chunkData.terrainPlacableMap;
        }
        //Else detail placable area
        else
        {
            validPlacableMap = chunkData.terrainDetailPlacableMap;
        }

        //Create empty parent to hold object type
        GameObject parentObject;

        switch (objectType)
        {
        case ObjectType.House:
            HouseCounter++;
            parentObject = new GameObject("Houses " + HouseCounter);
            tag          = "House";
            break;

        case ObjectType.Tree:
            TreeCounter++;
            parentObject = new GameObject("Trees " + TreeCounter);
            tag          = "Tree";
            break;

        case ObjectType.Detail:
            DetailCounter++;
            parentObject = new GameObject("Details " + DetailCounter);
            tag          = "Detail";
            break;

        default:
            parentObject = new GameObject("Other");
            tag          = "Default";
            break;
        }

        //Create first sub chunk
        subChunks.Add(new GameObject("Sub chunk " + subChunkIndex));
        subChunks[subChunkIndex].transform.SetParent(parentObject.transform);
        subChunks[subChunkIndex].AddComponent <MeshRenderer>().sharedMaterial = objectData.ObjectMaterial;

        //Parent empty object to chunk
        parentObject.transform.SetParent(chunkData.terrain.gameObject.transform);

        int maxRequiredSpaceX = int.MinValue;
        int maxRequiredSpaceZ = int.MinValue;

        //Get largest for x and z
        foreach (PrefabData prefabData in prefabDataArray)
        {
            maxRequiredSpaceX = (prefabData.RequiredSpaceX > maxRequiredSpaceX) ? prefabData.RequiredSpaceX : maxRequiredSpaceX;
            maxRequiredSpaceZ = (prefabData.RequiredSpaceZ > maxRequiredSpaceZ) ? prefabData.RequiredSpaceZ : maxRequiredSpaceZ;
        }

        //Largest as to not go out of array range
        int range = Mathf.Max(maxRequiredSpaceX, maxRequiredSpaceZ);

        //Required for chosing of prefab to spawn
        System.Random rand = new System.Random();

        //If an area has already been tested, dont check it again for this object
        bool[,] hasAttempedPlacement = new bool[ProceduralTerrain.TerrainResolution, ProceduralTerrain.TerrainResolution];

        //Spawn objects
        for (int x = 0 + range; x < ProceduralTerrain.TerrainResolution - range; x++)
        {
            for (int y = 0 + range; y < ProceduralTerrain.TerrainResolution - range; y++)
            {
                //If an attempt to place an object here has been made
                if (hasAttempedPlacement[x, y])
                {
                    //Next area
                    continue;
                }

                float terrainHeight = chunkData.terrainHeightMap[x, y];
                bool  canPlace      = true;

                //Randomly choose an object from the array to place
                PrefabData prefabData = prefabDataArray[(rand.Next(0, prefabDataArray.Length))];

                //Get the required space for that prefab
                int requiredSpaceX = prefabData.RequiredSpaceX;
                int requiredSpaceZ = prefabData.RequiredSpaceZ;

                //Check around this point to check it is flat
                if (canPlace)
                {
                    canPlace = CheckIfPlacableFromMap(new Vector2(x, y), new Vector2(requiredSpaceX, requiredSpaceZ), flatPlacableMap);
                }
                //Check around this point to check there is no other objects
                if (canPlace)
                {
                    canPlace = CheckIfPlacableFromMap(new Vector2(x, y), new Vector2(requiredSpaceX, requiredSpaceZ), validPlacableMap);
                }
                //Randomly decide whether object can be placed based off of density
                if (canPlace)
                {
                    canPlace = CheckIfPlacableFromDensity(density, prefabDataArray.Length);
                }
                //Check against min and max height
                if (canPlace)
                {
                    canPlace = CheckIfPlacableFromHeight(terrainHeight, minSpawnHeight, maxSpawnHeight);
                }

                if (canPlace)
                {
                    //Update map
                    map[x, y] = 1f;

                    //Subtract noise
                    map[x, y] = Mathf.Clamp01(map[x, y] - noiseMap[x, y]);

                    //If greater than threshold
                    if (map[x, y] >= threshold)
                    {
                        //Need to invert as terrain is created inverted
                        float xToPlace = ((float)y / (float)ProceduralTerrain.TerrainResolution) * (float)ProceduralTerrain.Current.TerrainMapData.TerrainSize;
                        float yToPlace = chunkData.terrainHeightMap[x, y] * (float)ProceduralTerrain.Current.TerrainMapData.TerrainHeight;
                        float zToPlace = ((float)x / (float)ProceduralTerrain.TerrainResolution) * (float)ProceduralTerrain.Current.TerrainMapData.TerrainSize;

                        //Move object to be placed in centre of area just checked
                        xToPlace += requiredSpaceX / 2;
                        zToPlace += requiredSpaceZ / 2;

                        //This area is no longer placable within objects required area
                        UpdatePlacableMap(new Vector2(x, y), new Vector2(requiredSpaceX, requiredSpaceZ), validPlacableMap);
                        //If not detail
                        if (objectType != ObjectType.Detail)
                        {
                            //Update detail placable map with actual size, so details can be placed under within objects required size
                            UpdatePlacableMap(new Vector2(x, y), new Vector2(prefabData.ActualSizeX, prefabData.ActualSizeZ), chunkData.terrainDetailPlacableMap);
                        }
                        //If is detail
                        else
                        {
                            UpdatePlacableMap(new Vector2(x, y), new Vector2(requiredSpaceX, requiredSpaceX), chunkData.terrainDetailPlacableMap);
                        }

                        objectsPlaced++;
                        //Get total verticies of this object's mesh and its children's meshes
                        int localVertices = GetTotalVerticies(prefabData);

                        //If more vertices than unitys max vertex count
                        if (vertexCount + localVertices >= 64000)
                        {
                            //Combine mesh for this subchunk before creating next
                            if (ProceduralTerrain.Current.CombineMeshes && objectType != ObjectType.House)
                            {
                                subChunks[subChunkIndex].AddComponent <CombineMeshes>().SetTag(tag);
                            }

                            //Reset vertexCount
                            vertexCount = 0;

                            subChunkIndex++;
                            subChunks.Add(new GameObject("Sub chunk " + subChunkIndex));
                            subChunks[subChunkIndex].transform.SetParent(parentObject.transform);
                            subChunks[subChunkIndex].AddComponent <MeshRenderer>().sharedMaterial = objectData.ObjectMaterial;
                        }

                        //Randomly rotate the object to make less uniform
                        Quaternion randomRotation = Quaternion.Euler(0, rand.Next(0, 360), 0);
                        //Instantiate object
                        GameObject spawnedObject = (GameObject)Instantiate(prefabData.ObjectPrefab, new Vector3(xToPlace + chunkData.position.x, yToPlace, zToPlace + chunkData.position.y), randomRotation, subChunks[subChunkIndex].transform);

                        //If a house, add to the chunkData's house list (used for village generation)
                        if (objectType == ObjectType.House)
                        {
                            //Add house to list of houses
                            chunkData.VillageHouseList.Add(spawnedObject.AddComponent <VillageHouseData>());
                            spawnedObject.GetComponent <VillageHouseData>().SetChunkLocalPosition(new Vector2(x, y));
                        }

                        //Update the verticies for this subchunk
                        vertexCount += localVertices;

                        //Increment objects spawned
                        objectsSpawned++;
                        //If objects spawns is greater than max per frame, wait untill next frame to spawn next
                        if (objectsSpawned >= maxSpawnsPerFrame)
                        {
                            objectsSpawned = 0;
                            yield return(null);
                        }
                    }
                    //Else there is nothing here
                    else
                    {
                        map[x, y] = 0;
                    }
                }

                //If can't place, mark this area as having been attemped for this object
                else
                {
                    //hasAttempedPlacement[x, y] = true;
                    for (int i = 0; i <= requiredSpaceX; i++)
                    {
                        for (int j = 0; j <= requiredSpaceZ; j++)
                        {
                            hasAttempedPlacement[x + i, y + j] = true;
                        }
                    }
                }
            }
        }

        //Combine meshes for last sub chunk
        if (ProceduralTerrain.Current.CombineMeshes && objectType != ObjectType.House)
        {
            subChunks[subChunkIndex].AddComponent <CombineMeshes>().SetTag(tag);
        }

        yield return(null);
    }
Ejemplo n.º 29
0
            public void ProcessCustomOption(String optionOperation, bool isCheck, String argument, String[] targetObjectList)
            {
                switch (optionOperation.ToUpper())
                {
                case "DELETE_OBJECT":
                    if (isCheck)
                    {
                        for (int i = 0; i < targetObjectList.Length; i++)
                        {
                            Transform target = PrefabData.GetAvatar().transform.Find(targetObjectList[i]);
                            if (target != null)
                            {
                                if (isDeleteIsEditorOnlyTag)
                                {
                                    target.gameObject.tag = "EditorOnly";
                                    target.gameObject.SetActive(false);
                                }
                                else
                                {
                                    GameObject.DestroyImmediate(target.gameObject);
                                }
                            }
                        }
                    }
                    break;

                case "NOT_DELETE_OBJECT":
                    if (!isCheck)
                    {
                        for (int i = 0; i < targetObjectList.Length; i++)
                        {
                            Transform target = PrefabData.GetAvatar().transform.Find(targetObjectList[i]);
                            if (target != null)
                            {
                                if (isDeleteUnnecessaryObject)
                                {
                                    target.tag = "EditorOnly";
                                    target.gameObject.SetActive(false);
                                }
                                else
                                {
                                    GameObject.DestroyImmediate(target.gameObject);
                                }
                            }
                        }
                    }
                    break;

                case "ENABLE_OBJECT":
                    if (isCheck)
                    {
                        for (int i = 0; i < targetObjectList.Length; i++)
                        {
                            Transform target = PrefabData.GetAvatar().transform.Find(targetObjectList[i]);
                            if (target != null)
                            {
                                target.gameObject.SetActive(true);
                            }
                        }
                    }
                    break;

                case "DISABLE_OBJECT":
                    if (isCheck)
                    {
                        for (int i = 0; i < targetObjectList.Length; i++)
                        {
                            Transform target = PrefabData.GetAvatar().transform.Find(targetObjectList[i]);
                            if (target != null)
                            {
                                target.gameObject.SetActive(false);
                            }
                        }
                    }
                    break;

                case "SET_MATERIAL":
                    if (isCheck)
                    {
                        string   assetsPath = Path.GetDirectoryName(clothPrefabParentPath) + "/";
                        Material material   = AssetDatabase.LoadAssetAtPath <Material>(assetsPath + argument);
                        if (material != null)
                        {
                            for (int i = 0; i < targetObjectList.Length; i++)
                            {
                                Transform target = PrefabData.GetAvatar().transform.Find(targetObjectList[i]);
                                if (target != null)
                                {
                                    SkinnedMeshRenderer meshRenderer = target.gameObject.GetComponent <SkinnedMeshRenderer>();
                                    if (meshRenderer != null)
                                    {
                                        meshRenderer.material = material;
                                    }
                                }
                            }
                        }
                    }
                    break;

                case "NONE":
                    break;
                }
            }
Ejemplo n.º 30
0
        private void SpawnEntities()
        {
            Log.Info("Spawning entities...");
            entitiesByAbsoluteCell = new Dictionary <AbsoluteEntityCell, List <Entity> >();
            Random random = new Random();

            foreach (EntitySpawnPoint entitySpawnPoint in entitySpawnPoints)
            {
                DstData dstData;
                if (!lootDistributionData.GetBiomeLoot(entitySpawnPoint.BiomeType, out dstData))
                {
                    continue;
                }

                float rollingProbabilityDensity = 0;

                PrefabData selectedPrefab = null;

                foreach (PrefabData prefab in dstData.prefabs)
                {
                    float probabilityDensity = prefab.probability / entitySpawnPoint.Density;
                    rollingProbabilityDensity += probabilityDensity;
                }
                double randomNumber       = random.NextDouble();
                double rollingProbability = 0;

                if (rollingProbabilityDensity > 0)
                {
                    if (rollingProbabilityDensity > 1f)
                    {
                        randomNumber *= rollingProbabilityDensity;
                    }

                    foreach (PrefabData prefab in dstData.prefabs)
                    {
                        float probabilityDensity = prefab.probability / entitySpawnPoint.Density;
                        rollingProbability += probabilityDensity;
                        if (rollingProbability >= randomNumber)
                        {
                            selectedPrefab = prefab;
                            break;
                        }
                    }
                }

                if (!ReferenceEquals(selectedPrefab, null) && worldEntitiesByClassId.ContainsKey(selectedPrefab.classId))
                {
                    WorldEntityInfo worldEntityInfo = worldEntitiesByClassId[selectedPrefab.classId];

                    for (int i = 0; i < selectedPrefab.count; i++)
                    {
                        Entity spawnedEntity = new Entity(entitySpawnPoint.Position,
                                                          worldEntityInfo.techType,
                                                          Guid.NewGuid().ToString(),
                                                          (int)worldEntityInfo.cellLevel);

                        AbsoluteEntityCell absoluteCellId = new AbsoluteEntityCell(entitySpawnPoint.BatchId, entitySpawnPoint.CellId);

                        if (!entitiesByAbsoluteCell.ContainsKey(absoluteCellId))
                        {
                            entitiesByAbsoluteCell[absoluteCellId] = new List <Entity>();
                        }

                        entitiesByAbsoluteCell[absoluteCellId].Add(spawnedEntity);
                    }
                }
            }
        }
Ejemplo n.º 31
0
            //ExpandOptionのGUI処理
            private void OnCustomOptionGUI()
            {
                if (expandOption.custom_options == null)
                {
                    return;
                }

                for (int i = 0; i < expandOption.custom_options.Length; i++)
                {
                    CustomOption customOption = expandOption.custom_options[i];

                    //オプションが非表示の場合
                    if (customOption.is_not_visible_option)
                    {
                        return;
                    }

                    GUILayout.Space(4);

                    switch (customOption.option_type.ToLower())
                    {
                    case "toggle":
                        customOption.is_check = GUILayout.Toggle(customOption.is_check, I18N.Instance().Get(customOption.name));
                        break;

                    case "grid":
                        GUILayout.Label(I18N.Instance().Get(customOption.name));

                        //GUI用の文字列リストを作る
                        List <string> selectGridList = new List <string>();
                        //CustomOptionのgrid_listから名前を取り出し文字列リストに追加
                        for (int selectGridCount = 0; selectGridCount < customOption.grid_list.Length; selectGridCount++)
                        {
                            selectGridList.Add(I18N.Instance().Get(customOption.grid_list[selectGridCount].name));
                        }
                        //GUI表示。処理するときにはselect(index)を使ってCustomOptionのgrid_listから取り出す
                        customOption.select = GUILayout.SelectionGrid(customOption.select, selectGridList.ToArray(), 3);
                        break;
                    }

                    //適用ボタン表示のフィルター処理
                    bool filterPassed = false;

                    if (customOption.apply_filter != null && PrefabData.GetAvatar() != null)
                    {
                        for (int filterCount = 0; filterCount < customOption.apply_filter.Length; filterCount++)
                        {
                            Transform filterObject = PrefabData.GetAvatar().transform.Find(customOption.apply_filter[filterCount]);
                            if (filterObject != null)
                            {
                                filterPassed = true;
                            }
                        }
                    }

                    if (customOption.display_apply_button && filterPassed)
                    {
                        GUILayout.Space(4);
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.FlexibleSpace();
                        if (GUILayout.Button(I18N.Instance().Get("option.button.apply") + ": " + I18N.Instance().Get(customOption.name), new GUILayoutOption[] {
                            GUILayout.MinWidth(200)
                        }))
                        {
                            RunCustomOption(customOption);
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                }
            }