コード例 #1
0
ファイル: Units.cs プロジェクト: gdpaulmil/WPF_ServerClient
 static GameObjectData GetRandomGOData()
 {
     GameObjectData data = new GameObjectData();
     data.shape = new ObjectShape(ObjectShape.EShapeType.Circle, new Vector(32, 32), Colors.Red);
     Random r = new Random();
     data.pos.X = r.Next(Game.Config.GameWidth);
     data.pos.Y = r.Next(Game.Config.GameHeight);
     return data;
 }
コード例 #2
0
        void OnGUI()
        {
            InitGUI();
            EditorGUILayout.BeginHorizontal(GUILayout.Width(920f), min_height);
            GUILayout.Label("Filter : ", EditorStyles.miniLabel, width_filter);
            string search = GUILayout.TextField(mSearch.FilterString, style_toolbar_search_text);

            if (GUILayout.Button("", style_toolbar_search_cancel))
            {
                search = "";
            }
            if (search != mSearch.FilterString)
            {
                mSearch.FilterString = search;
                FilterObjects();
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Prefab", style_toolbar_button, width_prefab);
            GUILayout.Label("Renderer", style_toolbar_button, width_renderer);
            GUILayout.Label("Material", style_toolbar_button, width_material);
            GUILayout.Label("UV per meter (min max average)", style_toolbar_button, width_uv_pm);
            GUILayout.Label("Texture", style_toolbar_button, width_texture);
            GUILayout.Label("Pxs per meter (min max average)", style_toolbar_button, width_px_pm);
            EditorGUILayout.EndHorizontal();
            mScroll = EditorGUILayout.BeginScrollView(mScroll, false, false);
            const float item_height = 20f;
            int         from        = Mathf.FloorToInt(mScroll.y / item_height);
            int         end         = Mathf.CeilToInt(position.height / item_height) + from;
            int         len         = mFilteredObjects == null ? 0 : mFilteredObjects.Count;

            for (int i = 0; i < len; i++)
            {
                GameObjectData gd = mFilteredObjects[i];
                if (gd.renderers.Count <= 0)
                {
                    continue;
                }
                float standardDpx   = GetStandardDpx();
                float standardDpx2x = standardDpx * 2f;
                float standardDpx4x = standardDpx * 4f;
                int   gtexs         = 0;
                foreach (RendererData rd in gd.renderers)
                {
                    foreach (MaterialData md in rd.materials)
                    {
                        gtexs += Mathf.Max(1, md.textures.Count);
                    }
                }
                if (gd.from + gtexs < from || gd.from > end)
                {
                    GUILayout.Space(gtexs * item_height);
                    continue;
                }
                GUILayout.BeginHorizontal(min_height);
                // prefab
                GUILayout.BeginVertical(style_cn_box, width_prefab);
                float spacep = item_height * (gtexs - 1) * 0.5f;
                GUILayout.Space(spacep + 2f);
                EditorGUILayout.ObjectField(gd.gameobject, typeof(GameObject), false);
                GUILayout.Space(spacep);
                GUILayout.EndVertical();
                // renderer
                GUILayout.BeginVertical(width_renderer);
                foreach (RendererData rd in gd.renderers)
                {
                    int rtexs = 0;
                    foreach (MaterialData md in rd.materials)
                    {
                        rtexs += Mathf.Max(1, md.textures.Count);
                    }
                    GUILayout.BeginVertical(style_cn_box);
                    float space = item_height * (rtexs - 1) * 0.5f;
                    GUILayout.Space(space + 2f);
                    EditorGUILayout.ObjectField(rd.renderer, typeof(Renderer), false);
                    GUILayout.Space(space);
                    GUILayout.EndVertical();
                }
                GUILayout.EndVertical();
                // material
                GUILayout.BeginVertical(width_material);
                foreach (RendererData rd in gd.renderers)
                {
                    foreach (MaterialData md in rd.materials)
                    {
                        int ttexs = md.textures.Count;
                        GUILayout.BeginVertical(style_cn_box);
                        if (ttexs <= 0)
                        {
                            EditorGUILayout.LabelField("  ", min_width);
                        }
                        else
                        {
                            float space = item_height * (ttexs - 1) * 0.5f;
                            GUILayout.Space(space + 2f);
                            EditorGUILayout.ObjectField(md.material, typeof(Material), false);
                            GUILayout.Space(space);
                        }
                        GUILayout.EndVertical();
                    }
                }
                GUILayout.EndVertical();
                // uv per meter
                GUILayout.BeginVertical(width_uv_pm);
                foreach (RendererData rd in gd.renderers)
                {
                    foreach (MaterialData md in rd.materials)
                    {
                        int ttexs = md.textures.Count;
                        GUILayout.BeginVertical(style_cn_box);
                        if (ttexs <= 0)
                        {
                            EditorGUILayout.LabelField("  ", min_width);
                        }
                        else
                        {
                            float space = item_height * (ttexs - 1) * 0.5f;
                            GUILayout.Space(space + 2f);
                            EditorGUILayout.LabelField(md.duv_info, min_width);
                            GUILayout.Space(space);
                        }
                        GUILayout.EndVertical();
                    }
                }
                GUILayout.EndVertical();
                // texture
                GUILayout.BeginVertical(width_texture);
                foreach (RendererData rd in gd.renderers)
                {
                    foreach (MaterialData md in rd.materials)
                    {
                        foreach (TextureData td in md.textures)
                        {
                            EditorGUILayout.BeginHorizontal(style_cn_box);
                            EditorGUILayout.ObjectField(td.texture, typeof(Texture), false);
                            Texture2D tex  = td.texture as Texture2D;
                            string    size = string.Format("{0}x{1}", tex == null ? "?" : tex.width.ToString(),
                                                           tex == null ? "?" : tex.height.ToString());
                            EditorGUILayout.LabelField(size, tex != null && tex.mipmapCount > 1 ?
                                                       EditorStyles.miniBoldLabel : EditorStyles.miniLabel, width_64);
                            EditorGUILayout.EndHorizontal();
                        }
                        if (md.textures.Count <= 0)
                        {
                            GUILayout.BeginVertical(style_cn_box);
                            EditorGUILayout.LabelField("  ", min_width);
                            EditorGUILayout.EndHorizontal();
                        }
                    }
                }
                GUILayout.EndVertical();
                // pixels per meter
                GUILayout.BeginVertical(width_px_pm);
                foreach (RendererData rd in gd.renderers)
                {
                    foreach (MaterialData md in rd.materials)
                    {
                        foreach (TextureData td in md.textures)
                        {
                            GUILayout.BeginVertical(style_cn_box);
                            float  dpx;
                            string dpxInfo     = td.GetDPXInfo(md.duv_min, md.duv_max, md.duv_avg, out dpx);
                            Color  cachedColor = GUI.color;
                            if (dpx > standardDpx)
                            {
                                Color orange = new Color(1f, 0.5f, 0f, 1f);
                                if (dpx > standardDpx2x)
                                {
                                    float t = Mathf.InverseLerp(standardDpx2x, standardDpx4x, dpx);
                                    GUI.color = Color.Lerp(orange, Color.red, t);
                                }
                                else
                                {
                                    float t = Mathf.InverseLerp(standardDpx, standardDpx2x, dpx);
                                    GUI.color = Color.Lerp(cachedColor, orange, t);
                                }
                            }
                            EditorGUILayout.LabelField(dpxInfo, min_width);
                            GUI.color = cachedColor;
                            GUILayout.EndVertical();
                        }
                        if (md.textures.Count <= 0)
                        {
                            GUILayout.BeginVertical(style_cn_box);
                            EditorGUILayout.LabelField("  ", min_width);
                            GUILayout.EndVertical();
                        }
                    }
                }
                GUILayout.EndVertical();
                GUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();
        }
コード例 #3
0
 public static bool TryGetGameObjectDataByInstanceId(int goInstanceId, out GameObjectData gameObjectData)
 {
     // All the fun!
     return((singleton != null || (gameObjectData = null) == null) && singleton._localIdToGameObjectData.TryGetValue(goInstanceId, out gameObjectData));
 }
コード例 #4
0
        /// <summary>
        /// A helper method for loading an object layer from an XML subtree
        /// </summary>
        /// <param name="reader">The XML reader for the layer subtree</param>
        /// <returns>A GroupObjectContent object</returns>
        GameObjectGroupContent LoadObjectGroup(XmlReader reader, int tilewidth, int tileheight)
        {
            GameObjectGroupContent output = new GameObjectGroupContent();

            output.Properties = new Dictionary <string, string>();

            List <GameObjectData> gameObjects = new List <GameObjectData>();

            // Read the subtree
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                    case "object":
                        GameObjectData go = new GameObjectData();
                        go.Category = reader.GetAttribute("name");
                        go.Type     = reader.GetAttribute("type");

                        go.Position.X = int.Parse(reader.GetAttribute("x"));
                        go.Position.Y = int.Parse(reader.GetAttribute("y"));

                        // By default, Tiled sets objects to tile width and height - if
                        // there is no change to these, then it does not add a width
                        // and height attribute to the object XML - so we'll check
                        // for those elements and use them or the default, as needed
                        if (reader.GetAttribute("width") != null)
                        {
                            go.Position.Width = int.Parse(reader.GetAttribute("width"));
                        }
                        else
                        {
                            go.Position.Width = tilewidth;
                        }
                        if (reader.GetAttribute("height") != null)
                        {
                            go.Position.Height = int.Parse(reader.GetAttribute("height"));
                        }
                        else
                        {
                            go.Position.Width = tileheight;
                        }
                        gameObjects.Add(go);
                        break;

                    case "properties":
                        using (XmlReader st = reader.ReadSubtree())
                        {
                            st.Read();
                            output.Properties = LoadProperties(st);
                        }
                        break;
                    }
                }
            }

            output.GameObjectData = gameObjects.ToArray();

            return(output);
        }
コード例 #5
0
        void LoadHelper <T>(SortedSet <ulong> guid_set, CellCoord cell, ref uint count, Map map) where T : WorldObject, new()
        {
            foreach (var guid in guid_set)
            {
                T obj = new();
                // Don't spawn at all if there's a respawn time
                if ((obj.IsTypeId(TypeId.Unit) && map.GetCreatureRespawnTime(guid) == 0) || (obj.IsTypeId(TypeId.GameObject) && map.GetGORespawnTime(guid) == 0) || obj.IsTypeId(TypeId.AreaTrigger))
                {
                    //TC_LOG_INFO("misc", "DEBUG: LoadHelper from table: %s for (guid: %u) Loading", table, guid);
                    if (obj.IsTypeId(TypeId.Unit))
                    {
                        CreatureData cdata = Global.ObjectMgr.GetCreatureData(guid);
                        Cypher.Assert(cdata != null, $"Tried to load creature with spawnId {guid}, but no such creature exists.");

                        SpawnGroupTemplateData group = cdata.spawnGroupData;
                        // If creature in manual spawn group, don't spawn here, unless group is already active.
                        if (!group.flags.HasAnyFlag(SpawnGroupFlags.System))
                        {
                            if (!map.IsSpawnGroupActive(group.groupId))
                            {
                                obj.Dispose();
                                continue;
                            }
                        }

                        // If script is blocking spawn, don't spawn but queue for a re-check in a little bit
                        if (!group.flags.HasFlag(SpawnGroupFlags.CompatibilityMode) && !Global.ScriptMgr.CanSpawn(guid, cdata.Id, cdata, map))
                        {
                            map.SaveRespawnTime(SpawnObjectType.Creature, guid, cdata.Id, GameTime.GetGameTime() + RandomHelper.URand(4, 7), map.GetZoneId(PhasingHandler.EmptyPhaseShift, cdata.spawnPoint), GridDefines.ComputeGridCoord(cdata.spawnPoint.GetPositionX(), cdata.spawnPoint.GetPositionY()).GetId(), false);
                            obj.Dispose();
                            continue;
                        }
                    }
                    else if (obj.IsTypeId(TypeId.GameObject))
                    {
                        // If gameobject in manual spawn group, don't spawn here, unless group is already active.
                        GameObjectData godata = Global.ObjectMgr.GetGameObjectData(guid);
                        Cypher.Assert(godata != null, $"Tried to load gameobject with spawnId {guid}, but no such object exists.");

                        if (!godata.spawnGroupData.flags.HasAnyFlag(SpawnGroupFlags.System))
                        {
                            if (!map.IsSpawnGroupActive(godata.spawnGroupData.groupId))
                            {
                                obj.Dispose();
                                continue;
                            }
                        }
                    }

                    if (!obj.LoadFromDB(guid, map, false, false))
                    {
                        obj.Dispose();
                        continue;
                    }
                    AddObjectHelper(cell, ref count, map, obj);
                }
                else
                {
                    obj.Dispose();
                }
            }
        }
コード例 #6
0
    private static void GenUICode(GameObject root, GameObjectData data)
    {
        List <GameObject> controls = new List <GameObject>(); // 装所有控件
        List <GameObject> groups   = new List <GameObject>(); //

        Traverse(root, controls, groups, false);
        Dictionary <string, int> usedNames = new Dictionary <string, int>();

        //如果原先有代码生成,就先将原来的添加到gameobjectList中
        List <string> gameobjectList = getGameobjectStrListByFlag(ToolsConst.UI_CODE_PATH + root.name + ".cs"); //这个是代码原有的
        Dictionary <string, GameObject> gameObjectDic = TransListToDic(controls);                               //将所有的控件建立名字和GameObject映射,这个是重新生成的

        string flag = string.Empty;

        if (gameobjectList.Count > 0)
        {
            for (int i = 0; i < gameobjectList.Count; i++)
            {
                if (gameObjectDic.ContainsKey(gameobjectList[i]))           //如果有这个控件包含了列表该元素
                {
                    data.GameObjects.Add(gameObjectDic[gameobjectList[i]]); //添加这个对象到data中
                    flag += gameobjectList[i] + ",";                        //添加标记
                    gameObjectDic.Remove(gameobjectList[i]);                //移除字典里该元素
                    //UnityEditor.EditorUtility.DisplayProgressBar(gameobjectList[i], "", (float)i/(float));
                    continue;
                }
            }
        }
        //这是原来代码没有的控件
        foreach (KeyValuePair <string, GameObject> go in gameObjectDic)
        {
            data.GameObjects.Add(go.Value);
            flag += go.Value.name + ",";
        }

        //Generator
        Generator gen = new Generator();

        //将标记写入文本中
        if (flag.Contains(","))
        {
            flag = flag.Substring(0, flag.LastIndexOf(","));
        }
        gen.Println("//-L-<" + flag + ">");
        gen.Println("using UnityEngine;");
        gen.Println();
        gen.Println("public partial class " + root.name + " : View");
        gen.Println("{");
        gen.AddIndent();
        foreach (GameObject controlObject in data.GameObjects) //遍历控件对象 声明变量
        {
            int    times = 1;
            string name  = controlObject.name;
            if (usedNames.TryGetValue(name, out times))
            {
                name = name + "_" + times;
                ++times;
            }
            usedNames[controlObject.name] = times;

            GroupName groupName = controlObject.GetComponent <GroupName>();
            //如果有UIGameObjectList组件
            if (controlObject.GetComponent <UIGameObjectList>() != null)
            {
                gen.Printfln("private GameObject[] {0};", name); //声明这个数组
                gen.Printfln("private GameObject {0}Obj;", name);
            }
            else if (groupName == null) //如果没有组
            {
                gen.Println("private GameObject " + name + ";");
            }
            else
            {
                gen.Printfln("private {0} {1};", groupName.groupName, name);
            }
        }
        gen.Println();
        gen.Println("protected override void Awake()");
        gen.Println("{");
        gen.AddIndent();
        gen.Println("base.Awake();");
        gen.Println();
        gen.Println("GameObjectData data = gameObject.GetComponent<GameObjectData>();");
        usedNames.Clear();
        for (int i = 0, max = data.GameObjects.Count; i < max; i++)
        {
            int    times = 1;
            string name  = data.GameObjects[i].name;
            if (usedNames.TryGetValue(name, out times))
            {
                name = name + "_" + times;
                ++times;
            }
            usedNames[data.GameObjects[i].name] = times;

            GroupName groupName = data.GameObjects[i].GetComponent <GroupName>();
            //如果有UIGameObjectList
            if (data.GameObjects[i].GetComponent <UIGameObjectList>() != null)
            {
                gen.Printfln("{0} = data.GameObjects[{1}].gameObject.GetComponent<UIGameObjectList>().objects;", name, i.ToString());
                gen.Printfln("{0}Obj = data.GameObjects[{1}].gameObject;", name, i.ToString());

                //gen.Printfln("{0} = transform.Find(@\"{1}\").gameObject.GetComponent<UIGameObjectList>().objects;", name, GetPath(controls[i], root));
                //gen.Printfln("{0}Obj = transform.Find(@\"{1}\").gameObject;", name, GetPath(controls[i], root));
            }
            else if (groupName == null)
            {
                gen.Println(name + " =  data.GameObjects[" + i.ToString() + "].gameObject;");
                //gen.Println(name + " =  transform.Find(@\"" + GetPath(controls[i], root) + "\").gameObject;");
            }
            else
            {
                gen.Printfln("{0} = View.AddComponentIfNotExist<{1}>(data.GameObjects[" + i.ToString() + "].gameObject);", name, groupName.groupName);

                //gen.Printfln("{0} = View.AddComponentIfNotExist<{2}>(transform.Find(@\"{1}\").gameObject);", name, GetPath(controls[i], root), groupName.groupName);
            }
        }

        gen.Println("ViewMgr.Ins.addView(this);");
        gen.ReduceIndent();
        gen.Println("}");
        gen.Println();

        HashSet <string> groupNames = new HashSet <string>();

        foreach (GameObject group in groups)
        {
            string groupName = group.GetComponent <GroupName>().groupName;
            if (groupNames.Contains(groupName))
            {
                continue;
            }

            GenGroupCode(group); //生成Group 代码
            groupNames.Add(groupName);
            gen.Println();
        }

        gen.ReduceIndent();
        gen.Println("}");
        StreamWriter sw = new StreamWriter(ToolsConst.UI_CODE_PATH + root.name + ".cs", false);

        sw.Write(gen.GetContent());
        sw.Flush();
        sw.Close();
    }
コード例 #7
0
ファイル: PoolManager.cs プロジェクト: jungrok5/CypherCore
        public void LoadFromDB()
        {
            // Pool templates
            {
                uint oldMSTime = Time.GetMSTime();

                SQLResult result = DB.World.Query("SELECT entry, max_limit FROM pool_template");
                if (result.IsEmpty())
                {
                    mPoolTemplate.Clear();
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 object pools. DB table `pool_template` is empty.");
                    return;
                }

                uint count = 0;
                do
                {
                    uint pool_id = result.Read <uint>(0);

                    PoolTemplateData pPoolTemplate = new PoolTemplateData();
                    pPoolTemplate.MaxLimit = result.Read <uint>(1);
                    mPoolTemplate[pool_id] = pPoolTemplate;
                    ++count;
                }while (result.NextRow());

                Log.outInfo(LogFilter.ServerLoading, "Loaded {0} objects pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
            }

            // Creatures

            Log.outInfo(LogFilter.ServerLoading, "Loading Creatures Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                //                                                 1       2         3
                SQLResult result = DB.World.Query("SELECT guid, pool_entry, chance FROM pool_creature");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 creatures in  pools. DB table `pool_creature` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        ulong guid    = result.Read <ulong>(0);
                        uint  pool_id = result.Read <uint>(1);
                        float chance  = result.Read <float>(2);

                        CreatureData data = Global.ObjectMgr.GetCreatureData(guid);
                        if (data == null)
                        {
                            Log.outError(LogFilter.Sql, "`pool_creature` has a non existing creature spawn (GUID: {0}) defined for pool id ({1}), skipped.", guid, pool_id);
                            continue;
                        }
                        if (!mPoolTemplate.ContainsKey(pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_creature` pool id ({0}) is not in `pool_template`, skipped.", pool_id);
                            continue;
                        }
                        if (chance < 0 || chance > 100)
                        {
                            Log.outError(LogFilter.Sql, "`pool_creature` has an invalid chance ({0}) for creature guid ({1}) in pool id ({2}), skipped.", chance, guid, pool_id);
                            continue;
                        }
                        PoolTemplateData pPoolTemplate = mPoolTemplate[pool_id];
                        PoolObject       plObject      = new PoolObject(guid, chance);

                        if (!mPoolCreatureGroups.ContainsKey(pool_id))
                        {
                            mPoolCreatureGroups[pool_id] = new PoolGroup <Creature>();
                        }

                        PoolGroup <Creature> cregroup = mPoolCreatureGroups[pool_id];
                        cregroup.SetPoolId(pool_id);
                        cregroup.AddEntry(plObject, pPoolTemplate.MaxLimit);

                        mCreatureSearchMap.Add(guid, pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} creatures in pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // Gameobjects

            Log.outInfo(LogFilter.ServerLoading, "Loading Gameobject Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                //                                                 1        2         3
                SQLResult result = DB.World.Query("SELECT guid, pool_entry, chance FROM pool_gameobject");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 gameobjects in  pools. DB table `pool_gameobject` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        ulong guid    = result.Read <ulong>(0);
                        uint  pool_id = result.Read <uint>(1);
                        float chance  = result.Read <float>(2);

                        GameObjectData data = Global.ObjectMgr.GetGOData(guid);
                        if (data == null)
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` has a non existing gameobject spawn (GUID: {0}) defined for pool id ({1}), skipped.", guid, pool_id);
                            continue;
                        }

                        GameObjectTemplate goinfo = Global.ObjectMgr.GetGameObjectTemplate(data.id);
                        if (goinfo.type != GameObjectTypes.Chest &&
                            goinfo.type != GameObjectTypes.FishingHole &&
                            goinfo.type != GameObjectTypes.GatheringNode &&
                            goinfo.type != GameObjectTypes.Goober)
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` has a not lootable gameobject spawn (GUID: {0}, type: {1}) defined for pool id ({2}), skipped.", guid, goinfo.type, pool_id);
                            continue;
                        }

                        if (!mPoolTemplate.ContainsKey(pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` pool id ({0}) is not in `pool_template`, skipped.", pool_id);
                            continue;
                        }

                        if (chance < 0 || chance > 100)
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` has an invalid chance ({0}) for gameobject guid ({1}) in pool id ({2}), skipped.", chance, guid, pool_id);
                            continue;
                        }

                        PoolTemplateData pPoolTemplate = mPoolTemplate[pool_id];
                        PoolObject       plObject      = new PoolObject(guid, chance);

                        if (!mPoolGameobjectGroups.ContainsKey(pool_id))
                        {
                            mPoolGameobjectGroups[pool_id] = new PoolGroup <GameObject>();
                        }

                        PoolGroup <GameObject> gogroup = mPoolGameobjectGroups[pool_id];
                        gogroup.SetPoolId(pool_id);
                        gogroup.AddEntry(plObject, pPoolTemplate.MaxLimit);

                        mGameobjectSearchMap.Add(guid, pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} gameobject in pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // Pool of pools

            Log.outInfo(LogFilter.ServerLoading, "Loading Mother Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                //                                                  1        2            3
                SQLResult result = DB.World.Query("SELECT pool_id, mother_pool, chance FROM pool_pool");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 pools in pools");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  child_pool_id  = result.Read <uint>(0);
                        uint  mother_pool_id = result.Read <uint>(1);
                        float chance         = result.Read <float>(2);

                        if (!mPoolTemplate.ContainsKey(mother_pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` mother_pool id ({0}) is not in `pool_template`, skipped.", mother_pool_id);
                            continue;
                        }
                        if (!mPoolTemplate.ContainsKey(child_pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` included pool_id ({0}) is not in `pool_template`, skipped.", child_pool_id);
                            continue;
                        }
                        if (mother_pool_id == child_pool_id)
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` pool_id ({0}) includes itself, dead-lock detected, skipped.", child_pool_id);
                            continue;
                        }
                        if (chance < 0 || chance > 100)
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` has an invalid chance ({0}) for pool id ({1}) in mother pool id ({2}), skipped.", chance, child_pool_id, mother_pool_id);
                            continue;
                        }
                        PoolTemplateData pPoolTemplateMother = mPoolTemplate[mother_pool_id];
                        PoolObject       plObject            = new PoolObject(child_pool_id, chance);

                        if (!mPoolPoolGroups.ContainsKey(mother_pool_id))
                        {
                            mPoolPoolGroups[mother_pool_id] = new PoolGroup <Pool>();
                        }

                        PoolGroup <Pool> plgroup = mPoolPoolGroups[mother_pool_id];
                        plgroup.SetPoolId(mother_pool_id);
                        plgroup.AddEntry(plObject, pPoolTemplateMother.MaxLimit);

                        mPoolSearchMap.Add(child_pool_id, mother_pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} pools in mother pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            Log.outInfo(LogFilter.ServerLoading, "Loading Quest Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                PreparedStatement stmt   = DB.World.GetPreparedStatement(WorldStatements.SEL_QUEST_POOLS);
                SQLResult         result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 quests in pools");
                }
                else
                {
                    List <uint> creBounds;
                    List <uint> goBounds;

                    Dictionary <uint, eQuestTypes> poolTypeMap = new Dictionary <uint, eQuestTypes>();
                    uint count = 0;
                    do
                    {
                        uint entry   = result.Read <uint>(0);
                        uint pool_id = result.Read <uint>(1);

                        if (!poolTypeMap.ContainsKey(pool_id))
                        {
                            poolTypeMap[pool_id] = 0;
                        }

                        Quest quest = Global.ObjectMgr.GetQuestTemplate(entry);
                        if (quest == null)
                        {
                            Log.outError(LogFilter.Sql, "`pool_quest` has a non existing quest template (Entry: {0}) defined for pool id ({1}), skipped.", entry, pool_id);
                            continue;
                        }

                        if (!mPoolTemplate.ContainsKey(pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_quest` pool id ({0}) is not in `pool_template`, skipped.", pool_id);
                            continue;
                        }

                        if (!quest.IsDailyOrWeekly())
                        {
                            Log.outError(LogFilter.Sql, "`pool_quest` has an quest ({0}) which is not daily or weekly in pool id ({1}), use ExclusiveGroup instead, skipped.", entry, pool_id);
                            continue;
                        }

                        if (poolTypeMap[pool_id] == eQuestTypes.None)
                        {
                            poolTypeMap[pool_id] = quest.IsDaily() ? eQuestTypes.Daily : eQuestTypes.Weekly;
                        }

                        eQuestTypes currType = quest.IsDaily() ? eQuestTypes.Daily : eQuestTypes.Weekly;

                        if (poolTypeMap[pool_id] != currType)
                        {
                            Log.outError(LogFilter.Sql, "`pool_quest` quest {0} is {1} but pool ({2}) is specified for {3}, mixing not allowed, skipped.",
                                         entry, currType, pool_id, poolTypeMap[pool_id]);
                            continue;
                        }

                        creBounds = mQuestCreatureRelation.LookupByKey(entry);
                        goBounds  = mQuestGORelation.LookupByKey(entry);

                        if (creBounds.Empty() && goBounds.Empty())
                        {
                            Log.outError(LogFilter.Sql, "`pool_quest` lists entry ({0}) as member of pool ({1}) but is not started anywhere, skipped.", entry, pool_id);
                            continue;
                        }

                        PoolTemplateData pPoolTemplate = mPoolTemplate[pool_id];
                        PoolObject       plObject      = new PoolObject(entry, 0.0f);

                        if (!mPoolQuestGroups.ContainsKey(pool_id))
                        {
                            mPoolQuestGroups[pool_id] = new PoolGroup <Quest>();
                        }

                        PoolGroup <Quest> questgroup = mPoolQuestGroups[pool_id];
                        questgroup.SetPoolId(pool_id);
                        questgroup.AddEntry(plObject, pPoolTemplate.MaxLimit);

                        mQuestSearchMap.Add(entry, pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} quests in pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // The initialize method will spawn all pools not in an event and not in another pool, this is why there is 2 left joins with 2 null checks
            Log.outInfo(LogFilter.ServerLoading, "Starting objects pooling system...");
            {
                uint oldMSTime = Time.GetMSTime();

                SQLResult result = DB.World.Query("SELECT DISTINCT pool_template.entry, pool_pool.pool_id, pool_pool.mother_pool FROM pool_template" +
                                                  " LEFT JOIN game_event_pool ON pool_template.entry=game_event_pool.pool_entry" +
                                                  " LEFT JOIN pool_pool ON pool_template.entry=pool_pool.pool_id WHERE game_event_pool.pool_entry IS NULL");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Pool handling system initialized, 0 pools spawned.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint pool_entry   = result.Read <uint>(0);
                        uint pool_pool_id = result.Read <uint>(1);

                        if (!CheckPool(pool_entry))
                        {
                            if (pool_pool_id != 0)
                            {
                                // The pool is a child pool in pool_pool table. Ideally we should remove it from the pool handler to ensure it never gets spawned,
                                // however that could recursively invalidate entire chain of mother pools. It can be done in the future but for now we'll do nothing.
                                Log.outError(LogFilter.Sql, "Pool Id {0} has no equal chance pooled entites defined and explicit chance sum is not 100. This broken pool is a child pool of Id {1} and cannot be safely removed.", pool_entry, result.Read <uint>(2));
                            }
                            else
                            {
                                Log.outError(LogFilter.Sql, "Pool Id {0} has no equal chance pooled entites defined and explicit chance sum is not 100. The pool will not be spawned.", pool_entry);
                            }
                            continue;
                        }

                        // Don't spawn child pools, they are spawned recursively by their parent pools
                        if (pool_pool_id == 0)
                        {
                            SpawnPool(pool_entry);
                            count++;
                        }
                    }while (result.NextRow());

                    Log.outDebug(LogFilter.Pool, "Pool handling system initialized, {0} pools spawned in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }
        }
コード例 #8
0
    void OnGUI()
    {
        foreach (GameObject item in gameManager.Pool.Values)
        {
            GameObjectData data = item.GetComponent <Structure>().Data;

            if (data.identifier == GameObjectType.Miner ||
                data.identifier == GameObjectType.Stronghold ||
                data.identifier == GameObjectType.MineralStorage)
            {
                Vector3 point = GameObject.FindGameObjectWithTag("MainCamera").GetComponent <Camera>().WorldToScreenPoint(item.transform.position);
                point.y = (720 - point.y);
                GUI.Label(new Rect(point.x, point.y, 20, 100), ("M:" + data.productionQty), minersStyle);
            }

            //Show minerals in asteroid
            if (data.identifier == GameObjectType.Asteroid)
            {
                Vector3 point = GameObject.FindGameObjectWithTag("MainCamera").GetComponent <Camera>().WorldToScreenPoint(item.transform.position);
                point.y = (720 - point.y);
                GUI.Label(new Rect(point.x, point.y, 20, 100), ("" + data.productionQty), debugStyle);
            }

            //Show solar station energy level
            if (data.identifier == GameObjectType.SolarStation || data.identifier == GameObjectType.EnergyStorage)
            {
                Vector3 point = GameObject.FindGameObjectWithTag("MainCamera").GetComponent <Camera>().WorldToScreenPoint(item.transform.position);
                point.y = (720 - point.y);
                GUI.Label(new Rect(point.x, point.y, 20, 100), ("E:" + data.productionQty), solarStyle);
            }

            // //Show energy storage on battery
            // if (data.identifier == GameObjectType.EnergyStorage )
            // {
            //     Vector3 point = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>().WorldToScreenPoint(item.transform.position);
            //     point.y = (720 - point.y);
            //     GUI.Label(new Rect(point.x, point.y, 20, 100), ("E:" + data.productionQty), debugStyle);
            // }
        }

        //Player buttons
        xpos = 10;
        ypos = (screenHeight - (buttonHeight + 10));
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Solar\nStation", buttonStyle))
        {
            gameManager.addSolarStation();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Enegy\nStorage", buttonStyle))
        {
            gameManager.addEnegyStorage();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Mineral\nStorage", buttonStyle))
        {
            gameManager.addMineralStorage();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Relay", buttonStyle))
        {
            gameManager.addRelay();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Repair\nStation", buttonStyle))
        {
            gameManager.addRepairStation();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Miner", buttonStyle))
        {
            gameManager.addMiner();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Laser", buttonStyle))
        {
            gameManager.addLaser();
        }

        xpos += (buttonWidth + 10);
        if (GUI.Button(new Rect(xpos, ypos, buttonWidth, buttonHeight), "Missile\nLaunher", buttonStyle))
        {
            gameManager.addMissileLauncher();
        }


        //Player data
        xpos = 10;
        ypos = 10;
        GUI.Label(new Rect(xpos, ypos, 100, 50), string.Concat("Cash:", gameManager.player.Cash), style);

        //Game object data
        if (currentObject != null)
        {
            ypos += 40;
            GUI.Label(new Rect(xpos, ypos, 220, 20), "Current Structure", style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Identifier: ", this.currentObject.Data.identifier), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Price: ", this.currentObject.Data.price), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Name: ", this.currentObject.name), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Health: ", this.currentObject.Data.health), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Damage: ", this.currentObject.Data.damage), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Armor: ", this.currentObject.Data.armor), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Damage: ", this.currentObject.Data.damage), style);
            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("index: ", this.currentObject.ConnectionIndex), style);


            string text = "";
            foreach (int item in this.currentObject.Data.ins)
            {
                text += item;
                text += ", ";
            }

            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("ins: ", text), style);

            text = "";
            foreach (int item in this.currentObject.Data.outs)
            {
                text += item;
                text += ", ";
            }

            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("outs: ", text), style);

            ypos += 25;
            GUI.Label(new Rect(xpos, ypos, 220, 20), string.Concat("Energy Require: ", this.currentObject.Data.energyRequire), style);

            ypos += 30;
            if (GUI.Button(new Rect(xpos, ypos, 220, 40), string.Concat("Upgrade:", this.currentObject.Data.upgradePrice), buttonStyle))
            {
            }

            ypos += 45;
            if (GUI.Button(new Rect(xpos, ypos, 220, 40), string.Concat("Sale:", (this.currentObject.Data.price * this.currentObject.Data.priceLost)), buttonStyle))
            {
            }
        }

        //Level creation data
        ypos += 45;
        GUI.Label(new Rect(xpos, ypos, 220, 20), ("Level: " + gameManager.DataManager.CurrenLevel), style);

        ypos += 25;
        gameManager.DataManager.CurrenLevel = GUI.TextField(new Rect(xpos, ypos, 220, 20), gameManager.DataManager.CurrenLevel);

        ypos += 30;
        if (GUI.Button(new Rect(xpos, ypos, 40, 40), "1", buttonStyle))
        {
            gameManager.addAsteroid(1);
        }

        xpos += 45;
        if (GUI.Button(new Rect(xpos, ypos, 40, 40), "2", buttonStyle))
        {
            gameManager.addAsteroid(2);
        }

        xpos += 45;
        if (GUI.Button(new Rect(xpos, ypos, 40, 40), "3", buttonStyle))
        {
            gameManager.addAsteroid(3);
        }

        xpos += 45;
        if (GUI.Button(new Rect(xpos, ypos, 40, 40), "4", buttonStyle))
        {
            gameManager.addAsteroid(4);
        }

        xpos += 45;
        if (GUI.Button(new Rect(xpos, ypos, 40, 40), "5", buttonStyle))
        {
            gameManager.addAsteroid(5);
        }

        xpos  = 10;
        ypos += 45;
        if (GUI.Button(new Rect(xpos, ypos, 220, 40), "Load", buttonStyle))
        {
            //gameManager.DataManager.loadGameLevelsData();
        }

        ypos += 45;
        if (GUI.Button(new Rect(xpos, ypos, 220, 40), "Save", buttonStyle))
        {
            gameManager.saveLevelData();
        }
    }
コード例 #9
0
ファイル: MapScript.cs プロジェクト: kurisu9az/FlyingGameDemo
        private void LoadGameObject(List <CommonEntity> mapPart, Vector3Data startPositon, GameObjectData data)
        {
            CommonEntity entity = EntityFactory.InstanceEntity <CommonEntity>();

            entity.Create(m_container, data.path);

            TransformData transformData = new TransformData(AddVector3Data(startPositon, data.transformData.position),
                                                            data.transformData.rotation, data.transformData.scale);

            entity.InitTransform(transformData);

            mapPart.Add(entity);
        }
コード例 #10
0
        private void init()
        {
            GameObject        _go, _prefab;
            int               _len = objList.Count;
            List <GameObject> _list;
            GameObjectData    _dataList;
            Transform         _parent;
            bool              _bUI;
            int               _count, i, j;

            for (j = 0; j < _len; j++)
            {
                _prefab = objList [j].prefab;
                _count  = objList [j].count;
                _parent = objList [j].parent;
                _bUI    = objList [j].bUI;
                if (_parent == null)
                {
                    _parent            = transform;
                    objList [j].parent = transform;
                }

                if (_count <= 0)
                {
                    _count = 1;
                }
                //Debug.Log (_prefab.name + ":" + _prefab.name.IndexOf ("Ui") + ":" +_prefab.name.Contains("Ui") + ":" + _prefab.name.Contains("UI"));
                if (poolList.ContainsKey(_prefab))
                {
                    Debug.LogWarning((j + 1) + "번째 풀링 프리펩이 동일 GameObject 풀링 : " + _prefab);
                    continue;
                }
                else if (_prefab == null)
                {
                    Debug.LogWarning((j + 1) + "번째 풀링 프리펩이 활당되지 않음.");
                    continue;
                }
                else if (_bUI && objList [j].parent == null)
                {
                    Debug.LogWarning((j + 1) + "번째 풀링 " + _prefab.name + "는 UiRoot밑에 Ui_MsgRoot가 있는 곳에 넣어 주셔야 합니다.");
                    continue;
                }

                _list     = new List <GameObject> ();
                _dataList = new GameObjectData(_list, _count);
                poolList.Add(_prefab, _dataList);
                poolListName.Add(_prefab.name.GetHashCode(), _prefab);
                for (i = 0; i < _count; i++)
                {
                    //Debug.Log ("create > c");
                    _go = Instantiate(_prefab) as GameObject;
                    _go.transform.SetParent(_parent);
                    //Debug.Log ("create > t");
                    _go.SetActive(false);
                    //Debug.Log ("create > f");
                    _list.Add(_go);
                    _go.name += i.ToString();
                    //NGUITools.AddChild (_prefab);
                    if (_bUI)
                    {
                        _go.transform.localScale = Vector3.one;
                    }
                }
            }
        }
コード例 #11
0
        static bool HandleGameObjectInfoCommand(CommandHandler handler, StringArguments args)
        {
            if (args.Empty())
            {
                return(false);
            }

            string param1 = handler.ExtractKeyFromLink(args, "Hgameobject_entry");

            if (param1.IsEmpty())
            {
                return(false);
            }

            GameObject     thisGO = null;
            GameObjectData data   = null;

            uint  entry;
            ulong spawnId = 0;

            if (param1.Equals("guid"))
            {
                string cValue = handler.ExtractKeyFromLink(args, "Hgameobject");
                if (cValue.IsEmpty())
                {
                    return(false);
                }

                if (!ulong.TryParse(cValue, out spawnId))
                {
                    return(false);
                }

                data = Global.ObjectMgr.GetGameObjectData(spawnId);
                if (data == null)
                {
                    handler.SendSysMessage(CypherStrings.CommandObjnotfound, spawnId);
                    return(false);
                }

                entry  = data.Id;
                thisGO = handler.GetObjectFromPlayerMapByDbGuid(spawnId);
            }
            else
            {
                if (!uint.TryParse(param1, out entry))
                {
                    return(false);
                }
            }

            GameObjectTemplate gameObjectInfo = Global.ObjectMgr.GetGameObjectTemplate(entry);

            if (gameObjectInfo == null)
            {
                handler.SendSysMessage(CypherStrings.GameobjectNotExist, entry);
                return(false);
            }

            GameObjectTypes type      = gameObjectInfo.type;
            uint            displayId = gameObjectInfo.displayId;
            string          name      = gameObjectInfo.name;
            uint            lootId    = gameObjectInfo.GetLootId();

            // If we have a real object, send some info about it
            if (thisGO != null)
            {
                handler.SendSysMessage(CypherStrings.SpawninfoGuidinfo, thisGO.GetGUID().ToString());
                handler.SendSysMessage(CypherStrings.SpawninfoCompatibilityMode, thisGO.GetRespawnCompatibilityMode());

                if (thisGO.GetGameObjectData() != null && thisGO.GetGameObjectData().spawnGroupData.groupId != 0)
                {
                    SpawnGroupTemplateData groupData = thisGO.ToGameObject().GetGameObjectData().spawnGroupData;
                    handler.SendSysMessage(CypherStrings.SpawninfoGroupId, groupData.name, groupData.groupId, groupData.flags, thisGO.GetMap().IsSpawnGroupActive(groupData.groupId));
                }

                GameObjectOverride goOverride = Global.ObjectMgr.GetGameObjectOverride(spawnId);
                if (goOverride == null)
                {
                    goOverride = Global.ObjectMgr.GetGameObjectTemplateAddon(entry);
                }
                if (goOverride != null)
                {
                    handler.SendSysMessage(CypherStrings.GoinfoAddon, goOverride.Faction, goOverride.Flags);
                }
            }

            if (data != null)
            {
                data.rotation.toEulerAnglesZYX(out float yaw, out float pitch, out float roll);
                handler.SendSysMessage(CypherStrings.SpawninfoSpawnidLocation, data.SpawnId, data.SpawnPoint.GetPositionX(), data.SpawnPoint.GetPositionY(), data.SpawnPoint.GetPositionZ());
                handler.SendSysMessage(CypherStrings.SpawninfoRotation, yaw, pitch, roll);
            }

            handler.SendSysMessage(CypherStrings.GoinfoEntry, entry);
            handler.SendSysMessage(CypherStrings.GoinfoType, type);
            handler.SendSysMessage(CypherStrings.GoinfoLootid, lootId);
            handler.SendSysMessage(CypherStrings.GoinfoDisplayid, displayId);
            handler.SendSysMessage(CypherStrings.GoinfoName, name);
            handler.SendSysMessage(CypherStrings.GoinfoSize, gameObjectInfo.size);

            handler.SendSysMessage(CypherStrings.ObjectInfoAIInfo, gameObjectInfo.AIName, Global.ObjectMgr.GetScriptName(gameObjectInfo.ScriptId));
            var ai = thisGO != null?thisGO.GetAI() : null;

            if (ai != null)
            {
                handler.SendSysMessage(CypherStrings.ObjectInfoAIType, nameof(ai));
            }

            GameObjectDisplayInfoRecord modelInfo = CliDB.GameObjectDisplayInfoStorage.LookupByKey(displayId);

            if (modelInfo != null)
            {
                handler.SendSysMessage(CypherStrings.GoinfoModel, modelInfo.GeoBoxMax.X, modelInfo.GeoBoxMax.Y, modelInfo.GeoBoxMax.Z, modelInfo.GeoBoxMin.X, modelInfo.GeoBoxMin.Y, modelInfo.GeoBoxMin.Z);
            }

            return(true);
        }
コード例 #12
0
    // Update is called once per frame
    void Update()
    {
        //if (Input.GetKeyDown(KeyCode.C))
        //{
        //    Connect();
        //}
        //if (Input.GetKeyDown(KeyCode.K))
        //{
        //    CreateGame("Test");
        //}
        //if (Input.GetKeyDown(KeyCode.J))
        //{
        //    JoinGame(playerName, lobbyCode);
        //}
        if (inLobby)
        {
            if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("game"))
            {
                inLobby = false;
                NetData n = new NetData("ready_start", "");
                sendData(JsonConvert.SerializeObject(n));
            }
        }
        if (!inLobby)
        {
            if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("lobby"))
            {
                inLobby = true;
            }
        }

        if (connected)
        {
            acceptedQueue.AddRange(queue);
            queue.Clear();
            updatedObjects.Clear();
            for (int i = acceptedQueue.Count - 1; i >= 0; i--)
            {
                NetData data = JsonConvert.DeserializeObject <NetData>(acceptedQueue[i]);
                if (data.type == "object")
                {
                    if (!updatedObjects.Contains(data.id))
                    {
                        GameObjectData gData = JsonConvert.DeserializeObject <GameObjectData>(data.value);
                        if (networkedObjects.ContainsKey(data.id))
                        {
                            GameObjectData.updateGameObject(gData, networkedObjects[data.id]);
                        }
                        else
                        {
                            Debug.Log(data.key);
                            GameObject g      = Instantiate(objects[objectNames.IndexOf(data.key)]);
                            NetObject  netObj = g.AddComponent <NetObject>();
                            netObj.id = data.id;
                            networkedObjects.Add(data.id, g);
                            GameObjectData.updateGameObject(gData, g);
                            if (data.key == "player")
                            {
                                string p_name = data.other[0];
                                if (p_name.EndsWith("?"))
                                {
                                    p_name = p_name.Substring(0, p_name.Length - 1);
                                }
                                g.transform.Find("Stats").GetChild(0).GetComponent <TextMeshProUGUI>().text = p_name;
                            }
                        }

                        updatedObjects.Add(data.id);
                    }
                }
                else if (data.type == "object_id")
                {
                    Debug.Log("New Object: " + data.id);
                    NetObject obj = waitlist[0].AddComponent <NetObject>();
                    obj.id = data.id;
                    sync.Add(data.id, waitlist[0]);
                    waitlist.RemoveAt(0);
                }
                else if (data.type == "game_start")
                {
                    gameStarted = true;
                    Debug.Log("Game Started");
                }
                else if (data.type == "animation")
                {
                    Animator anim = networkedObjects[data.id].GetComponent <Animator>();
                    if (data.key == "trigger")
                    {
                        anim.SetTrigger(data.value);
                    }
                    else
                    {
                        anim.SetBool(data.value, bool.Parse(data.key));
                    }
                }
                else if (data.type == "update_roster")
                {
                    string combinedRoster = "";
                    foreach (string n in data.other)
                    {
                        Debug.Log(n);
                        combinedRoster += n + ";";
                    }
                    combinedRoster = combinedRoster.Substring(0, combinedRoster.Length - 1);
                    PlayerPrefs.SetString("last_roster", combinedRoster);
                    Debug.Log(combinedRoster);
                    LobbyManager m = FindObjectOfType <LobbyManager>();
                    if (m != null)
                    {
                        m.UpdatePlayers(data.other);
                        int counter = 0;
                        foreach (string n in data.other)
                        {
                            Debug.Log(n);
                            if (n == nameUsed)
                            {
                                PlayerPrefs.SetInt("color", counter);
                                Debug.Log("Found Name: " + counter);
                                break;
                            }
                            counter++;
                        }
                    }
                }
                else if (data.type == "lobby_joined")
                {
                    Debug.Log("Joined Lobby: " + data.id);
                    PlayerPrefs.SetInt("joinedLobby", data.id);
                    inLobby = true;
                    SceneManager.LoadScene("lobby");
                }
                else if (data.type == "prepare_game")
                {
                    SceneManager.LoadScene("game");
                }
                else if (data.type == "recieve_damage")
                {
                    Debug.Log("Lost " + data.value + " health");
                    Vector3 enemyPosition = networkedObjects[int.Parse(data.key)].transform.position;
                    sync[data.id].GetComponent <PlayerController>().addKnockback(enemyPosition);
                    sync[data.id].GetComponent <PlayerController>().Damage(int.Parse(data.value));
                }
                else if (data.type == "join_failed")
                {
                    GameObject alertCanvas = Instantiate(alertPrefab);
                    Alert      alert       = alertCanvas.GetComponent <Alert>();
                    alert.ShowInput(false);
                    alert.ConfigureQuestion(data.key);
                    alert.Display(null);
                }
                else if (data.type == "destroy_beacon")
                {
                    Debug.Log("recieved Destroy Message");
                    BeaconManager manager = FindObjectOfType <BeaconManager>();
                    if (manager != null)
                    {
                        manager.DestoryBeacon(data.id);
                    }
                }
            }
            acceptedQueue.Clear();
            if (gameStarted)
            {
                timeCounter -= Time.deltaTime;
                if (timeCounter < 0)
                {
                    runGameSync();
                    timeCounter = 1 / 60;
                }
            }
        }
        if (disconnect)
        {
            Disconnect();
        }
    }
コード例 #13
0
    public PreFabData generatePrefabMap(Vector3[] meshCoordinates, MapData map, float maxHeight, float minHeight)
    {
        System.Random rand = new System.Random();

        nonce.placeable = false;
        int dim = (int)Mathf.Floor(Mathf.Sqrt(meshCoordinates.Length));

        GameObjectData[,] coordinateBasedPlacements = new GameObjectData[dim, dim];
        bool[,,] acceptableAssets = new bool[dim, dim, biomeGroups.Length];



        //initializes placement permission to true for all objects at each position
        for (int i = 1; i < dim; i++)
        {
            for (int j = 1; j < dim; j++)
            {
                for (int k = 0; k < biomeGroups.Length; k++)
                {
                    acceptableAssets[i, j, k] = true;
                }
            }
        }


        for (int k = 0; k < biomeGroups.Length; k++)
        {
            biomeGroups[k].representative.setIndex(k);
        }

        int total = 0;

        //Looks at each coordinate and attempts to instantiate a random Asset
        for (int i = 1; i < dim - 1; i++)
        {
            for (int j = 1; j < dim - 1; j++)
            {
                //Finds the percentage based height
                float        height  = lerp(minHeight, maxHeight, meshCoordinates[i * dim + j].y);
                AssetGroup[] options = new AssetGroup[biomeGroups.Length];

                int   validGroups  = 0;
                float totalDensity = 0;

                //loads all options available at the specified heights
                for (int k = 0; k < biomeGroups.Length; k++)
                {
                    if (height < biomeGroups[k].representative.end && height > biomeGroups[k].representative.start)
                    {
                        if (acceptableAssets[i, j, k])
                        {
                            options[validGroups] = biomeGroups[k].representative;
                            totalDensity        += biomeGroups[k].representative.density;
                            validGroups++;
                        }
                    }
                }
                float seed = Range(rand, 0, 1f);

                if (seed < overallDensity && validGroups != 0)
                {
                    AssetGroup group = weightedDiceRoleGroups(options, totalDensity, validGroups, rand);
                    if (group == null)
                    {
                        coordinateBasedPlacements[i, j] = nonce;
                    }
                    else
                    {
                        float totalProbability = 0;
                        for (int k = 0; k < group.assets.Length; k++)
                        {
                            totalProbability += group.assets[k].probability;
                        }
                        if (weightedDiceRoleAsset(group.assets, totalProbability, rand).orientAndPlace(i, j, height, coordinateBasedPlacements, acceptableAssets, group.getIndex(), group.claustraphobia, rand, nonce))
                        {
                            total++;
                        }
                    }
                }
                else
                {
                    coordinateBasedPlacements[i, j] = nonce;
                }
            }
        }


        GameObjectData[] ret         = new GameObjectData[total];
        float            distance    = (meshCoordinates[1].x - meshCoordinates[0].x);
        float            radius      = distance / 4;
        float            offset      = radius / distance;
        int            curr          = 0;
        int            wrong         = 0;
        float          magnification = (float)map.heightMap.GetLength(0) / dim;
        AnimationCurve curve         = new AnimationCurve(terrain.meshHeightCurve.keys);

        for (int i = 1; i < dim; i++)
        {
            for (int j = 1; j < dim; j++)
            {
                GameObjectData temp = coordinateBasedPlacements[i, j];
                if (temp != null && temp.placeable)
                {
                    float angle = Range(rand, 0, 360f);

                    int exZ = (int)((temp.position.x - offset * Mathf.Sin(angle)) * magnification) + 2;
                    int exX = (int)((temp.position.z + offset * Mathf.Sin(angle)) * magnification) + 2;

                    float z = (temp.position.x - dim / 2);
                    float x = (temp.position.z - dim / 2);

                    temp.position.z = (z) * distance * -1 + radius * Mathf.Sin(angle);
                    temp.position.x = (x) * distance + radius * Mathf.Cos(angle);



                    float tempX = (dim / 2 - (temp.position.x / distance) * magnification) + 2;
                    float tempZ = ((temp.position.z / distance + dim / 2) * magnification) + 2;

                    int iz = Mathf.Clamp((int)tempX, 0, map.heightMap.GetLength(0) - 1);
                    int ix = Mathf.Clamp((int)tempZ, 0, map.heightMap.GetLength(1) - 1);
                    iz = exZ;
                    ix = exX;

                    float y = curve.Evaluate(Mathf.Min(map.heightMap[ix, iz], map.heightMap[ix + 1, iz], map.heightMap[ix + 1, iz + 1], map.heightMap[ix, iz + 1]));

                    temp.position.y = y * terrain.mapHeightMultiplier;//temp.position.y * (maxHeight - minHeight) + minHeight;
                    ret[curr]       = temp;

                    curr++;
                }
                else
                {
                    wrong++;
                }
            }
        }

        /*
         * GameObject piece = ret[0].gamePiece;
         * ret = new GameObjectData[map.heightMap.Length];
         * float half = map.heightMap.GetLength(0) / 2;
         * for (int i = 0; i < map.heightMap.GetLength(0); i++)
         * {
         *  for (int j = 0; j < map.heightMap.GetLength(1); j++)
         *  {
         *
         *      GameObjectData toStore = new GameObjectData();
         *      toStore.placeable = true;
         *      toStore.position = new Vector3(i - half, curve.Evaluate(map.heightMap[i, j]) * terrain.mapHeightMultiplier, half - j);
         *      toStore.gamePiece = piece;
         *      toStore.rotation = Quaternion.identity;
         *      toStore.scale = Vector3.one;
         *      ret[i * map.heightMap.GetLength(0) + j] = toStore;
         *  }
         * }
         */
        PreFabData dataRet = new PreFabData();

        dataRet.prefabs = ret;

        return(dataRet);
    }
コード例 #14
0
        static GameObjectData AssessGameObject(GameObject go)
        {
            if (go == null)
            {
                return(null);
            }
            GameObjectData gd = new GameObjectData();

            gd.gameobject = go;
            foreach (Renderer r in go.GetComponentsInChildren <Renderer>(true))
            {
                Mesh mesh = null;
                if (r is SkinnedMeshRenderer)
                {
                    mesh = (r as SkinnedMeshRenderer).sharedMesh;
                }
                else
                {
                    MeshFilter mf = r.GetComponent <MeshFilter>();
                    if (mf != null)
                    {
                        mesh = mf.sharedMesh;
                    }
                }
                if (mesh == null)
                {
                    continue;
                }
                RendererData rd = new RendererData();
                rd.renderer = r;
                gd.renderers.Add(rd);
                Material[] mats  = r.sharedMaterials;
                Transform  trans = r.transform;
                vertices.Clear();
                uvs.Clear();
                mesh.GetVertices(vertices);
                mesh.GetUVs(0, uvs);
                for (int i = 0; i < mesh.subMeshCount; i++)
                {
                    Material     m  = i < mats.Length ? mats[i] : null;
                    MaterialData md = new MaterialData();
                    md.material = m;
                    rd.materials.Add(md);
                    if (m != null)
                    {
                        string mp = AssetDatabase.GetAssetPath(m);
                        if (string.IsNullOrEmpty(mp))
                        {
                            continue;
                        }
                        foreach (string tp in AssetDatabase.GetDependencies(mp, false))
                        {
                            Texture tex = AssetDatabase.LoadAssetAtPath <Texture>(tp);
                            if (tex == null)
                            {
                                continue;
                            }
                            TextureData td = new TextureData();
                            td.texture = tex;
                            md.textures.Add(td);
                        }
                    }
                    if (uvs.Count > 0)
                    {
                        md.duv_min = float.PositiveInfinity;
                        float weight = 0f;
                        triangles.Clear();
                        mesh.GetTriangles(triangles, i, false);
                        int index = 0;
                        //Debug.LogError(triangles.Count);
                        while (index < triangles.Count)
                        {
                            int     i0  = triangles[index++];
                            int     i1  = triangles[index++];
                            int     i2  = triangles[index++];
                            Vector3 v0  = vertices[i0];
                            Vector3 v1  = vertices[i1];
                            Vector3 v2  = vertices[i2];
                            Vector2 uv0 = uvs[i0];
                            Vector2 uv1 = uvs[i1];
                            Vector2 uv2 = uvs[i2];
                            //Debug.LogWarningFormat("{0} - {1} - {2}", v0, v1, v2);
                            v0 = trans.TransformPoint(v0);
                            v1 = trans.TransformPoint(v1);
                            v2 = trans.TransformPoint(v2);
                            //Debug.LogWarningFormat("{0} - {1} - {2}", v0, v1, v2);
                            //Debug.LogWarningFormat("{0} - {1} - {2}", uv0, uv1, uv2);
                            float dis0 = (v1 - v0).magnitude;
                            float dis1 = (v2 - v1).magnitude;
                            float dis2 = (v0 - v2).magnitude;
                            float duv0 = (uv1 - uv0).magnitude / dis0;
                            float duv1 = (uv2 - uv1).magnitude / dis1;
                            float duv2 = (uv0 - uv2).magnitude / dis2;
                            float s    = 0.25f * Mathf.Sqrt((dis0 + dis1 + dis2) * (dis0 + dis1 - dis2) * (dis0 + dis2 - dis1) * (dis1 + dis2 - dis0));
                            md.duv_min  = Mathf.Min(md.duv_min, duv0);
                            md.duv_min  = Mathf.Min(md.duv_min, duv1);
                            md.duv_min  = Mathf.Min(md.duv_min, duv2);
                            md.duv_max  = Mathf.Max(md.duv_max, duv0);
                            md.duv_max  = Mathf.Max(md.duv_max, duv1);
                            md.duv_max  = Mathf.Max(md.duv_max, duv2);
                            md.duv_avg += (duv0 + duv1 + duv2) * s;
                            weight     += s + s + s;
                        }
                        md.duv_avg /= weight;
                    }
                    //Debug.LogError(md.duv_min);
                    //Debug.LogWarning(md.duv_max);
                    //Debug.LogWarning(md.duv_avg);
                    //Debug.Log(weight);
                }
            }
            return(gd);
        }
コード例 #15
0
    private void createObject(string value, Vector3 position, bool doPriceCheck)
    {
        GameObjectData data = dataManager.findGameObjectData(value).Clone();

        bool canPlayerPurchaseObject = false;

        if (doPriceCheck)
        {
            if (player.hasEnoughCash(data.price))
            {
                canPlayerPurchaseObject = true;
            }
        }
        else
        {
            canPlayerPurchaseObject = true;
        }

        if (canPlayerPurchaseObject)
        {
            GameObject go;
            Structure  script;
            string     name = string.Concat(value, "_", objectCounter);

            switch (value)
            {
            case "stronghold":
                go         = Instantiate(strongholdPref, position, Quaternion.identity);
                stronghold = go;
                pool.Add(name, go);
                script = go.GetComponent <Stronghold>();
                break;

            case "solarStation1":
                go = Instantiate(solarStationPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <SolarStation>();
                break;

            case "enegyStorage1":
                go = Instantiate(enegyStoragePref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <EnegyStorage>();
                break;

            case "mineralStorage1":
                go = Instantiate(materialStoragePref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <MineralStorage>();
                break;

            case "cargoContainer":
                go = Instantiate(materialContainerPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <CargoContainer>();
                break;

            case "cargoDrone1":
                go = Instantiate(cargoDronePref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <CargoDrone>();
                break;

            case "relay1":
                go = Instantiate(relayPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Relay>();
                break;

            case "repairStation1":
                go = Instantiate(repairStationPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <RepairStation>();
                break;

            case "repairDrone1":
                go = Instantiate(repairDromePref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <RepairDrone>();
                break;

            case "miner1":
                go = Instantiate(minerPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Miner>();
                break;

            case "asteroid1":
                go = Instantiate(asteroid1Pref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Asteroid>();
                break;

            case "asteroid2":
                go = Instantiate(asteroid2Pref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Asteroid>();
                break;

            case "asteroid3":
                go = Instantiate(asteroid3Pref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Asteroid>();
                break;

            case "asteroid4":
                go = Instantiate(asteroid4Pref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Asteroid>();
                break;

            case "asteroid5":
                go = Instantiate(asteroid5Pref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Asteroid>();
                break;

            case "laser1":
                go = Instantiate(laserPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <Laser>();
                break;

            case "missileLauncher1":
                go = Instantiate(missileLauncherPref, position, Quaternion.identity);
                pool.Add(name, go);
                script = go.GetComponent <MissileLauncher>();
                break;

            default:
                go     = null;
                script = null;
                break;
            }

            if (go != null)
            {
                go.name            = name;
                script.Data        = data;
                script.GameManager = this;
                objectCounter++;
            }
        }
    }
コード例 #16
0
        static bool HandleGameObjectInfoCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string param1 = handler.ExtractKeyFromLink(args, "Hgameobject_entry");

            if (param1.IsEmpty())
            {
                return(false);
            }

            uint entry;

            if (param1.Equals("guid"))
            {
                string cValue = handler.ExtractKeyFromLink(args, "Hgameobject");
                if (cValue.IsEmpty())
                {
                    return(false);
                }

                if (!ulong.TryParse(cValue, out ulong guidLow))
                {
                    return(false);
                }

                GameObjectData data = Global.ObjectMgr.GetGameObjectData(guidLow);
                if (data == null)
                {
                    return(false);
                }
                entry = data.Id;
            }
            else
            {
                if (!uint.TryParse(param1, out entry))
                {
                    return(false);
                }
            }

            GameObjectTemplate gameObjectInfo = Global.ObjectMgr.GetGameObjectTemplate(entry);

            if (gameObjectInfo == null)
            {
                return(false);
            }

            GameObject thisGO = null;

            if (handler.GetSession().GetPlayer())
            {
                thisGO = handler.GetSession().GetPlayer().FindNearestGameObject(entry, 30);
            }
            else if (handler.GetSelectedObject() != null && handler.GetSelectedObject().IsTypeId(TypeId.GameObject))
            {
                thisGO = handler.GetSelectedObject().ToGameObject();
            }

            GameObjectTypes type      = gameObjectInfo.type;
            uint            displayId = gameObjectInfo.displayId;
            string          name      = gameObjectInfo.name;
            uint            lootId    = gameObjectInfo.GetLootId();

            // If we have a real object, send some info about it
            if (thisGO != null)
            {
                handler.SendSysMessage(CypherStrings.SpawninfoGuidinfo, thisGO.GetGUID().ToString());
                handler.SendSysMessage(CypherStrings.SpawninfoSpawnidLocation, thisGO.GetSpawnId(), thisGO.GetPositionX(), thisGO.GetPositionY(), thisGO.GetPositionZ());
                Player player = handler.GetSession().GetPlayer();
                if (player != null)
                {
                    Position playerPos = player.GetPosition();
                    float    dist      = thisGO.GetExactDist(playerPos);
                    handler.SendSysMessage(CypherStrings.SpawninfoDistancefromplayer, dist);
                }
            }
            handler.SendSysMessage(CypherStrings.GoinfoEntry, entry);
            handler.SendSysMessage(CypherStrings.GoinfoType, type);
            handler.SendSysMessage(CypherStrings.GoinfoLootid, lootId);
            handler.SendSysMessage(CypherStrings.GoinfoDisplayid, displayId);
            WorldObject obj = handler.GetSelectedObject();

            if (obj != null)
            {
                if (obj.IsGameObject() && obj.ToGameObject().GetGameObjectData() != null && obj.ToGameObject().GetGameObjectData().spawnGroupData.groupId != 0)
                {
                    SpawnGroupTemplateData groupData = obj.ToGameObject().GetGameObjectData().spawnGroupData;
                    handler.SendSysMessage(CypherStrings.SpawninfoGroupId, groupData.name, groupData.groupId, groupData.flags, obj.GetMap().IsSpawnGroupActive(groupData.groupId));
                }
                if (obj.IsGameObject())
                {
                    handler.SendSysMessage(CypherStrings.SpawninfoCompatibilityMode, obj.ToGameObject().GetRespawnCompatibilityMode());
                }
            }
            handler.SendSysMessage(CypherStrings.GoinfoName, name);
            handler.SendSysMessage(CypherStrings.GoinfoSize, gameObjectInfo.size);

            GameObjectTemplateAddon addon = Global.ObjectMgr.GetGameObjectTemplateAddon(entry);

            if (addon != null)
            {
                handler.SendSysMessage(CypherStrings.GoinfoAddon, addon.faction, addon.flags);
            }

            GameObjectDisplayInfoRecord modelInfo = CliDB.GameObjectDisplayInfoStorage.LookupByKey(displayId);

            if (modelInfo != null)
            {
                handler.SendSysMessage(CypherStrings.GoinfoModel, modelInfo.GeoBoxMax.X, modelInfo.GeoBoxMax.Y, modelInfo.GeoBoxMax.Z, modelInfo.GeoBoxMin.X, modelInfo.GeoBoxMin.Y, modelInfo.GeoBoxMin.Z);
            }

            return(true);
        }
コード例 #17
0
        private GameObject InstantiateInner(GameObject _prefab, Vector3 _pos, Quaternion _qua)
        {
            if (!poolList.ContainsKey(_prefab))
            {
                Debug.LogError("풀링에 없음 _name[" + _prefab.name + "]");
                return(null);
            }

            GameObject        _rtn      = null;
            GameObjectData    _dataList = poolList [_prefab];
            List <GameObject> _list     = _dataList.list;

            if (!_list [_dataList.front].activeInHierarchy)
            {
                //Not use gameobject > return data
                _rtn = _list [_dataList.front];
                //Debug.Log ("used > f");
                _rtn.transform.position = _pos;                 //순서가 중요.
                _rtn.transform.rotation = _qua;
                _rtn.SetActive(true);
                //Debug.Log ("used > t");

                _dataList.front++;
                if (_dataList.front >= _dataList.max)
                {
                    _dataList.front = 0;
                }
            }
            else if (willGrow)
            {
                //not found the pooling gameobject and create gameobject
                //GameObject _goTemp = Instantiate (_prefab, _pos, _qua) as GameObject;
                //이상하게 위치 잡고 생성하면 오류나고 이렇게 해야만 한다...

                //이것도 안된다. ㅠㅠ.
                //Debug.Log ("create2 > .");
                //GameObject _goTemp = Instantiate ((GameObject)_prefab, _pos, _qua) as GameObject;             //유니티 자체가 멈춰버린다. ㅠㅠ
                //GameObject _goTemp = Instantiate (_prefab, _pos, _qua) as GameObject;                         //유니티 자체가 멈춰버린다. ㅠㅠ
                GameObject _goTemp = (Instantiate(_prefab.transform, _pos, _qua) as Transform).gameObject;                      //된다. ㅠㅠ.
                //Debug.Log ("create2 > I");
                //Debug.Log("create2 > I" + _goTemp.transform.position + ":" + _pos);

                //생성후(Awake, OnEnable) => 위치 음... 문제
                //1. Instantiate    ->  Awake()
                //				        OnEnable() -> 충돌, 체크 할 수 있다....
                //						*위치가 반영되었다고 생각했는데... > 순서 꼬임...
                //2. pos, qut		->  이제 위치 반영...
                //GameObject _goTemp = Instantiate (_prefab);
                //_goTemp.transform.position = _pos;
                //_goTemp.transform.rotation = _qua;
                //Debug.Log ("create2 > I");

                _goTemp.transform.SetParent(transform);
                _list.Insert(_dataList.front, _goTemp);
                _goTemp.name += _dataList.max.ToString();
                _rtn          = _goTemp;

                //Debug.Log ("add front:" + _dataList.front);

                _dataList.front++;
                _dataList.max++;
                if (_dataList.front >= _dataList.max)
                {
                    _dataList.front = 0;
                }
                //Debug.Log ("info front:" + _dataList.front + " max:" + _dataList.max);
            }
            else
            {
                Debug.LogWarning(" 성장이 아닌데 여유가 없다 > 논리 오류");
            }

            return(_rtn);
        }
コード例 #18
0
ファイル: ListCommands.cs プロジェクト: spadd/CypherCore
        static bool HandleListRespawnsCommand(StringArguments args, CommandHandler handler)
        {
            Player player = handler.GetSession().GetPlayer();
            Map    map    = player.GetMap();

            uint range = 0;

            if (!args.Empty())
            {
                range = args.NextUInt32();
            }

            List <RespawnInfo> respawns         = new();
            Locale             locale           = handler.GetSession().GetSessionDbcLocale();
            string             stringOverdue    = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsOverdue, locale);
            string             stringCreature   = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsCreatures, locale);
            string             stringGameobject = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsGameobjects, locale);

            uint zoneId = player.GetZoneId();

            if (range != 0)
            {
                handler.SendSysMessage(CypherStrings.ListRespawnsRange, stringCreature, range);
            }
            else
            {
                handler.SendSysMessage(CypherStrings.ListRespawnsZone, stringCreature, GetZoneName(zoneId, handler.GetSessionDbcLocale()), zoneId);
            }
            handler.SendSysMessage(CypherStrings.ListRespawnsListheader);
            map.GetRespawnInfo(respawns, SpawnObjectTypeMask.Creature, range != 0 ? 0 : zoneId);
            foreach (RespawnInfo ri in respawns)
            {
                CreatureData data = Global.ObjectMgr.GetCreatureData(ri.spawnId);
                if (data == null)
                {
                    continue;
                }

                if (range != 0 && !player.IsInDist(data.spawnPoint, range))
                {
                    continue;
                }

                uint gridY = ri.gridId / MapConst.MaxGrids;
                uint gridX = ri.gridId % MapConst.MaxGrids;

                string respawnTime = ri.respawnTime > Time.UnixTime ? Time.secsToTimeString((ulong)(ri.respawnTime - Time.UnixTime), true) : stringOverdue;
                handler.SendSysMessage($"{ri.spawnId} | {ri.entry} | [{gridX},{gridY}] | {GetZoneName(ri.zoneId, handler.GetSessionDbcLocale())} ({ri.zoneId}) | {(map.IsSpawnGroupActive(data.spawnGroupData.groupId) ? respawnTime : "inactive")}");
            }

            respawns.Clear();
            if (range != 0)
            {
                handler.SendSysMessage(CypherStrings.ListRespawnsRange, stringGameobject, range);
            }
            else
            {
                handler.SendSysMessage(CypherStrings.ListRespawnsZone, stringGameobject, GetZoneName(zoneId, handler.GetSessionDbcLocale()), zoneId);
            }
            handler.SendSysMessage(CypherStrings.ListRespawnsListheader);
            map.GetRespawnInfo(respawns, SpawnObjectTypeMask.GameObject, range != 0 ? 0 : zoneId);
            foreach (RespawnInfo ri in respawns)
            {
                GameObjectData data = Global.ObjectMgr.GetGameObjectData(ri.spawnId);
                if (data == null)
                {
                    continue;
                }

                if (range != 0 && !player.IsInDist(data.spawnPoint, range))
                {
                    continue;
                }

                uint gridY = ri.gridId / MapConst.MaxGrids;
                uint gridX = ri.gridId % MapConst.MaxGrids;

                string respawnTime = ri.respawnTime > Time.UnixTime ? Time.secsToTimeString((ulong)(ri.respawnTime - Time.UnixTime), true) : stringOverdue;
                handler.SendSysMessage($"{ri.spawnId} | {ri.entry} | [{gridX},{gridY}] | {GetZoneName(ri.zoneId, handler.GetSessionDbcLocale())} ({ri.zoneId}) | {(map.IsSpawnGroupActive(data.spawnGroupData.groupId) ? respawnTime : "inactive")}");
            }
            return(true);
        }
コード例 #19
0
ファイル: FireAbility.cs プロジェクト: fredu85/Solumaa
 public void Fire(GameObjectData data)
 {
     _GameObjectData = data;
     StartCoroutine(ArmsAnimation());
 }
コード例 #20
0
ファイル: PoolManager.cs プロジェクト: jungrok5/CypherCore
        void Spawn1Object(PoolObject obj)
        {
            switch (typeof(T).Name)
            {
            case "Creature":
                CreatureData data = Global.ObjectMgr.GetCreatureData(obj.guid);
                if (data != null)
                {
                    Global.ObjectMgr.AddCreatureToGrid(obj.guid, data);

                    // Spawn if necessary (loaded grids only)
                    Map map = Global.MapMgr.CreateBaseMap(data.mapid);
                    // We use spawn coords to spawn
                    if (!map.Instanceable() && map.IsGridLoaded(data.posX, data.posY))
                    {
                        Creature.CreateCreatureFromDB(obj.guid, map);
                    }
                }
                break;

            case "GameObject":
                GameObjectData data_ = Global.ObjectMgr.GetGOData(obj.guid);
                if (data_ != null)
                {
                    Global.ObjectMgr.AddGameObjectToGrid(obj.guid, data_);
                    // Spawn if necessary (loaded grids only)
                    // this base map checked as non-instanced and then only existed
                    Map map = Global.MapMgr.CreateBaseMap(data_.mapid);
                    // We use current coords to unspawn, not spawn coords since creature can have changed grid
                    if (!map.Instanceable() && map.IsGridLoaded(data_.posX, data_.posY))
                    {
                        GameObject go = GameObject.CreateGameObjectFromDB(obj.guid, map, false);
                        if (go)
                        {
                            if (go.isSpawnedByDefault())
                            {
                                map.AddToMap(go);
                            }
                        }
                    }
                }
                break;

            case "Pool":
                Global.PoolMgr.SpawnPool((uint)obj.guid);
                break;

            case "Quest":
                // Creatures
                var questMap = Global.ObjectMgr.GetCreatureQuestRelationMap();
                var qr       = Global.PoolMgr.mQuestCreatureRelation.LookupByKey(obj.guid);
                foreach (var creature in qr)
                {
                    Log.outDebug(LogFilter.Pool, "PoolGroup<Quest>: Adding quest {0} to creature {1}", obj.guid, creature);
                    questMap.Add(creature, (uint)obj.guid);
                }

                // Gameobjects
                questMap = Global.ObjectMgr.GetGOQuestRelationMap();
                qr       = Global.PoolMgr.mQuestGORelation.LookupByKey(obj.guid);
                foreach (var go in qr)
                {
                    Log.outDebug(LogFilter.Pool, "PoolGroup<Quest>: Adding quest {0} to GO {1}", obj.guid, go);
                    questMap.Add(go, (uint)obj.guid);
                }
                break;
            }
        }
コード例 #21
0
ファイル: Units.cs プロジェクト: gdpaulmil/WPF_ServerClient
 public static GameObject CreateGameObject(GameObjectData data)
 {
     return new GameObject() { GameObjectData = data };
 }
コード例 #22
0
ファイル: Gameobject.cs プロジェクト: Inifield/zoso-server
        /// <summary>
        /// Creates a new instance of the <see cref="Gameobject"/> class.
        /// </summary>
        public Gameobject(MmoZone zone, int objectId, GameObjectType goType, short familyId, GameObjectData goInfo)
            : base(zone, ObjectType.Gameobject, objectId, familyId, new Bounds(), null)
        {
            this.goType      = goType;
            this.lootGroupId = goInfo.LootGroupId;

            this.BuildProperties(Properties, PropertyFlags.GameobjectAll);
            this.Revision = this.Properties.Count;
            if (Properties.Count > 0)
            {
                this.Flags |= MmoObjectFlags.HasProperties;
            }

            switch (goType)
            {
            case GameObjectType.Chest:
                // chest can be looted by a single person
                this.lootRestriction = LootRestriction.SingleLooter;
                break;

            case GameObjectType.Plant:
            case GameObjectType.Vein:
                // plants and veins can be looted by multiple
                this.lootRestriction = LootRestriction.MultipleLooter;
                break;

            default:
                this.lootRestriction = LootRestriction.None;
                break;
            }

            this.lootGeneration = 0;
        }
コード例 #23
0
ファイル: Units.cs プロジェクト: gdpaulmil/WPF_ServerClient
 public static Unit CreateUnit(GameObjectData goData, UnitData data)
 {
     return null;
 }
コード例 #24
0
ファイル: GameObjectCommands.cs プロジェクト: uvbs/CypherCore
        static bool HandleGameObjectInfoCommand(StringArguments args, CommandHandler handler)
        {
            uint            entry     = 0;
            GameObjectTypes type      = 0;
            uint            displayId = 0;
            uint            lootId    = 0;

            if (args.Empty())
            {
                return(false);
            }

            string param1 = handler.ExtractKeyFromLink(args, "Hgameobject_entry");

            if (param1.IsEmpty())
            {
                return(false);
            }

            if (param1.Equals("guid"))
            {
                string cValue = handler.ExtractKeyFromLink(args, "Hgameobject");
                if (cValue.IsEmpty())
                {
                    return(false);
                }

                if (!ulong.TryParse(cValue, out ulong guidLow))
                {
                    return(false);
                }

                GameObjectData data = Global.ObjectMgr.GetGOData(guidLow);
                if (data == null)
                {
                    return(false);
                }
                entry = data.id;
            }
            else
            {
                if (!uint.TryParse(param1, out entry))
                {
                    return(false);
                }
            }

            GameObjectTemplate gameObjectInfo = Global.ObjectMgr.GetGameObjectTemplate(entry);

            if (gameObjectInfo == null)
            {
                return(false);
            }

            type      = gameObjectInfo.type;
            displayId = gameObjectInfo.displayId;
            string name = gameObjectInfo.name;

            lootId = gameObjectInfo.GetLootId();

            handler.SendSysMessage(CypherStrings.GoinfoEntry, entry);
            handler.SendSysMessage(CypherStrings.GoinfoType, type);
            handler.SendSysMessage(CypherStrings.GoinfoLootid, lootId);
            handler.SendSysMessage(CypherStrings.GoinfoDisplayid, displayId);
            handler.SendSysMessage(CypherStrings.GoinfoName, name);
            handler.SendSysMessage(CypherStrings.GoinfoSize, gameObjectInfo.size);

            GameObjectTemplateAddon addon = Global.ObjectMgr.GetGameObjectTemplateAddon(entry);

            if (addon != null)
            {
                handler.SendSysMessage(CypherStrings.GoinfoAddon, addon.faction, addon.flags);
            }

            GameObjectDisplayInfoRecord modelInfo = CliDB.GameObjectDisplayInfoStorage.LookupByKey(displayId);

            if (modelInfo != null)
            {
                handler.SendSysMessage(CypherStrings.GoinfoModel, modelInfo.GeoBoxMax.X, modelInfo.GeoBoxMax.Y, modelInfo.GeoBoxMax.Z, modelInfo.GeoBoxMin.X, modelInfo.GeoBoxMin.Y, modelInfo.GeoBoxMin.Z);
            }

            return(true);
        }
コード例 #25
0
ファイル: Units.cs プロジェクト: gdpaulmil/WPF_ServerClient
 public static Player CreatePlayer(GameObjectData goData, UnitData unitData, PlayerData playerData)
 {
     return null;
 }
コード例 #26
0
 public static bool TryGetGameObjectDataByNetId(long goNetId, out GameObjectData gameObjectData)
 {
     return((singleton != null || (gameObjectData = null) == null) && singleton._netIdToGameObjectData.TryGetValue(goNetId, out gameObjectData));
 }
コード例 #27
0
        public void LoadFromDB()
        {
            // Pool templates
            {
                uint oldMSTime = Time.GetMSTime();

                SQLResult result = DB.World.Query("SELECT entry, max_limit FROM pool_template");
                if (result.IsEmpty())
                {
                    mPoolTemplate.Clear();
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 object pools. DB table `pool_template` is empty.");
                    return;
                }

                uint count = 0;
                do
                {
                    uint pool_id = result.Read <uint>(0);

                    PoolTemplateData pPoolTemplate = new();
                    pPoolTemplate.MaxLimit = result.Read <uint>(1);
                    mPoolTemplate[pool_id] = pPoolTemplate;
                    ++count;
                }while (result.NextRow());

                Log.outInfo(LogFilter.ServerLoading, "Loaded {0} objects pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
            }

            // Creatures

            Log.outInfo(LogFilter.ServerLoading, "Loading Creatures Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                //                                         1        2            3
                SQLResult result = DB.World.Query("SELECT spawnId, poolSpawnId, chance FROM pool_members WHERE type = 0");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 creatures in  pools. DB table `pool_creature` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        ulong guid    = result.Read <ulong>(0);
                        uint  pool_id = result.Read <uint>(1);
                        float chance  = result.Read <float>(2);

                        CreatureData data = Global.ObjectMgr.GetCreatureData(guid);
                        if (data == null)
                        {
                            Log.outError(LogFilter.Sql, "`pool_creature` has a non existing creature spawn (GUID: {0}) defined for pool id ({1}), skipped.", guid, pool_id);
                            continue;
                        }
                        if (!mPoolTemplate.ContainsKey(pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_creature` pool id ({0}) is not in `pool_template`, skipped.", pool_id);
                            continue;
                        }
                        if (chance < 0 || chance > 100)
                        {
                            Log.outError(LogFilter.Sql, "`pool_creature` has an invalid chance ({0}) for creature guid ({1}) in pool id ({2}), skipped.", chance, guid, pool_id);
                            continue;
                        }
                        PoolTemplateData pPoolTemplate = mPoolTemplate[pool_id];
                        PoolObject       plObject      = new(guid, chance);

                        if (!mPoolCreatureGroups.ContainsKey(pool_id))
                        {
                            mPoolCreatureGroups[pool_id] = new PoolGroup <Creature>();
                        }

                        PoolGroup <Creature> cregroup = mPoolCreatureGroups[pool_id];
                        cregroup.SetPoolId(pool_id);
                        cregroup.AddEntry(plObject, pPoolTemplate.MaxLimit);

                        mCreatureSearchMap.Add(guid, pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} creatures in pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // Gameobjects

            Log.outInfo(LogFilter.ServerLoading, "Loading Gameobject Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                //                                         1        2            3
                SQLResult result = DB.World.Query("SELECT spawnId, poolSpawnId, chance FROM pool_members WHERE type = 1");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 gameobjects in  pools. DB table `pool_gameobject` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        ulong guid    = result.Read <ulong>(0);
                        uint  pool_id = result.Read <uint>(1);
                        float chance  = result.Read <float>(2);

                        GameObjectData data = Global.ObjectMgr.GetGameObjectData(guid);
                        if (data == null)
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` has a non existing gameobject spawn (GUID: {0}) defined for pool id ({1}), skipped.", guid, pool_id);
                            continue;
                        }

                        GameObjectTemplate goinfo = Global.ObjectMgr.GetGameObjectTemplate(data.Id);
                        if (goinfo.type != GameObjectTypes.Chest &&
                            goinfo.type != GameObjectTypes.FishingHole &&
                            goinfo.type != GameObjectTypes.GatheringNode &&
                            goinfo.type != GameObjectTypes.Goober)
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` has a not lootable gameobject spawn (GUID: {0}, type: {1}) defined for pool id ({2}), skipped.", guid, goinfo.type, pool_id);
                            continue;
                        }

                        if (!mPoolTemplate.ContainsKey(pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` pool id ({0}) is not in `pool_template`, skipped.", pool_id);
                            continue;
                        }

                        if (chance < 0 || chance > 100)
                        {
                            Log.outError(LogFilter.Sql, "`pool_gameobject` has an invalid chance ({0}) for gameobject guid ({1}) in pool id ({2}), skipped.", chance, guid, pool_id);
                            continue;
                        }

                        PoolTemplateData pPoolTemplate = mPoolTemplate[pool_id];
                        PoolObject       plObject      = new(guid, chance);

                        if (!mPoolGameobjectGroups.ContainsKey(pool_id))
                        {
                            mPoolGameobjectGroups[pool_id] = new PoolGroup <GameObject>();
                        }

                        PoolGroup <GameObject> gogroup = mPoolGameobjectGroups[pool_id];
                        gogroup.SetPoolId(pool_id);
                        gogroup.AddEntry(plObject, pPoolTemplate.MaxLimit);

                        mGameobjectSearchMap.Add(guid, pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} gameobject in pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // Pool of pools

            Log.outInfo(LogFilter.ServerLoading, "Loading Mother Pooling Data...");
            {
                uint oldMSTime = Time.GetMSTime();

                //                                         1        2            3
                SQLResult result = DB.World.Query("SELECT spawnId, poolSpawnId, chance FROM pool_members WHERE type = 2");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 pools in pools");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  child_pool_id  = result.Read <uint>(0);
                        uint  mother_pool_id = result.Read <uint>(1);
                        float chance         = result.Read <float>(2);

                        if (!mPoolTemplate.ContainsKey(mother_pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` mother_pool id ({0}) is not in `pool_template`, skipped.", mother_pool_id);
                            continue;
                        }
                        if (!mPoolTemplate.ContainsKey(child_pool_id))
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` included pool_id ({0}) is not in `pool_template`, skipped.", child_pool_id);
                            continue;
                        }
                        if (mother_pool_id == child_pool_id)
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` pool_id ({0}) includes itself, dead-lock detected, skipped.", child_pool_id);
                            continue;
                        }
                        if (chance < 0 || chance > 100)
                        {
                            Log.outError(LogFilter.Sql, "`pool_pool` has an invalid chance ({0}) for pool id ({1}) in mother pool id ({2}), skipped.", chance, child_pool_id, mother_pool_id);
                            continue;
                        }
                        PoolTemplateData pPoolTemplateMother = mPoolTemplate[mother_pool_id];
                        PoolObject       plObject            = new(child_pool_id, chance);

                        if (!mPoolPoolGroups.ContainsKey(mother_pool_id))
                        {
                            mPoolPoolGroups[mother_pool_id] = new PoolGroup <Pool>();
                        }

                        PoolGroup <Pool> plgroup = mPoolPoolGroups[mother_pool_id];
                        plgroup.SetPoolId(mother_pool_id);
                        plgroup.AddEntry(plObject, pPoolTemplateMother.MaxLimit);

                        mPoolSearchMap.Add(child_pool_id, mother_pool_id);
                        ++count;
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} pools in mother pools in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // The initialize method will spawn all pools not in an event and not in another pool, this is why there is 2 left joins with 2 null checks
            Log.outInfo(LogFilter.ServerLoading, "Starting objects pooling system...");
            {
                uint oldMSTime = Time.GetMSTime();

                SQLResult result = DB.World.Query("SELECT DISTINCT pool_template.entry, pool_members.spawnId, pool_members.poolSpawnId FROM pool_template" +
                                                  " LEFT JOIN game_event_pool ON pool_template.entry=game_event_pool.pool_entry" +
                                                  " LEFT JOIN pool_members ON pool_members.type = 2 AND pool_template.entry = pool_members.spawnId WHERE game_event_pool.pool_entry IS NULL");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Pool handling system initialized, 0 pools spawned.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint pool_entry   = result.Read <uint>(0);
                        uint pool_pool_id = result.Read <uint>(1);

                        if (!CheckPool(pool_entry))
                        {
                            if (pool_pool_id != 0)
                            {
                                // The pool is a child pool in pool_pool table. Ideally we should remove it from the pool handler to ensure it never gets spawned,
                                // however that could recursively invalidate entire chain of mother pools. It can be done in the future but for now we'll do nothing.
                                Log.outError(LogFilter.Sql, "Pool Id {0} has no equal chance pooled entites defined and explicit chance sum is not 100. This broken pool is a child pool of Id {1} and cannot be safely removed.", pool_entry, result.Read <uint>(2));
                            }
                            else
                            {
                                Log.outError(LogFilter.Sql, "Pool Id {0} has no equal chance pooled entites defined and explicit chance sum is not 100. The pool will not be spawned.", pool_entry);
                            }
                            continue;
                        }

                        // Don't spawn child pools, they are spawned recursively by their parent pools
                        if (pool_pool_id == 0)
                        {
                            SpawnPool(pool_entry);
                            count++;
                        }
                    }while (result.NextRow());

                    Log.outInfo(LogFilter.ServerLoading, "Pool handling system initialized, {0} pools spawned in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Loads a new level asynchronously
        /// </summary>
        /// <param name="level">The name of the level to load</param>
        public void LoadLevel(string level)
        {
            Loading = true;
            DungeonCrawlerGame game = (DungeonCrawlerGame)this.game;

            ThreadStart threadStarter = delegate
            {
                if (!LoadedTilemaps.ContainsKey(level))
                {
                    CurrentMap = game.Content.Load <Tilemap>("Tilemaps/" + level);
                    CurrentMap.LoadContent(game.Content);

                    // Load the background music
                    //if (CurrentMap.MusicTitle != null && CurrentMap.MusicTitle != "")
                    //{
                    //    CurrentSong = game.Content.Load<Song>("Music/" + CurrentMap.MusicTitle);
                    //}
                    //else
                    //{
                    //    CurrentSong = null;
                    //}
                    currentRoomID = game.RoomFactory.CreateRoom(level, CurrentMap.Width, CurrentMap.Height, CurrentMap.TileWidth, CurrentMap.TileHeight, CurrentMap.WallWidth, level);
                    Room room = game.RoomComponent[currentRoomID];



                    for (int i = 0; i < CurrentMap.GameObjectGroupCount; i++)
                    {
                        for (int j = 0; j < CurrentMap.GameObjectGroups[i].GameObjectData.Count(); j++)
                        {
                            GameObjectData goData   = CurrentMap.GameObjectGroups[i].GameObjectData[j];
                            Vector2        position = new Vector2(goData.Position.Center.X, goData.Position.Center.Y);

                            uint entityID = uint.MaxValue;


                            switch (goData.Category)
                            {
                            case "PlayerSpawn":
                                room.playerSpawns.Add(goData.properties["SpawnName"], new Vector2(goData.Position.X, goData.Position.Y));
                                break;

                            case "Enemy":
                                switch (goData.Type)
                                {
                                case "MovingTarget":
                                    entityID = game.EnemyFactory.CreateEnemy(EnemyType.MovingTarget, new Position {
                                        Center = new Vector2(goData.Position.X, goData.Position.Y), RoomID = currentRoomID, Radius = 32
                                    });
                                    break;

                                case "StationaryTarget":
                                    entityID = game.EnemyFactory.CreateEnemy(EnemyType.MovingTarget, new Position {
                                        Center = new Vector2(goData.Position.X, goData.Position.Y), RoomID = currentRoomID, Radius = 32
                                    });
                                    break;

                                case "Alien":
                                    entityID = game.EnemyFactory.CreateEnemy(EnemyType.Alien, new Position {
                                        Center = new Vector2(goData.Position.X, goData.Position.Y), RoomID = currentRoomID, Radius = 16
                                    });
                                    break;

                                default:
                                    break;
                                }
                                break;

                            case "NPC":
                                entityID = game.NPCFactory.CreateNPC((NPCName)Enum.Parse(typeof(NPCName), goData.Type), new Position
                                {
                                    Center = new Vector2(goData.Position.X, goData.Position.Y), RoomID = currentRoomID, Radius = 32
                                });
                                break;

                            case "Trigger":
                                switch (goData.Type)
                                {
                                case "Door":
                                    entityID = game.DoorFactory.CreateDoor(currentRoomID, goData.properties["DestinationRoom"], goData.properties["DestinationSpawnName"], goData.Position);
                                    break;

                                case "Wall":
                                    entityID = game.WallFactory.CreateWall(currentRoomID, goData.Position);
                                    break;

                                default:
                                    break;
                                }
                                break;
                            }
                            if (goData.properties.Keys.Contains("id"))
                            {
                                room.idMap.Add(goData.properties["id"], entityID);
                                room.targetTypeMap.Add(goData.properties["id"], goData.Type);
                            }
                        }
                    }

                    game.RoomComponent[currentRoomID] = room;

                    //// Load the game objects
                    //for (int i = 0; i < CurrentMap.GameObjectGroupCount; i++)
                    //{
                    //    for (int j = 0; j < CurrentMap.GameObjectGroups[i].GameObjectData.Count(); j++)
                    //    {
                    //        GameObjectData goData = CurrentMap.GameObjectGroups[i].GameObjectData[j];
                    //        Vector2 position = new Vector2(goData.Position.Center.X, goData.Position.Center.Y);
                    //        GameObject go;

                    //        switch (goData.Category)
                    //        {
                    //            case "PlayerStart":
                    //                ScrollingShooterGame.Game.Player.Position = position;
                    //                ScrollingShooterGame.Game.Player.LayerDepth = CurrentMap.GameObjectGroups[i].LayerDepth;
                    //                scrollDistance = -2 * position.Y + 300;
                    //                break;

                    //            case "LevelEnd":
                    //                break;

                    //            case "Powerup":
                    //                go = ScrollingShooterGame.GameObjectManager.CreatePowerup((PowerupType)Enum.Parse(typeof(PowerupType), goData.Type), position);
                    //                CurrentMap.GameObjectGroups[i].GameObjectData[j].ID = go.ID;
                    //                go.LayerDepth = CurrentMap.GameObjectGroups[i].LayerDepth;
                    //                go.ScrollingSpeed = CurrentMap.GameObjectGroups[i].ScrollingSpeed;
                    //                break;

                    //            case "Enemy":
                    //                go = ScrollingShooterGame.GameObjectManager.CreateEnemy((EnemyType)Enum.Parse(typeof(EnemyType), goData.Type), position);
                    //                CurrentMap.GameObjectGroups[i].GameObjectData[j].ID = go.ID;
                    //                go.LayerDepth = CurrentMap.GameObjectGroups[i].LayerDepth;
                    //                go.ScrollingSpeed = CurrentMap.GameObjectGroups[i].ScrollingSpeed;
                    //                break;
                    //            case "Boss":
                    //                go = ScrollingShooterGame.GameObjectManager.CreateBoss((BossType)Enum.Parse(typeof(BossType), goData.Type), position);
                    //                CurrentMap.GameObjectGroups[i].GameObjectData[j].ID = go.ID;
                    //                go.LayerDepth = CurrentMap.GameObjectGroups[i].LayerDepth;
                    //                go.ScrollingSpeed = CurrentMap.GameObjectGroups[i].ScrollingSpeed;
                    //                break;
                    //        }
                    //    }
                    //}

                    LoadedTilemaps.Add(level, CurrentMap);
                }
                else
                {
                    Room newRoom = game.RoomComponent.FindRoom(level);
                    if (newRoom.Tilemap == level)
                    {
                        CurrentMap    = LoadedTilemaps[level];
                        currentRoomID = newRoom.EntityID;
                    }
                }


                // Mark level as loaded
                Loading = false;
            };

            Thread loadingThread = new Thread(threadStarter);

            loadingThread.Start();
        }
コード例 #29
0
    public virtual void loadDataMissions()
    {
        LogUtil.Log("Load Missions:");

        int i = 0;

        double scoreTotal = 0;

        string worldCode = GameWorlds.Current.code;

        UpdateMetaLabels();

        foreach (AppContentCollect mission in
                 AppContentCollects.GetMissionsByWorld(worldCode))
        {
            double scoreMission = 0;

            GameObject item = NGUITools.AddChild(listGridRoot, listItemPrefab);
            item.name = "MissionItem" + i;

            UIUtil.UpdateLabelObject(item, "Container/Meta/LabelName", mission.display_name);
            UIUtil.UpdateLabelObject(item, "Container/Meta/LabelDescription", mission.description);

            string actionType      = BaseDataObjectKeys.mission;
            string appContentState = AppContentStates.Current.code;
            string appState        = AppStates.Current.code;
            string missionCode     = mission.code;

            // Update button action

            Transform buttonObject = item.transform.Find("Container/Button/ButtonAction");
            if (buttonObject != null)
            {
                UIImageButton button = buttonObject.gameObject.GetComponent <UIImageButton>();
                if (button != null)
                {
                    GameObjectData objData = button.gameObject.Get <GameObjectData>();

                    if (objData == null)
                    {
                        objData = button.gameObject.AddComponent <GameObjectData>();
                    }

                    if (objData != null)
                    {
                        objData.Set(BaseDataObjectKeys.type, actionType);
                        objData.Set(BaseDataObjectKeys.app_content_state, appContentState);
                        objData.Set(BaseDataObjectKeys.app_state, appState);
                        objData.Set(BaseDataObjectKeys.code, missionCode);
                    }

                    button.name = BaseUIButtonNames.buttonGamePlay +
                                  "$" + appContentState + "$" + missionCode;
                }
            }

            // hide actions

            string currentType = BaseDataObjectKeys.action;

            foreach (GameObjectInactive obj in
                     item.GetComponentsInChildren <GameObjectInactive>(true))
            {
                if (obj.type == currentType)
                {
                    obj.gameObject.Hide();
                }
            }

            // fill in action content and stars

            int j = 0;

            foreach (AppContentCollectItem action in mission.GetItemsData())
            {
                foreach (GameObjectInactive obj in
                         item.GetComponentsInChildren <GameObjectInactive>(true))
                {
                    if (obj.type == currentType)
                    {
                        string index = (j + 1).ToString();

                        string currentActionItem = currentType + "-" + index;

                        if (obj.code == currentActionItem)
                        {
                            //Debug.Log("action.data.display_name:" + action.data.display_name);

                            obj.gameObject.Show();

                            UIUtil.UpdateLabelObject(
                                obj.gameObject, "LabelDescription", action.data.display_name);

                            // CHECK ACTION COMPLETE/SCORE STATE

                            string collectType = BaseDataObjectKeys.mission;

                            string collectKey =
                                GameProfileModes.GetAppContentCollectItemKey(
                                    appState,
                                    appContentState,
                                    worldCode,
                                    BaseDataObjectKeys.all,
                                    mission.code, action.uid);

                            bool complete = GameProfileModes.Current.GetContentCollectValue <bool>(
                                collectType, collectKey, BaseDataObjectKeys.complete);

                            double points = GameProfileModes.Current.GetContentCollectValue <double>(
                                collectType, collectKey, BaseDataObjectKeys.points);

                            if (points == 0)
                            {
                                points = GameProfileModes.Current.GetContentCollectValue <int>(
                                    collectType, collectKey, BaseDataObjectKeys.points);
                            }


                            if (complete)
                            {
                                // figure score
                                scoreMission += points;
                            }

                            // STARS LIST

                            SetStars(obj.gameObject, complete);

                            // STARS STAR CONTAINER

                            GameObject starObject = null;

                            foreach (GameObjectInactive starItem in
                                     item.GetComponentsInChildren <GameObjectInactive>(true))
                            {
                                if (starItem.code == "stars-star-" + index.ToString())
                                {
                                    starObject = starItem.gameObject;

                                    //Debug.Log("Worlds:loadDataMissions::StarObject Found");
                                }
                            }

                            SetStars(starObject, complete);
                        }
                    }
                }

                j++;
            }

            // fill score

            scoreTotal += scoreMission;

            Transform scoreObject = item.transform.Find("Container/Stars");
            if (scoreObject != null)
            {
                UIUtil.UpdateLabelObject(
                    scoreObject.gameObject, "LabelScore", scoreMission.ToString("N0"));
            }

            i++;
        }

        //Transform scoreTotalObject = item.transform.FindChild("Container/ScoreTotal");
        //if(scoreObject != null) {
        //    UIUtil.UpdateLabelObject(
        //        scoreObject.gameObject, "LabelScoreTotal", scoreTotal.ToString("N0"));
        //}
    }