Esempio n. 1
0
        void LftClickedOnGameObject(GameObject obj)
        {
            var gameEntity = obj.GetComponent <AbstractGameObject>();

            if (gameEntity == null || (!FieldOfView.IsVisible(gameEntity) && ChunkManager.staticFogEnabled))
            {
                ClickedOnSpace();
                return;
            }


            if (_choosed)
            {
                var prevEnt = _choosedObj.GetComponent <GameEntity>();

                ClickedOnSpace();
                UnitBar_HTML.ClearUnitBar(prevEnt);
            }

            if (!GroupUtil.IsGround(gameEntity.Group))
            {
                ChooseUnit(gameEntity);
            }
            else
            {
                ClickedOnSpace();
            }
        }
Esempio n. 2
0
        void FixedUpdate()
        {
            if (PauseMenu_HTML.IsPaused || GroupUtil.IsNeutral(Group))
            {
                return;
            }

            foreach (var ab in AbilityList)
            {
                ab.Update();
            }


            GameMoveManager.OnMoveUpdate(this);

            if (Group == "" ||
                !GroupUtil.isCreatureGroup(Group) ||
                GroupUtil.IsNeutral(Group) ||
                Owner == PlayersManager.GetMyPlayer()
                )
            {
                return;
            }

            AI_Main.Update(this);
        }
Esempio n. 3
0
        public static Table FindEnemiesInRadius(GameUnit unit, int radius)
        {
            var t     = DynValue.NewTable(LuaManager.ScriptObj).Table;
            var point = unit.CurrentPos;

            var n = 0;

            for (var i = point.x - radius; i <= point.x + radius; i++)
            {
                for (var j = point.y - radius; j <= point.y + radius; j++)
                {
                    if (!ChunkManager.CurrentChunk.IsMapPos(new Vector3Int(i, j, point.z)))
                    {
                        continue;
                    }
                    var ent = ChunkManager.CurrentChunk.Ground[point.z][i][j];
                    if (ent == null ||
                        unit.EntityIndex == ent.EntityIndex ||
                        unit.PlayerID == ent.PlayerID ||
                        GroupUtil.IsNeutral(ent.Group))
                    {
                        continue;
                    }
                    t.Set(DynValue.NewNumber(n), DynValue.FromObject(LuaManager.ScriptObj, ent));
                    n++;
                }
            }
            return(t);
        }
Esempio n. 4
0
        void Update()
        {
            if (PauseMenu_HTML.IsPaused)
            {
                return;
            }

            if (GroupUtil.IsNeutral(Group))
            {
                return;
            }

            if (SoloEvolution)
            {
                UnitEvolution.Update(this);
            }

            if (!GroupUtil.isCreatureGroup(Group))
            {
                return;
            }

            ItemMain.Update(this);
            UnitEvolution.Update(this);
        }
Esempio n. 5
0
        AddCollapsedGroupAttributes
        (
            Microsoft.Office.Interop.Excel.Workbook workbook,
            ReadWorkbookContext readWorkbookContext,
            IGraph graph
        )
        {
            Debug.Assert(workbook != null);
            Debug.Assert(readWorkbookContext != null);
            Debug.Assert(graph != null);

            GroupInfo[] aoGroups;
            ListObject  oEdgeTable, oVertexTable;

            if (
                GroupUtil.TryGetGroups(graph, out aoGroups)
                &&
                ExcelTableUtil.TryGetTable(workbook, WorksheetNames.Edges,
                                           TableNames.Edges, out oEdgeTable)
                &&
                ExcelTableUtil.TryGetTable(workbook, WorksheetNames.Vertices,
                                           TableNames.Vertices, out oVertexTable)
                )
            {
                AddCollapsedGroupAttributesInternal(workbook, readWorkbookContext,
                                                    oEdgeTable, oVertexTable, aoGroups);
            }
        }
Esempio n. 6
0
    void FieldOfViewOnTargetsVisibilityChange(List <Transform> newTargets)
    {
        if (!ChunkManager.staticFogEnabled)
        {
            return;
        }
        if (Recolor.IsIgnored(gameObject.GetComponent <GameEntity>()) &&
            FieldOfView.visibleBefore.Contains(transform))
        {
            renderer.enabled  = true;
            entScript.enabled = true;
        }
        else
        {
            var cont = newTargets.Contains(transform);
            renderer.enabled = cont;

            //Block script logic only on neutral ents
            if (!cont && !GroupUtil.IsNeutral(entScript.Group))
            {
                cont = true;
            }
            entScript.enabled = cont;
        }
    }
Esempio n. 7
0
        public async Task <GroupRecord> getGroup(byte[] groupId)
        {
            var query = conn.Table <Group>().Where(v => v.group_id == GroupUtil.getEncodedId(groupId));

            Reader      reader = new Reader(query.ToList());
            GroupRecord record = reader.getNext();

            reader.close();
            return(record);
        }
Esempio n. 8
0
 public byte[] getId()
 {
     try
     {
         return(GroupUtil.getDecodedId(id));
     }
     catch (IOException ioe)
     {
         throw new Exception(ioe.Message);
     }
 }
Esempio n. 9
0
        public GameItem SetupItem(GameEntity ent, string name, Vector3Int pos, Player owner)
        {
            var index = Loader.GetIndexByName(name);
            var npc   = LuaNpcGetter.GetNpcById(index);

            ent.Owner        = owner;
            ent.OriginalName = name;
            ent.name         = name;
            var item = ent as GameItem;

            var evoTo = LuaNpcGetter.GetEvolutionTo(npc);

            if (evoTo.Length > 0)
            {
                if (!UnitEvolution.IsHasSoloEvolution(name))
                {
                    UnitEvolution.AddToSoloDict(name, evoTo);
                }

                if (item != null)
                {
                    item.SoloEvolution = true;
                }
            }

            var evoCross = LuaNpcGetter.GetNpcEvoCrossing(npc);

            if (evoCross.Keys.Count > 0)
            {
                foreach (var pair in evoCross)
                {
                    UnitEvolution.AddToStackDict(name, pair.Key, pair.Value);

                    if (!string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase))
                    {
                        UnitEvolution.AddToStackDict(pair.Key, name, pair.Value);
                    }
                }
            }
            if (GroupUtil.IsItem(ent.Group))
            {
                SecondaryGroundLvL.SetGroundEnt(ChunkNumber, pos, item);
            }

            if (GroupUtil.isBuilding(ent.Group))
            {
                ChunkManager.AddVision(ent);
            }
            ItemEvents.OnCreateItem(item, firstCreate);

            Coloring.RecolorObject(ChunkUtil.GetDovvner(ent.CurrentPos));

            return(item);
        }
Esempio n. 10
0
        public void SetUp()
        {
            _jsonUtil         = Substitute.For <IJsonUtil>();
            _groupHistoryUtil = Substitute.For <IGroupHistoryUtil>();

            _util = new GroupUtil(
                _jsonUtil,
                _groupHistoryUtil
                );

            _notificationSession = Substitute.For <INotificationSession>();
        }
        TryCalculateGraphMetrics
        (
            IGraph graph,
            CalculateGraphMetricsContext calculateGraphMetricsContext,
            out GraphMetricColumn [] graphMetricColumns
        )
        {
            Debug.Assert(graph != null);
            Debug.Assert(calculateGraphMetricsContext != null);
            AssertValid();

            graphMetricColumns = new GraphMetricColumn[0];

            // Attempt to retrieve the group information the WorkbookReader object
            // may have stored as metadata on the graph.

            GroupInfo [] aoGroups;

            if (
                !calculateGraphMetricsContext.ShouldCalculateGraphMetrics(
                    GraphMetrics.GroupMetrics)
                ||
                !GroupUtil.TryGetGroups(graph, out aoGroups)
                )
            {
                return(true);
            }

            // Count the edges using the IntergroupEdgeCalculator class in the
            // Algorithms namespace, which knows nothing about Excel.

            IList <IntergroupEdgeInfo> oIntergroupEdges;

            if (!(new Algorithms.IntergroupEdgeCalculator()).
                TryCalculateGraphMetrics(graph,
                                         calculateGraphMetricsContext.BackgroundWorker, aoGroups, true,
                                         out oIntergroupEdges))
            {
                // The user cancelled.

                return(false);
            }

            // Add a row to the group-edge table for each pair of groups that has
            // edges.

            graphMetricColumns = CreateGraphMetricColumns(
                AddRows(aoGroups, oIntergroupEdges));

            return(true);
        }
Esempio n. 12
0
        /// <summary>
        ///  读取 GroupList , 生成 “组合” 下拉菜单的选项
        /// </summary>
        private void GetGroups()
        {
            Dictionary <int, string> dictGroups = EnumHepler.EnumToDictionary <GroupType>();

            this.ddlGroup.DisplayMember = "Name";
            this.ddlGroup.ValueMember   = "Id";

            foreach (var item in dictGroups)
            {
                ComboBoxListItem listItem = new ComboBoxListItem(
                    item.Key, item.Value, GroupUtil.GetGroupColorByGroupId(item.Key)
                    );
                this.ddlGroup.Items.Add(listItem);
            }

            this.ddlGroup.SelectedIndex = 0;
        }
Esempio n. 13
0
        /*
         * public void create(byte[] groupId, String title, List<String> members,
         *                 TextSecureAttachmentPointer avatar, String relay)
         * {
         *  ContentValues contentValues = new ContentValues();
         *  contentValues.put(GROUP_ID, GroupUtil.getEncodedId(groupId));
         *  contentValues.put(TITLE, title);
         *  contentValues.put(MEMBERS, Util.join(members, ","));
         *
         *  if (avatar != null)
         *  {
         *      contentValues.put(AVATAR_ID, avatar.getId());
         *      contentValues.put(AVATAR_KEY, avatar.getKey());
         *      contentValues.put(AVATAR_CONTENT_TYPE, avatar.getContentType());
         *  }
         *
         *  contentValues.put(AVATAR_RELAY, relay);
         *  contentValues.put(TIMESTAMP, System.currentTimeMillis());
         *  contentValues.put(ACTIVE, 1);
         *
         *  databaseHelper.getWritableDatabase().insert(TABLE_NAME, null, contentValues);
         * }
         *
         * public void update(byte[] groupId, String title, TextSecureAttachmentPointer avatar)
         * {
         *  ContentValues contentValues = new ContentValues();
         *  if (title != null) contentValues.put(TITLE, title);
         *
         *  if (avatar != null)
         *  {
         *      contentValues.put(AVATAR_ID, avatar.getId());
         *      contentValues.put(AVATAR_CONTENT_TYPE, avatar.getContentType());
         *      contentValues.put(AVATAR_KEY, avatar.getKey());
         *  }
         *
         *  databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues,
         *                                              GROUP_ID + " = ?",
         *                                              new String[] { GroupUtil.getEncodedId(groupId) });
         *
         *  RecipientFactory.clearCache();
         *  notifyDatabaseListeners();
         * }
         *
         * public void updateTitle(byte[] groupId, String title)
         * {
         *  ContentValues contentValues = new ContentValues();
         *  contentValues.put(TITLE, title);
         *  databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues, GROUP_ID + " = ?",
         *                                              new String[] { GroupUtil.getEncodedId(groupId) });
         *
         *  RecipientFactory.clearCache();
         *  notifyDatabaseListeners();
         * }
         *
         * public void updateAvatar(byte[] groupId, Bitmap avatar)
         * {
         *  updateAvatar(groupId, BitmapUtil.toByteArray(avatar));
         * }
         *
         * public void updateAvatar(byte[] groupId, byte[] avatar)
         * {
         *  ContentValues contentValues = new ContentValues();
         *  contentValues.put(AVATAR, avatar);
         *
         *  databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues, GROUP_ID + " = ?",
         *                                              new String[] { GroupUtil.getEncodedId(groupId) });
         *
         *  RecipientFactory.clearCache();
         *  notifyDatabaseListeners();
         * }
         *
         * public void updateMembers(byte[] id, List<String> members)
         * {
         *  ContentValues contents = new ContentValues();
         *  contents.put(MEMBERS, Util.join(members, ","));
         *  contents.put(ACTIVE, 1);
         *
         *  databaseHelper.getWritableDatabase().update(TABLE_NAME, contents, GROUP_ID + " = ?",
         *                                              new String[] { GroupUtil.getEncodedId(id) });
         * }
         *
         * public void remove(byte[] id, String source)
         * {
         *  List<String> currentMembers = getCurrentMembers(id);
         *  currentMembers.remove(source);
         *
         *  ContentValues contents = new ContentValues();
         *  contents.put(MEMBERS, Util.join(currentMembers, ","));
         *
         *  databaseHelper.getWritableDatabase().update(TABLE_NAME, contents, GROUP_ID + " = ?",
         *                                              new String[] { GroupUtil.getEncodedId(id) });
         * }
         */
        private async Task <List <String> > getCurrentMembers(byte[] id)
        {
            try
            {
                var query = conn.Table <Group>().Where(v => v.group_id == GroupUtil.getEncodedId(id));


                if (query != null)
                {
                    return((query.First()).members.Split(',').ToList());
                }

                return(new List <string>());
            }
            finally
            {
            }
        }
Esempio n. 14
0
        void Update()
        {
            if (PauseMenu_HTML.IsPaused)
            {
                return;
            }

            if (SoloEvolution)
            {
                UnitEvolution.Update(this);
            }

            if (GroupUtil.IsNeutral(Group))
            {
                return;
            }
            AbilitiesManager.UpdateUnitAbilities(this);
        }
Esempio n. 15
0
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogDebug("Starting");


        _logger.LogDebug("Ensuring '{home}' directory exists and has correct permissions", HomeBasePath);
        Directory.CreateDirectory(HomeBasePath);
        await ProcessUtil.QuickRun("chown", $"root:root \"{HomeBasePath}\"");

        _logger.LogDebug("Ensuring group '{group}' exists", SftpUserInventoryGroup);
        if (!await GroupUtil.GroupExists(SftpUserInventoryGroup))
        {
            _logger.LogInformation("Creating group '{group}'", SftpUserInventoryGroup);
            await GroupUtil.GroupCreate(SftpUserInventoryGroup, true);
        }

        await SyncUsersAndGroups();

        _logger.LogInformation("Started");
    }
Esempio n. 16
0
        public static void ClearPosesForPlayer(Vector3Int pos, int tileRadius)
        {
            var chunk = ChunkManager.CurrentChunk;

            for (int x = pos.x - tileRadius; x < pos.x + tileRadius; x++)
            {
                for (int y = pos.y - tileRadius; y < pos.y + tileRadius; y++)
                {
                    var ent = chunk.GetGameObjectByIndex(new Vector3Int(x, y, 1));
                    if (ent == null)
                    {
                        continue;
                    }
                    if (GroupUtil.IsNeutral(ent.Group))
                    {
                        ent.KillSelf();
                    }
                }
            }
        }
Esempio n. 17
0
        private async Task <RecipientDetails> getGroupRecipientDetails(String groupId)
        {
            try
            {
                GroupDatabase.GroupRecord record = await DatabaseFactory.getGroupDatabase()
                                                   .getGroup(GroupUtil.getDecodedId(groupId));

                if (record != null)
                {
                    //Drawable avatar = ContactPhotoFactory.getGroupContactPhoto(context, record.getAvatar());
                    return(new RecipientDetails(record.getTitle(), groupId, null));
                }

                return(null);
            }
            catch (Exception e)
            {
                //Log.w("RecipientProvider", e);
                return(null);
            }
        }
Esempio n. 18
0
        public static void MoveToIndex(GameUnit unit, Vector3Int posTarget)
        {
            if (posTarget == Vector3Int.zero)
            {
                return;
            }
            var ent = ChunkManager.CurrentChunk.GetGameObjectByIndex(posTarget);
            var pos = posTarget;

            if (ent == null || !GroupUtil.IsGround(ent.Group))
            {
                pos = ChunkUtil.GetDovvner(pos);
            }
            var path = PresetPath(unit, pos);

            if (path == null)
            {
                return;
            }

            GameOrderManager.DoOrder(unit, path, OrderTypes.MoveOrder);
        }
Esempio n. 19
0
        /*public IncomingTextMessage(SmsMessage message)
         * {
         *  this.message = message.getDisplayMessageBody();
         *  this.sender = message.getDisplayOriginatingAddress();
         *  this.senderDeviceId = TextSecureAddress.DEFAULT_DEVICE_ID;
         *  this.protocol = message.getProtocolIdentifier();
         *  this.serviceCenterAddress = message.getServiceCenterAddress();
         *  this.replyPathPresent = message.isReplyPathPresent();
         *  this.pseudoSubject = message.getPseudoSubject();
         *  this.sentTimestampMillis = message.getTimestampMillis();
         *  this.groupId = null;
         *  this.push = false;
         * }*/

        public IncomingTextMessage(String sender, int senderDeviceId, long sentTimestampMillis,
                                   String encodedBody, May <SignalServiceGroup> group)
        {
            this.Message              = encodedBody;
            this.Sender               = sender;
            this.SenderDeviceId       = senderDeviceId;
            this.Protocol             = 31337;
            this.ServiceCenterAddress = "GCM";
            this.ReplyPathPresent     = true;
            this.PseudoSubject        = "";
            this.SentTimestampMillis  = sentTimestampMillis;
            this.Push = true;

            if (group.HasValue)
            {
                this.GroupId = GroupUtil.getEncodedId(group.ForceGetValue().getGroupId());
            }
            else
            {
                this.GroupId = null;
            }
        }
Esempio n. 20
0
        public static void UpdateFlag(Vector2Int pos)
        {
            if (!FlagDict.ContainsKey(pos))
            {
                return;
            }
            var        z    = -1;
            GameEntity prev = null;

            for (int i = 0; i < ChunkManager.MaxGroundsLvls; i++)
            {
                var ent = ChunkManager.CurrentChunk.GetGameObjectByIndex(new Vector3Int(pos.x, pos.y, i));

                z = i;
                if (prev != null &&
                    (GroupUtil.isCreatureGroup(prev.Group) || !FieldOfView.IsVisible(prev)))
                {
                    z--;
                }

                if (ent == null)
                {
                    break;
                }
                prev = ent;
            }
            if (z == -1)
            {
                z = ChunkManager.MaxGroundsLvls;
            }

            var pos3D = Util.Get3DPosByIndex(pos.x, pos.y, z);
            var flag  = FlagDict[pos];

            flag.transform.position = pos3D + staticFlag.transform.position;
        }
        CalculateSnapOverallMetrics
        (
            IGraph oGraph,
            out Nullable <Int32> iMaximumGeodesicDistance,
            out Nullable <Double> dAverageGeodesicDistance,
            out Nullable <Double> dModularity
        )
        {
            Debug.Assert(oGraph != null);
            AssertValid();

            iMaximumGeodesicDistance = new Nullable <Int32>();
            dAverageGeodesicDistance = new Nullable <Double>();
            dModularity = new Nullable <Double>();

            if (oGraph.Vertices.Count == 0 || oGraph.Edges.Count == 0)
            {
                return;
            }

            // Always calculate the geodesic distances.

            SnapGraphMetrics eSnapGraphMetrics =
                SnapGraphMetrics.GeodesicDistances;

            // Also calculate modularity if the graph has at least one group.

            Boolean          bCalculateModularity = false;
            List <GroupInfo> oGroups = null;

            if (GroupUtil.GraphHasGroups(oGraph))
            {
                oGroups = GroupUtil.GetGroupsWithAllVertices(oGraph, false);

                // SNAP can't handle isolates when calculating modularity, so
                // remove them.

                GroupUtil.RemoveIsolatesFromGroups(oGroups);

                if (oGroups.Count > 0)
                {
                    eSnapGraphMetrics   |= SnapGraphMetrics.Modularity;
                    bCalculateModularity = true;
                }
                else
                {
                    oGroups = null;
                }
            }

            String sOutputFilePath = CalculateSnapGraphMetrics(
                oGraph, eSnapGraphMetrics, oGroups);

            using (StreamReader oStreamReader = new StreamReader(
                       sOutputFilePath))
            {
                // The first line is a header.

                String sLine = oStreamReader.ReadLine();

            #if DEBUG
                const String GeodesicDistancesHeader =
                    "Maximum Geodesic Distance\tAverage Geodesic Distance";

                if (bCalculateModularity)
                {
                    Debug.Assert(sLine ==
                                 GeodesicDistancesHeader + "\tModularity");
                }
                else
                {
                    Debug.Assert(sLine == GeodesicDistancesHeader);
                }
            #endif

                // The second line contains the metric values.

                Debug.Assert(oStreamReader.Peek() >= 0);

                sLine = oStreamReader.ReadLine();
                String [] asFields = sLine.Split('\t');
                Debug.Assert(asFields.Length == (bCalculateModularity ? 3: 2));

                iMaximumGeodesicDistance =
                    ParseSnapInt32GraphMetricValue(asFields, 0);

                dAverageGeodesicDistance =
                    ParseSnapDoubleGraphMetricValue(asFields, 1);

                if (bCalculateModularity)
                {
                    dModularity = ParseSnapDoubleGraphMetricValue(asFields, 2);
                }
            }

            File.Delete(sOutputFilePath);
        }
Esempio n. 22
0
        private async Task SyncUsersAndGroups()
        {
            _logger.LogInformation("Synchronizing users and groups");

            if (!await GroupUtil.GroupExists(SftpUserInventoryGroup))
            {
                _logger.LogInformation("Creating group '{group}'", SftpUserInventoryGroup);
                await GroupUtil.GroupCreate(SftpUserInventoryGroup, true);
            }

            var existingUsers = await GroupUtil.GroupListUsers(SftpUserInventoryGroup);

            var toRemove = existingUsers.Where(s => !_config.Users.Select(t => t.Username).Contains(s)).ToList();

            foreach (var user in toRemove)
            {
                _logger.LogDebug("Removing user '{user}'", user, SftpUserInventoryGroup);
                await UserUtil.UserDelete(user, false);
            }


            foreach (var user in _config.Users)
            {
                _logger.LogInformation("Processing user '{user}'", user.Username);

                if (!await UserUtil.UserExists(user.Username))
                {
                    _logger.LogDebug("Creating user '{user}'", user.Username);
                    await UserUtil.UserCreate(user.Username, true);

                    _logger.LogDebug("Adding user '{user}' to '{group}'", user.Username, SftpUserInventoryGroup);
                    await GroupUtil.GroupAddUser(SftpUserInventoryGroup, user.Username);
                }


                _logger.LogDebug("Updating the password for user '{user}'", user.Username);
                await UserUtil.UserSetPassword(user.Username, user.Password, user.PasswordIsEncrypted);

                if (user.UID.HasValue)
                {
                    if (await UserUtil.UserGetId(user.Username) != user.UID.Value)
                    {
                        _logger.LogDebug("Updating the UID for user '{user}'", user.Username);
                        await UserUtil.UserSetId(user.Username, user.UID.Value);
                    }
                }

                if (user.GID.HasValue)
                {
                    var virtualGroup = $"sftp-gid-{user.GID.Value}";
                    if (!await GroupUtil.GroupExists(virtualGroup))
                    {
                        _logger.LogDebug("Creating group '{group}' with GID '{gid}'", virtualGroup, user.GID.Value);
                        await GroupUtil.GroupCreate(virtualGroup, true, user.GID.Value);
                    }

                    _logger.LogDebug("Adding user '{user}' to '{group}'", user.Username, virtualGroup);
                    await GroupUtil.GroupAddUser(virtualGroup, user.Username);
                }

                await PrepareUserForSftp(user.Username);
            }
        }
Esempio n. 23
0
        public static GameEntity InitObject(int chunkNumber, string name, Vector3Int vecInt, int index,
                                            Table npc, Player owner)
        {
            var chunk = GetChunkByNum(chunkNumber);

            if (chunk == null)
            {
                return(null);
            }

            var vec = Util.Get3DPosByIndex(vecInt.x, vecInt.y, vecInt.z);

            var vecIntPos = new Vector3Int(vecInt.x, vecInt.y, vecInt.z);


            var prefab = Loader.GetPrefabByIndex(index);
            var obj    = Instantiate(prefab, vec + prefab.transform.position, new Quaternion());

            if (IsGroupVVithName(prefab.name))
            {
                var trans = GetGroupVVithName(prefab.name);
                obj.transform.SetParent(trans);
            }
            else
            {
                var o = new GameObject {
                    name = prefab.name
                };

                o.transform.SetParent(BATYAtrans);
                Groups.Add(o);

                obj.transform.SetParent(o.transform);
            }


            var group = LuaNpcGetter.GetNpcGroup(npc);

            Stats stats = null;

            if (!GroupUtil.IsGround(group))
            {
                stats     = LuaNpcGetter.GetStatsFromTable(npc);
                obj.layer = 9;


                if (staticFogEnabled)
                {
                    obj.AddComponent <FogCoverable>();
                }
            }


            var abilities = new List <Ability>();

            if (!GroupUtil.IsGround(group))
            {
                if (!GroupUtil.IsItem(group) && staticFogEnabled)
                {
                    var spRend = obj.GetComponent <SpriteRenderer>();
                    if (spRend != null)
                    {
                        spRend.enabled = false;
                    }
                }

                if (!GroupUtil.IsNeutral(group) && !GroupUtil.IsItem(group))
                {
                    var npcAbilitiesNames = LuaNpcGetter.GetNpcAbilitiesNames(npc);
                    foreach (var KV in npcAbilitiesNames)
                    {
                        var ability = LuaAbilitiesGetter.GetAbility(KV.Value);
                        ability.Owner = owner;
                        abilities.Add(ability);
                    }
                }
            }

            GameEntity ent;

            if (GroupUtil.IsGround(group))
            {
                ent = obj.AddComponent <GameEntity>();
                ent.Init(chunkNumber, vecIntPos, false, index);
                ent.Group = group;

                chunk.SetIndex(vecIntPos, index);

                obj.layer = 8;
                chunk.IndexMas[vecInt.z][vecInt.x][vecInt.y] = index;
                chunk.Ground[vecInt.z][vecInt.x][vecInt.y]   = ent;
            }
            else if (GroupUtil.IsItem(group))
            {
                var item = obj.AddComponent <GameItem>();

                item.Init(chunkNumber, vecIntPos, false, index, stats);
                item.Group = group;

                var npcModifiersNames = LuaNpcGetter.GetNpcModifiersNames(npc);
                item.ModifierNamesList.AddRange(npcModifiersNames);

                ent = item;
            }
            else
            {
                var unit = obj.AddComponent <GameUnit>();

                unit.Init(chunkNumber, vecIntPos, false, index, stats);
                unit.Group = group;

                var soundVolume  = LuaNpcGetter.GetNpcSoundVolume(npc);
                var soundByIndex = Loader.GetSoundByIndex(index, soundVolume);

                unit.GameAudio = soundByIndex;
                unit.itemDrop  = LuaNpcGetter.GetNpcItemDrop(npc);

                CreatureGroupManager.Init(unit);

                if (GroupUtil.isBuilding(group))
                {
                    var researchName = LuaNpcGetter.GetNpcResearch(npc);
                    if (researchName.Length > 0)
                    {
                        var research = ResearchManager.SetupResearch(researchName);
                        unit.research = research;
                        owner.AddResearch(research);
                        AbilityBar_HTML.Update();
                    }
                    BuildingsGroupManager.Init(unit);
                }

                foreach (var ab in abilities)
                {
                    unit.AddAbility(ab);
                }

                ent = unit;
                chunk.IndexMas[vecInt.z][vecInt.x][vecInt.y] = index;
                chunk.Ground[vecInt.z][vecInt.x][vecInt.y]   = ent;
            }
            ent.OriginalName = name;
            ent.ExtraPos     = prefab.transform.position;


            ent.foodCost = LuaNpcGetter.GetNpcFoodCost(npc);
            ent.foodGive = LuaNpcGetter.GetNpcFoodGive(npc);

            owner.foodCount += ent.foodCost;
            owner.foodMax   += ent.foodGive;


            ent.goldDrop = LuaNpcGetter.GetNpcGoldDrop(npc);


            //obj.name = prefab.name + "_" + vecInt.z + "_" + vecInt.x + "_" + vecInt.y;


            PathCalcManager.CalculatePoint(vecInt);
            PathCalcManager.CalculatePoint(ChunkUtil.GetDovvner(vecInt));


            return(ent);
        }
Esempio n. 24
0
        public override void KillSelf()
        {
            if (Destroyed)
            {
                return;
            }
            var chunk = ChunkManager.GetChunkByNum(ChunkNumber);

            chunk.SetIndex(CurrentPos, -1);
            chunk.RemoveObject(CurrentPos);

            if (pickUped != null)
            {
                ItemEvents.OnDeathDropItem(pickUped, this);
            }

            ClickManager.RemoveChosing(gameObject);

            GameMoveManager.CancelAllOrders(this);
            if (GroupUtil.isCreatureGroup(Group))
            {
                GameOrderManager.RemoveMarks(this);
                //SimpleOrderManager.CancelOrders(this);
                if (MovingPath != null)
                {
                    MovingPath.Clear();
                }
            }

            if (SecondaryGroundLvL.isSecondaryGroup(Group))
            {
                SecondaryGroundLvL.RemovePos(ChunkNumber, CurrentPos);
            }

            if (FlagManager.IsFlagAtPos(CurrentPos))
            {
                FlagManager.RemoveFlag(CurrentPos);
            }

            ProgressUnitBar.RemoveProgressBar(this);
            CreatureGroupManager.RemoveEntFromGroup(this);
            BuildingsGroupManager.RemoveBuildingFromGroup(this);

            RemoveAbilities();

            if (research != null)
            {
                var sameBuilds = BuildingsGroupManager.GetAllInChunkWithName(ChunkNumber, OriginalName);
                if (sameBuilds.Count == 0)
                {
                    Owner.RemoveResearch(research);
                }
            }
            Coloring.RecolorObject(ChunkUtil.GetDovvner(CurrentPos));
            Owner.foodCount -= foodCost;
            Owner.foodMax   -= foodGive;

            if (gameObject != null)
            {
                Destroy(gameObject);
            }


            Destroyed = true;
        }
Esempio n. 25
0
        TestRemoveIsolatesFromGroups()
        {
            IGraph            oGraph    = new Graph();
            IEdgeCollection   oEdges    = oGraph.Edges;
            IVertexCollection oVertices = oGraph.Vertices;

            // Non-isolates.

            IVertex oVertexA = oVertices.Add();
            IVertex oVertexB = oVertices.Add();
            IVertex oVertexC = oVertices.Add();
            IVertex oVertexD = oVertices.Add();

            // Isolates.

            IVertex oVertexE = oVertices.Add();
            IVertex oVertexF = oVertices.Add();
            IVertex oVertexG = oVertices.Add();

            oEdges.Add(oVertexA, oVertexB);
            oEdges.Add(oVertexB, oVertexC);
            oEdges.Add(oVertexD, oVertexA);

            // Group1 contains all non-isolate vertices.

            GroupInfo oGroup1 = new GroupInfo();

            oGroup1.Vertices.AddLast(oVertexA);
            oGroup1.Vertices.AddLast(oVertexB);
            oGroup1.Vertices.AddLast(oVertexC);

            // Group2 contains a mix of isolate and non-isolate vertices.

            GroupInfo oGroup2 = new GroupInfo();

            oGroup2.Vertices.AddLast(oVertexD);
            oGroup2.Vertices.AddLast(oVertexE);

            // Group3 contains all isolate vertices.

            GroupInfo oGroup3 = new GroupInfo();

            oGroup3.Vertices.AddLast(oVertexF);
            oGroup3.Vertices.AddLast(oVertexG);

            // Group4 is empty.

            GroupInfo oGroup4 = new GroupInfo();

            List <GroupInfo> oGroups = new List <GroupInfo>();

            oGroups.Add(oGroup1);
            oGroups.Add(oGroup2);
            oGroups.Add(oGroup3);
            oGroups.Add(oGroup4);

            GroupUtil.RemoveIsolatesFromGroups(oGroups);

            Assert.AreEqual(2, oGroups.Count);

            Assert.AreEqual(3, oGroups[0].Vertices.Count);
            Assert.IsNotNull(oGroups[0].Vertices.Find(oVertexA));
            Assert.IsNotNull(oGroups[0].Vertices.Find(oVertexB));
            Assert.IsNotNull(oGroups[0].Vertices.Find(oVertexC));

            Assert.AreEqual(1, oGroups[1].Vertices.Count);
            Assert.IsNotNull(oGroups[1].Vertices.Find(oVertexD));
        }
Esempio n. 26
0
        OnLayoutUsingGroupsEnd
        (
            IGraph graph,
            IList <GroupInfo> laidOutGroups,
            Double groupRectanglePenWidth,
            IntergroupEdgeStyle intergroupEdgeStyle
        )
        {
            Debug.Assert(graph != null);
            Debug.Assert(laidOutGroups != null);
            Debug.Assert(groupRectanglePenWidth >= 0);

            List <IntergroupEdgeInfo> oCombinedIntergroupEdges = null;

            if (intergroupEdgeStyle == IntergroupEdgeStyle.Combine)
            {
                // Get a collection of IntergroupEdgeInfo objects, one for the
                // edges between each pair of groups and one for the edges within
                // each group.

                IEnumerable <IntergroupEdgeInfo> oAllIntergroupEdges =
                    (new IntergroupEdgeCalculator()).CalculateGraphMetrics(
                        graph, laidOutGroups, false);

                // Filter out the objects for the edges within each group.

                oCombinedIntergroupEdges = new List <IntergroupEdgeInfo>(
                    oAllIntergroupEdges.Where(
                        oIntergroupEdge =>
                        oIntergroupEdge.Group1Index != oIntergroupEdge.Group2Index
                        ));
            }

            if (intergroupEdgeStyle == IntergroupEdgeStyle.Hide ||
                intergroupEdgeStyle == IntergroupEdgeStyle.Combine)
            {
                // Intergroup edges need to be hidden.

                Boolean bEdgeHidden    = false;
                Int32   iLaidOutGroups = laidOutGroups.Count;

                // The key is an IVertex.ID and the value is the zero-based index
                // of the laid-out group the vertex belongs to.

                Dictionary <Int32, Int32> oGroupIndexDictionary =
                    GroupUtil.GetGroupIndexDictionary(laidOutGroups);

                for (Int32 iGroupIndex = 0; iGroupIndex < iLaidOutGroups;
                     iGroupIndex++)
                {
                    GroupInfo oGroup = laidOutGroups[iGroupIndex];

                    foreach (IVertex oVertex in oGroup.Vertices)
                    {
                        foreach (IEdge oIncidentEdge in oVertex.IncidentEdges)
                        {
                            if (IncidentEdgeShouldBeHidden(oIncidentEdge, oVertex,
                                                           iGroupIndex, oGroupIndexDictionary))
                            {
                                HideEdge(oIncidentEdge);
                                bEdgeHidden = true;
                            }
                        }
                    }
                }

                if (bEdgeHidden)
                {
                    graph.SetValue(ReservedMetadataKeys.IntergroupEdgesHidden,
                                   null);
                }
            }

            graph.SetValue(ReservedMetadataKeys.GroupLayoutDrawingInfo,
                           new GroupLayoutDrawingInfo(laidOutGroups, groupRectanglePenWidth,
                                                      oCombinedIntergroupEdges));
        }
Esempio n. 27
0
        public static void RecolorObject(GameEntity ent, bool trueCall)
        {
            if (ent == null || ((Recolor.IsHided(ent) && !trueCall) && ChunkManager.staticFogEnabled))
            {
                return;
            }


            var mod   = 3f;
            var upper = ChunkUtil.GetUpper(ent.CurrentPos);

            if ((ChunkUtil.IsAnyEntity(ent.ChunkNumber, upper) ||
                 !SecondaryGroundLvL.IsEmptyPos(ent.ChunkNumber, upper)) &&
                ent.CurrentPos.z + 1 != ChunkManager.MaxGroundsLvls)
            {
                mod += 2.5f;
            }


            var i     = 1f / ((ent.CurrentPos.z + mod) * 0.3f);
            var color = new Color(i, i, i);

            if (ChunkUtil.IsEntity(ent.ChunkNumber, upper) &&
                ent.CurrentPos.z + 1 != ChunkManager.MaxGroundsLvls)
            {
                var chunk    = ChunkManager.GetChunkByNum(ent.ChunkNumber);
                var upperEnt = chunk.GetGameObjectByIndex(upper);
                if (upperEnt != null)
                {
                    if (TreeGroup.IsTreeGroup(upperEnt.Group))
                    {
                        color.r = 0.5f;
                        color.b = 0.7f;
                        color.g = 0.3f;
                    }
                    else if (upperEnt.Group == "rock")
                    {
                        color.r = 0.3f;
                        color.b = 0.7f;
                        color.g = 0.2f;
                    }
                    else if (upperEnt is GameUnit)
                    {
                        var unit = upperEnt as GameUnit;
                        if (unit.IsEnemy(PlayersManager.GetMyPlayer()))
                        {
                            color.r = 1;
                            color.b = 0.3f;
                            color.g = 0.3f;
                        }
                        else
                        {
                            color.r = 0.1f;
                            color.b = 0.1f;
                            color.g = 0.6f;
                        }
                    }
                    else
                    {
                        color.r = 0.1f;
                        color.b = 0.1f;
                        color.g = 0.6f;
                    }
                }
            }

            if (!GroupUtil.isCreatureGroup(ent.Group) &&
                !GroupUtil.isBuilding(ent.Group))
            {
                var spriteRenderer = ent.GetComponent <SpriteRenderer>();
                spriteRenderer.color = color;
            }
        }
Esempio n. 28
0
        void RghtClickedOnGameObject(GameObject obj)
        {
            if (_choosed)
            {
                var from = _choosedObj.GetComponent <GameUnit>();
                if (from == null || !from.IsMy())
                {
                    return;
                }
                var to = obj.GetComponent <GameEntity>();

                if (to == null)
                {
                    return;
                }

                if (!GroupUtil.isCreatureGroup(from.Group))
                {
                    return;
                }


                if (!FieldOfView.IsVisible(to) && !GroupUtil.IsGround(to.Group))
                {
                    ClickedOnSpace();
                    return;
                }

                Vector3Int f;
                if (from.MovingTo != null)
                {
                    f = from.MovingTo.Index;
                }
                else
                {
                    f = from.CurrentPos;
                    f.z--;
                }

                //Cant move ?
                if (from.UpgradedStats.MoveSpeed <= 0f)
                {
                    SimpleOrderManager.CancelOrders(from);
                    ErrorBar_HTML.SetupError("This unit can`t move!");
                    return;
                }

                //Attack
                var t             = to.CurrentPos;
                var buildingCheck = false;
                if (ChunkUtil.IsAnyEntity(from.ChunkNumber, ChunkUtil.GetUpper(t)))
                {
                    var underGround = ChunkManager.CurrentChunk.GetGameObjectByIndex(ChunkUtil.GetUpper(t));
                    var underEnt    = underGround.GetComponent <GameEntity>();
                    if (SecondaryGroundLvL.isSecondaryGroup(underEnt.Group))
                    {
                        buildingCheck = true;
                    }

                    if (!GroupUtil.IsGround(underEnt.Group) && underEnt.Owner != PlayersManager.GetMyPlayer())
                    {
                        var underP = underEnt.CurrentPos;
                        underP.z++;

                        if (!ChunkManager.CurrentChunk.IsMapPos(underP) ||
                            !ChunkUtil.IsAnyEntity(from.ChunkNumber, ChunkUtil.GetUpper(underEnt.CurrentPos)))
                        {
                            if (from.UpgradedStats.Dmg > 0)
                            {
                                SimpleOrderManager.AttackToIndex(from, t);
                            }
                            else if (from.UpgradedStats.Dmg == 0)
                            {
                                ErrorBar_HTML.SetupError("This unit can`t attack!");
                            }
                            return;
                        }
                    }
                }


                //Cancel or Move
                if ((ChunkUtil.IsAnyEntity(from.ChunkNumber, ChunkUtil.GetUpper(t)) ||
                     !PathCalcManager.IsReaching(f, t)) && !buildingCheck)
                {
                    ErrorBar_HTML.SetupError("Can`t reach that place!");
                    SimpleOrderManager.CancelOrders(from);
                }
                else if (ChunkUtil.IsCanStayHere(from.ChunkNumber, t) || buildingCheck)
                {
                    SimpleOrderManager.MoveToIndex(from, t);
                }
            }
            else
            {
                var clicked = obj.GetComponent <GameEntity>();
                if (clicked == null)
                {
                    return;
                }

                var pos = clicked.CurrentPos;

                if (FlagManager.IsFlagAtPos(pos))
                {
                    FlagManager.RemoveFlag(pos);
                }
                else
                {
                    FlagManager.SetupFlag(pos);
                }
            }
        }
Esempio n. 29
0
        SortFilteredEdgesByGroup
        (
            IGraph oGraph,
            Int32 iMaximumGroups,
            IEnumerable <IEdge> oFilteredEdges
        )
        {
            Debug.Assert(oGraph != null);
            Debug.Assert(iMaximumGroups > 0);
            Debug.Assert(oFilteredEdges != null);

            List <GroupEdgeInfo> oGroupEdgeInfos = new List <GroupEdgeInfo>();

            // Get the graph's groups.

            GroupInfo [] aoGroups;

            if (GroupUtil.TryGetGroups(oGraph, out aoGroups))
            {
                // For each top group, we need a collection of the edges whose
                // first vertex is in the group.

                // This LinkedList will contain the graph's filtered edges, sorted
                // by their first vertex.  A null entry is inserted between each
                // set of edges.

                LinkedList <IEdge> oSortedEdges;

                // The key is a vertex, and the value is the first entry in
                // oSortedEdges for the vertex.

                Dictionary <IVertex, LinkedListNode <IEdge> > oFirstNodes;

                SortEdgesByVertex1(oFilteredEdges, out oSortedEdges,
                                   out oFirstNodes);

                List <IEdge> oEdgesInGroup = new List <IEdge>();

                // Sort the groups by descending vertex count.

                foreach (ExcelTemplateGroupInfo oGroupInfo in
                         ExcelTemplateGroupUtil.GetTopGroups(aoGroups, iMaximumGroups))
                {
                    oEdgesInGroup.Clear();

                    foreach (IVertex oVertex in oGroupInfo.Vertices)
                    {
                        // Loop through the edges that have oVertex as their first
                        // vertex.

                        LinkedListNode <IEdge> oNodeForVertex;

                        if (oFirstNodes.TryGetValue(oVertex, out oNodeForVertex))
                        {
                            while (oNodeForVertex.Value != null)
                            {
                                oEdgesInGroup.Add(oNodeForVertex.Value);
                                oNodeForVertex = oNodeForVertex.Next;
                            }
                        }
                    }

                    oGroupEdgeInfos.Add(new GroupEdgeInfo(
                                            oEdgesInGroup.ToArray(), oGroupInfo));
                }
            }

            return(oGroupEdgeInfos);
        }
Esempio n. 30
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                SetProgressBar(60);

                SetLabel("Initializing components");

                //this.LoadUserAppData();

                SetProgressBar(100);

                SetLabel("Getting user information");

                //GlobalService.User = "******";
                //GlobalService.DbTable = "TB_hk950097";

                /*if (domain == "kmhk.local")
                 *  GlobalService.DbTable = "TB_" + AdUtil.GetUserIdByUsername(GlobalService.User, "kmhk.local");
                 * else
                 * {
                 *  string id = AdUtil.GetUserIdByUsername(GlobalService.User, domain);
                 *
                 *  string tb = id == "as1600048" ? "hk070022"
                 *      : id == "as1600049" ? "hk110017"
                 *      : id == "as1600050" ? "hk040015"
                 *      : id == "as1600051" ? "hk160002"
                 *      : id == "as1600053" ? "hk950330"
                 *      : id == "as1600054" ? "hk110023"
                 *      : id == "as1600055" ? "hk120027"
                 *      : id == "as1600056" ? "hk140005" : "";
                 *
                 *  GlobalService.DbTable = "TB_" + tb;
                 *
                 *  string name = id == "as1600048" ? "Chow Chi To(周志滔,Sammy)"
                 *      : id == "as1600049" ? "Ling Wai Man(凌慧敏,Velma)"
                 *      : id == "as1600050" ? "Chan Fai Lung(陳輝龍,Onyx)"
                 *      : id == "as1600051" ? "Ng Lau Yu, Lilith (吳柳如)"
                 *      : id == "as1600053" ? "Lee Miu Wah(李苗華)"
                 *      : id == "as1600054" ? "Lee Ming Fung(李銘峯)"
                 *      : id == "as1600055" ? "Ho Kin Hang(何健恒,Ken)"
                 *      : id == "as1600056" ? "Yeung Wai, Gabriel (楊偉)" : "";
                 *
                 *  GlobalService.User = name;
                 * }*/

                //List<string> list = new List<string>();
                //list.Add(GlobalService.User);
                //EmailUtil.SendNotificationEmail(list);

                GlobalService.User = GlobalService.User.Trim();

                try
                {
                    SetLabel("Synchronizing data");

                    SharedUtil.AutoDeleteData();

                    Stopwatch sw = new Stopwatch();

                    sw.Start();
                    GlobalService.DepartmentFolder = SetupUtil.GetDepartmentFolder(GlobalService.User);
                    sw.Stop();
                    Debug.WriteLine("Get Department Folder: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.DivisionMemberList = SystemUtil.DivisionMember(GlobalService.User);
                    sw.Stop();
                    Debug.WriteLine("Get Division Memeber: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.DepartmentMemberList = SystemUtil.DepartmentMember(GlobalService.User);
                    sw.Stop();
                    Debug.WriteLine("Get Department Member: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.SystemGroupList = GroupUtil.SystemGroupList();
                    GlobalService.CNGroupList     = GroupUtil.CnGroupList();
                    GlobalService.VNGroupList     = GroupUtil.VnGroupList();
                    GlobalService.JPGroupList     = GroupUtil.JpGroupList();
                    sw.Stop();
                    Debug.WriteLine("Get System Group: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.CustomGroupList = GroupUtil.CustomGroupList2(GlobalService.User);
                    sw.Stop();
                    Debug.WriteLine("Get Custom Group: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.AllUserList = UserUtil.AllUserList();
                    GlobalService.CnUserList  = UserUtil.CnUserList();
                    GlobalService.VnUserList  = UserUtil.VnUserList();
                    GlobalService.JpUserList  = UserUtil.JpUserList();
                    sw.Stop();
                    Debug.WriteLine("Get All User: "******"Initialize attachment list: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.ExtraSystemGroupList = GroupUtil.ExtraSystemGroupList();
                    sw.Stop();
                    Debug.WriteLine("Get Extra System Group: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.NoticeList = MessageUtil.GetNoticeList();
                    sw.Stop();
                    Debug.WriteLine("Get Notice list: " + sw.Elapsed);

                    GlobalService.IsPasswordInput = false;

                    sw.Reset();
                    sw.Start();
                    GlobalService.DiscList = DiscUtil.PopulateDiscList();
                    sw.Stop();
                    Debug.WriteLine("Populate Disc List: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.Division = SystemUtil.GetDivision(GlobalService.User);
                    sw.Stop();
                    Debug.WriteLine("Get Division: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.AppsList = SystemUtil.AppsList();
                    sw.Stop();
                    Debug.WriteLine("Get Application list: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.DocumentList = new List <lists.DocumentList>();
                    sw.Stop();
                    Debug.WriteLine("Initialize Document List: " + sw.Elapsed);

                    sw.Reset();
                    sw.Start();
                    GlobalService.ContactList = ContactUtil.ContactList();
                    sw.Stop();
                    Debug.WriteLine("Load Contact List: " + sw.Elapsed);

                    GetSystemVersion();

                    UpdateCommon();

                    SharedUtil.UpdateEmptyShared();

                    SharedUtil.UpdateShared();

                    Login();

                    //DataUtil.SyncDataToServer();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message + ex.StackTrace);
                }
            }
            catch (ArgumentException ex)
            {
                File.WriteAllText(@"D:\Error.txt", ex.Message + ex.StackTrace);
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }