Exemplo n.º 1
0
        public async Task RemoveItemAsync(Lot lot, uint count, bool silent = false)
        {
            await using var cdClient = new CdClientContext();

            var componentId = await cdClient.ComponentsRegistryTable.FirstOrDefaultAsync(
                r => r.Id == lot && r.Componenttype == (int)ComponentId.ItemComponent
                );

            if (componentId == default)
            {
                Logger.Error($"{lot} does not have a Item component");
                return;
            }

            var component = await cdClient.ItemComponentTable.FirstOrDefaultAsync(
                i => i.Id == componentId.Componentid
                );

            if (component == default)
            {
                Logger.Error(
                    $"{lot} has a corrupted component registry. There is no Item component of Id: {componentId.Componentid}"
                    );

                return;
            }

            Debug.Assert(component.ItemType != null, "component.ItemType != null");

            RemoveItem(lot, count, ((ItemType)component.ItemType).GetInventoryType(), silent);
        }
Exemplo n.º 2
0
        public async Task LoadAsync()
        {
            await using var cdClient = new CdClientContext();

            var clientTasks = await cdClient.MissionTasksTable.Where(
                t => t.Id == MissionId
                ).ToArrayAsync();

            var tasks = new List <MissionTaskBase>();

            foreach (var clientTask in clientTasks)
            {
                var taskType = (MissionTaskType)(clientTask.TaskType ?? 0);

                if (!TaskTypes.TryGetValue(taskType, out var type))
                {
                    Logger.Error($"No {nameof(MissionTaskBase)} for {taskType} found.");

                    continue;
                }

                var instance = (MissionTaskBase)Activator.CreateInstance(type);

                Debug.Assert(clientTask.Uid != null, "clientTask.Uid != null");

                await instance.LoadAsync(Player, MissionId, clientTask.Uid.Value);

                tasks.Add(instance);
            }

            Tasks = tasks.ToArray();
        }
Exemplo n.º 3
0
        public async Task Buy(Lot lot, uint count, Player player)
        {
            await using var ctx = new CdClientContext();

            var itemComponent = await ctx.ItemComponentTable.FirstAsync(
                i => i.Id == lot.GetComponentId(ComponentId.ItemComponent)
                );

            if (count == default || itemComponent.BaseValue <= 0)
            {
                return;
            }

            var cost = (uint)((itemComponent.BaseValue ?? 0) * count);

            if (cost > player.Currency)
            {
                return;
            }

            player.Currency -= cost;

            await player.GetComponent <InventoryManagerComponent>().AddItemAsync(lot, count);

            player.Message(new VendorTransactionResultMessage
            {
                Associate = GameObject,
                Result    = TransactionResult.Success
            });

            await OnBuy.InvokeAsync(lot, count, player);
        }
Exemplo n.º 4
0
        private async Task LoadRequirementsAsync()
        {
            await using var cdClient = new CdClientContext();

            var clientTask = await cdClient.MissionTasksTable.FirstAsync(
                t => t.Uid == TaskId && t.Id == MissionId
                );

            Target = clientTask.Target ?? 0;

            TargetValue = clientTask.TargetValue ?? 0;

            if (clientTask.TargetGroup != default)
            {
                var targetGroup = clientTask.TargetGroup
                                  .Replace(" ", "")
                                  .Split(',')
                                  .Where(c => !string.IsNullOrEmpty(c)).ToList();

                var targets = new List <int>();

                foreach (var target in targetGroup)
                {
                    if (int.TryParse(target, out var lot))
                    {
                        targets.Add(lot);
                    }
                }

                TargetGroup = targets.ToArray();
            }
            else
            {
                TargetGroup = new int[0];
            }

            if (clientTask.TaskParam1 != default)
            {
                var targetParameters = clientTask.TaskParam1
                                       .Replace(" ", "")
                                       .Split(',')
                                       .Where(c => !string.IsNullOrEmpty(c)).ToList();

                var parameters = new List <int>();

                foreach (var parameter in targetParameters)
                {
                    if (int.TryParse(parameter, out var lot))
                    {
                        parameters.Add(lot);
                    }
                }

                Parameters = parameters.ToArray();
            }
            else
            {
                Parameters = new int[0];
            }
        }
Exemplo n.º 5
0
 protected async Task <BehaviorParameter> GetParameter(string name)
 {
     await using var cdClient = new CdClientContext();
     return(await cdClient.BehaviorParameterTable.FirstOrDefaultAsync(p =>
                                                                      p.BehaviorID == BehaviorId && p.ParameterID == name
                                                                      ));
 }
Exemplo n.º 6
0
        protected LuaScriptComponent()
        {
            Listen(OnStart, () =>
            {
                using var ctx = new CdClientContext();

                var scriptId = GameObject.Lot.GetComponentId(ComponentId.ScriptComponent);

                var script = ctx.ScriptComponentTable.FirstOrDefault(s => s.Id == scriptId);

                if (script == default)
                {
                    Logger.Warning($"{GameObject} has an invalid script component entry: {scriptId}");

                    return;
                }

                if (GameObject.Settings.TryGetValue("custom_script_server", out var scriptOverride))
                {
                    ScriptName = (string)scriptOverride;
                }
                else
                {
                    ScriptName = script.Scriptname;
                }

                ClientScriptName = script.Clientscriptname;

                Logger.Debug($"{GameObject} -> {ScriptName}");
            });
        }
Exemplo n.º 7
0
        /// <summary>
        /// For an item makes sure that an item set is created if said item is part of one, if this item is not part of
        /// an item set or the the item set this item belongs to is already created, this does nothing
        /// </summary>
        /// <param name="inventory">The inventory to get possible set items from</param>
        /// <param name="lot">The lot for which we wish to check if item sets should be tracked</param>
        public static async Task CreateIfNewSet(InventoryComponent inventory, Lot lot)
        {
            await using var context = new CdClientContext();
            var clientItemSets = context.ItemSetsTable.Where(
                i => i.ItemIDs.Contains(lot.ToString()));

            foreach (var clientItemSet in clientItemSets)
            {
                // Make sure that the item set is valid and that the inventory doesn't already track an item set with this ID
                if (clientItemSet.SetID == null ||
                    inventory.ActiveItemSets.Any(i => i._setId == clientItemSet.SetID.Value))
                {
                    continue;
                }

                var itemSet = Instantiate(inventory, clientItemSet.SetID.Value);
                Start(itemSet);

                foreach (var itemSetLot in clientItemSet.ItemIDs.Split(","))
                {
                    itemSet._itemsInSet.Add(new Lot(int.Parse(itemSetLot)));
                }

                // The skill sets that are unlocked when wearing n items of a set
                itemSet._skillSetMap[2] = clientItemSet.SkillSetWith2;
                itemSet._skillSetMap[3] = clientItemSet.SkillSetWith3;
                itemSet._skillSetMap[4] = clientItemSet.SkillSetWith4;
                itemSet._skillSetMap[5] = clientItemSet.SkillSetWith5;
                itemSet._skillSetMap[6] = clientItemSet.SkillSetWith6;
            }
        }
Exemplo n.º 8
0
        public long EquipUnmanagedItem(Lot lot, uint count         = 1, int slot = -1,
                                       InventoryType inventoryType = InventoryType.None)
        {
            using var cdClient = new CdClientContext();
            var cdClientObject = cdClient.ObjectsTable.FirstOrDefault(
                o => o.Id == lot
                );

            var itemRegistryEntry = lot.GetComponentId(ComponentId.ItemComponent);

            if (cdClientObject == default || itemRegistryEntry == default)
            {
                Logger.Error($"{lot} is not a valid item");
                return(-1);
            }

            var itemComponent = cdClient.ItemComponentTable.First(
                i => i.Id == itemRegistryEntry
                );

            var id = IdUtilities.GenerateObjectId();

            Items[itemComponent.EquipLocation] = new InventoryItem
            {
                InventoryItemId = id,
                Count           = count,
                Slot            = slot,
                LOT             = lot,
                InventoryType   = (int)inventoryType
            };

            return(id);
        }
Exemplo n.º 9
0
        private static async Task <Lot[]> ParseProxyItemsAsync(Lot item)
        {
            await using var ctx = new CdClientContext();

            var itemInfo = await ctx.ItemComponentTable.FirstOrDefaultAsync(
                i => i.Id == item.GetComponentId(ComponentId.ItemComponent)
                );

            if (itemInfo == default)
            {
                return(new Lot[0]);
            }

            if (string.IsNullOrWhiteSpace(itemInfo.SubItems))
            {
                return(new Lot[0]);
            }

            var proxies = itemInfo.SubItems
                          .Replace(" ", "")
                          .Split(',')
                          .Select(i => (Lot)int.Parse(i));

            return(proxies.ToArray());
        }
Exemplo n.º 10
0
        private async Task <long[]> GenerateProxyItemsAsync(Item item)
        {
            if (string.IsNullOrWhiteSpace(item?.ItemComponent?.SubItems))
            {
                return(null);
            }

            var proxies = item.ItemComponent.SubItems
                          .Replace(" ", "")
                          .Split(',')
                          .Select(int.Parse);

            var list = new List <long>();

            await using var cdClient = new CdClientContext();

            foreach (Lot proxy in proxies)
            {
                var componentId = proxy.GetComponentId(ComponentId.ItemComponent);

                var component = await cdClient.ItemComponentTable.FirstOrDefaultAsync(i => i.Id == componentId);

                if (component == default)
                {
                    continue;
                }

                list.Add(EquipUnmanagedItem(
                             proxy,
                             inventoryType: item.Inventory.InventoryType)
                         );
            }

            return(list.ToArray());
        }
Exemplo n.º 11
0
        public async Task PlayEmoteHandler(PlayEmoteMessage message, Player player)
        {
            await using var ctx = new CdClientContext();

            var animation = await ctx.EmotesTable.FirstOrDefaultAsync(e => e.Id == message.EmoteId);

            player.Zone.BroadcastMessage(new PlayAnimationMessage
            {
                Associate    = player,
                AnimationsId = animation.AnimationName
            });

            player.Zone.ExcludingMessage(new EmotePlayedMessage
            {
                Associate = player,
                EmoteId   = message.EmoteId,
                Target    = message.Target
            }, player);

            if (player.TryGetComponent <MissionInventoryComponent>(out var missionInventoryComponent))
            {
                await missionInventoryComponent.UseEmoteAsync(message.Target, message.EmoteId);
            }

            if (message.Target?.OnEmoteReceived != default)
            {
                await message.Target.OnEmoteReceived.InvokeAsync(message.EmoteId, player);
            }
        }
Exemplo n.º 12
0
        private async Task SetupEntries()
        {
            var componentId = GameObject.Lot.GetComponentId(ComponentId.VendorComponent);

            await using var cdClient = new CdClientContext();

            var vendorComponent = await cdClient.VendorComponentTable.FirstAsync(c => c.Id == componentId);

            var matrices =
                cdClient.LootMatrixTable.Where(l => l.LootMatrixIndex == vendorComponent.LootMatrixIndex);

            var shopItems = new List <ShopEntry>();

            foreach (var matrix in matrices)
            {
                shopItems.AddRange(cdClient.LootTableTable.Where(
                                       l => l.LootTableIndex == matrix.LootTableIndex
                                       ).ToArray().Select(lootTable =>
                {
                    Debug.Assert(lootTable.Itemid != null, "lootTable.Itemid != null");
                    Debug.Assert(lootTable.SortPriority != null, "lootTable.SortPriority != null");

                    return(new ShopEntry
                    {
                        Lot = new Lot(lootTable.Itemid.Value),
                        SortPriority = lootTable.SortPriority.Value
                    });
                }));
            }

            Entries = shopItems.ToArray();
        }
Exemplo n.º 13
0
        protected QuickBuildComponent()
        {
            Listen(OnStart, async() =>
            {
                if (GameObject.Settings.TryGetValue("rebuild_activators", out var rebuildActivators))
                {
                    ActivatorPosition = (Vector3)rebuildActivators;
                }
                else
                {
                    ActivatorPosition = Transform.Position;
                }

                Logger.Information($"{GameObject} is a rebuild-able!");

                await using var cdClient = new CdClientContext();

                var clientComponent = await cdClient.RebuildComponentTable.FirstOrDefaultAsync(
                    r => r.Id == GameObject.Lot.GetComponentId(ComponentId.QuickBuildComponent)
                    );

                if (clientComponent == default)
                {
                    Logger.Error(
                        $"{GameObject} does not have a valid {nameof(ComponentId.QuickBuildComponent)} component."
                        );

                    return;
                }

                _completeTime    = clientComponent.Completetime ?? 0;
                _imaginationCost = clientComponent.Takeimagination ?? 0;
                _timeToSmash     = clientComponent.Timebeforesmash ?? 0;
                _resetTime       = clientComponent.Resettime ?? 0;

                //if (!GameObject.Settings.TryGetValue("spawnActivator", out var spawnActivator) ||
                //    !(bool) spawnActivator) return;

                //
                // This activator is that imagination cost display of the quickbuild.
                // It is required to be able to start the quickbuild.
                //

                Activator = GameObject.Instantiate(new LevelObjectTemplate
                {
                    Lot      = 6604,
                    Position = ActivatorPosition,
                    Rotation = Quaternion.Identity,
                    Scale    = -1,
                    LegoInfo = new LegoDataDictionary()
                }, GameObject);

                Start(Activator);

                GameObject.Construct(Activator);
                GameObject.Serialize(GameObject);

                Listen(GameObject.OnInteract, StartRebuild);
            });
Exemplo n.º 14
0
        public override Task LoadAsync()
        {
            Listen(Zone.OnPlayerLoad, player =>
            {
                Listen(player.OnFireServerEvent, async(EventName, message) =>
                {
                    if (EventName == "ZonePlayer")
                    {
                        var launchpad = message.Associate.GetComponent <RocketLaunchpadComponent>();

                        await using var cdClient = new CdClientContext();

                        var id = launchpad.GameObject.Lot.GetComponentId(ComponentId.RocketLaunchComponent);

                        var launchpadComponent = await cdClient.RocketLaunchpadControlComponentTable.FirstOrDefaultAsync(
                            r => r.Id == id
                            );

                        if (launchpadComponent == default)
                        {
                            return;
                        }

                        await using var ctx = new UchuContext();

                        var character = await ctx.Characters.FirstAsync(c => c.Id == player.Id);

                        character.LaunchedRocketFrom = Zone.ZoneId;

                        await ctx.SaveChangesAsync();

                        if (launchpadComponent.TargetZone != null)
                        {
                            var target = (ZoneId)launchpadComponent.TargetZone;

                            //
                            // We don't want to lock up the server on a world server request, as it may take time.
                            //

                            var _ = Task.Run(async() =>
                            {
                                var success = await player.SendToWorldAsync(target);

                                if (!success)
                                {
                                    player.SendChatMessage($"Failed to transfer to {target}, please try later.");
                                }
                            });
                        }
                    }
                });

                return(Task.CompletedTask);
            });

            return(Task.CompletedTask);
        }
Exemplo n.º 15
0
        public void Initialize(Player player)
        {
            Player = player;

            using var cdClient = new CdClientContext();

            var zone = cdClient.ZoneTableTable.FirstOrDefault(z => z.ZoneID == (int)Player.Zone.ZoneId);

            Distance = zone?.Ghostdistance ?? 500;
        }
Exemplo n.º 16
0
        public override async Task ConfigureAsync(string configFile)
        {
            Logger.Information($"Created WorldServer on PID {Process.GetCurrentProcess().Id.ToString()}");
            await base.ConfigureAsync(configFile);

            // Update the CDClient database.
            await using var cdContext = new CdClientContext();
            await cdContext.EnsureUpdatedAsync();

            ZoneParser = new ZoneParser(Resources);
            Whitelist  = new Whitelist(Resources);

            await Whitelist.LoadDefaultWhitelist();

            GameMessageReceived += HandleGameMessageAsync;
            ServerStopped       += () =>
            {
                foreach (var zone in Zones)
                {
                    Object.Destroy(zone);
                }
            };

            var instance = await Api.RunCommandAsync <InstanceInfoResponse>(
                Config.ApiConfig.Port, $"instance/target?i={Id}"
                ).ConfigureAwait(false);

            ZoneId = (ZoneId)instance.Info.Zones.First();
#if DEBUG
            if (!Config.DebugConfig.StartInstancesAsThreads)
#endif
            Logger.SetServerTypeInformation("Z" + ZoneId.Id);

            var info = await Api.RunCommandAsync <InstanceInfoResponse>(MasterApi, $"instance/target?i={Id}");

            Api.RegisterCommandCollection <WorldCommands>(this);

            ManagedScriptEngine.AdditionalPaths = Config.ManagedScriptSources.Paths.ToArray();

            _ = Task.Run(async() =>
            {
                Logger.Information("Loading CDClient cache");
                await ClientCache.LoadAsync();
            });

            _ = Task.Run(async() =>
            {
                Logger.Information($"Setting up zones for world server {Id}");
                foreach (var zone in info.Info.Zones)
                {
                    await ZoneParser.LoadZoneDataAsync(zone);
                    await LoadZone(zone);
                }
            });
        }
Exemplo n.º 17
0
        public async Task EquipAsync(EquippedItem item)
        {
            await using var cdClient = new CdClientContext();

            var componentId = item.Lot.GetComponentId(ComponentId.ItemComponent);

            var info = await cdClient.ItemComponentTable.FirstAsync(i => i.Id == componentId);

            var location = (EquipLocation)info.EquipLocation;

            await UpdateSlotAsync(location, item);

            var skills = GameObject.TryGetComponent <SkillComponent>(out var skillComponent);

            if (skills)
            {
                await skillComponent.MountItemAsync(item.Lot);
            }

            await UpdateEquipState(item.Id, true);

            var proxies = await GenerateProxiesAsync(item.Id);

            foreach (var proxy in proxies)
            {
                var instance = await proxy.FindItemAsync();

                var lot = (Lot)instance.Lot;

                componentId = lot.GetComponentId(ComponentId.ItemComponent);

                info = await cdClient.ItemComponentTable.FirstOrDefaultAsync(i => i.Id == componentId);

                if (info == default)
                {
                    continue;
                }

                location = (EquipLocation)info.EquipLocation;

                await UpdateSlotAsync(location, new EquippedItem
                {
                    Id  = proxy,
                    Lot = lot
                });

                await UpdateEquipState(proxy, true);

                if (skills)
                {
                    await skillComponent.MountItemAsync(lot);
                }
            }
        }
Exemplo n.º 18
0
        public async Task <bool> CanAcceptAsync(int id)
        {
            await using var ctx = new CdClientContext();

            var mission = await ctx.MissionsTable.FirstAsync(m => m.Id == id);

            return(MissionParser.CheckPrerequiredMissions(
                       mission.PrereqMissionID,
                       GetCompletedMissions()
                       ));
        }
Exemplo n.º 19
0
        private async Task BuildAsync()
        {
            await using var ctx = new CdClientContext();

            foreach (var skill in BehaviorIds)
            {
                var root = BehaviorBase.Cache.ToArray().FirstOrDefault(b => b.BehaviorId == skill.BaseBehavior);

                if (root == default)
                {
                    var behavior = await ctx.BehaviorTemplateTable.FirstOrDefaultAsync(
                        t => t.BehaviorID == skill.BaseBehavior
                        );

                    if (behavior?.TemplateID == null)
                    {
                        continue;
                    }

                    var behaviorTypeId = (BehaviorTemplateId)behavior.TemplateID;

                    if (!Behaviors.TryGetValue(behaviorTypeId, out var behaviorType))
                    {
                        Logger.Error($"No behavior type of \"{behaviorTypeId}\" found.");

                        continue;
                    }

                    var instance = (BehaviorBase)Activator.CreateInstance(behaviorType);

                    instance.BehaviorId = skill.BaseBehavior;

                    BehaviorBase.Cache.Add(instance);

                    await instance.BuildAsync();

                    root = instance;
                }

                SkillRoots[skill.SkillId] = root;

                if (RootBehaviors.TryGetValue(skill.CastType, out var list))
                {
                    list.Add(root);
                }
                else
                {
                    RootBehaviors[skill.CastType] = new List <BehaviorBase> {
                        root
                    };
                }
            }
        }
Exemplo n.º 20
0
        protected InventoryComponent()
        {
            Listen(OnDestroyed, () =>
            {
                OnEquipped.Clear();
                OnUnEquipped.Clear();
            });

            Listen(OnStart, () =>
            {
                using var cdClient = new CdClientContext();

                var component = cdClient.ComponentsRegistryTable.FirstOrDefault(c =>
                                                                                c.Id == GameObject.Lot && c.Componenttype == (int)ComponentId.InventoryComponent);

                var items = cdClient.InventoryComponentTable.Where(i => i.Id == component.Componentid).ToArray();

                Items = new Dictionary <EquipLocation, InventoryItem>();

                foreach (var item in items)
                {
                    var cdClientObject = cdClient.ObjectsTable.FirstOrDefault(
                        o => o.Id == item.Itemid
                        );

                    var itemRegistryEntry = cdClient.ComponentsRegistryTable.FirstOrDefault(
                        r => r.Id == item.Itemid && r.Componenttype == 11
                        );

                    if (cdClientObject == default || itemRegistryEntry == default)
                    {
                        Logger.Error($"{item.Itemid} is not a valid item");
                        continue;
                    }

                    var itemComponent = cdClient.ItemComponentTable.First(
                        i => i.Id == itemRegistryEntry.Componentid
                        );

                    Debug.Assert(item.Itemid != null, "item.Itemid != null");
                    Debug.Assert(item.Count != null, "item.Count != null");

                    Items.TryAdd(itemComponent.EquipLocation, new InventoryItem
                    {
                        InventoryItemId = IdUtilities.GenerateObjectId(),
                        Count           = (long)item.Count,
                        LOT             = (int)item.Itemid,
                        Slot            = -1,
                        InventoryType   = -1
                    });
                }
            });
        }
Exemplo n.º 21
0
        /// <summary>
        /// Loads the initial cache
        /// </summary>
        public static async Task LoadAsync()
        {
            // Set up the cache tables.
            Logger.Debug("Setting up persistent cache tables");
            var loadTableTasks = new List <Task>();

            foreach (var clientTableType in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => (t.GetCustomAttribute <TableAttribute>() != null)))
            {
                // Determine the index.
                var indexPropertyInfo = clientTableType.GetProperties().FirstOrDefault(propertyInfo => propertyInfo.GetCustomAttribute <CacheIndexAttribute>() != null);
                if (indexPropertyInfo == null)
                {
                    continue;
                }

                // Get the cache type.
                var cacheType            = CacheMethod.Entry;
                var cacheMethodAttribute = clientTableType.GetCustomAttribute <CacheMethodAttribute>();
                if (cacheMethodAttribute != null)
                {
                    cacheType = cacheMethodAttribute.Method;
                }

                // Create the cache table if it is persistent.
                if (cacheType != CacheMethod.Persistent)
                {
                    continue;
                }
                Logger.Debug($"Setting up persistent cache table for {clientTableType.Name} with index {indexPropertyInfo.Name}");
                loadTableTasks.Add(Task.Run(async() =>
                {
                    await GetCacheTableAsync(clientTableType);
                }));
            }
            await Task.WhenAll(loadTableTasks);

            // Set up the mission cache.
            Logger.Debug("Setting up missions cache");
            await using var cdClient = new CdClientContext();
            var missionTasks = (await cdClient.MissionsTable.ToArrayAsync())
                               .Select(async m =>
            {
                var instance = new MissionInstance(m.Id ?? 0, default);
                await instance.LoadAsync();
                return(instance);
            }).ToList();

            await Task.WhenAll(missionTasks);

            Missions     = missionTasks.Select(t => t.Result).ToArray();
            Achievements = Missions.Where(m => !m.IsMission).ToArray();
        }
Exemplo n.º 22
0
        protected InventoryComponent()
        {
            Items = new Dictionary <EquipLocation, EquippedItem>();

            OnEquipped = new Event <Item>();

            OnUnEquipped = new Event <Item>();

            Listen(OnDestroyed, () =>
            {
                OnEquipped.Clear();
                OnUnEquipped.Clear();
            });

            Listen(OnStart, () =>
            {
                if (GameObject is Player)
                {
                    return;
                }

                using var cdClient = new CdClientContext();

                var component = cdClient.ComponentsRegistryTable.FirstOrDefault(c =>
                                                                                c.Id == GameObject.Lot && c.Componenttype == (int)ComponentId.InventoryComponent);

                var items = cdClient.InventoryComponentTable.Where(i => i.Id == component.Componentid).ToArray();

                foreach (var item in items)
                {
                    if (item.Itemid == default)
                    {
                        continue;
                    }

                    var lot = (Lot)item.Itemid;

                    var componentId = lot.GetComponentId(ComponentId.ItemComponent);

                    var info = cdClient.ItemComponentTable.First(i => i.Id == componentId);

                    var location = (EquipLocation)info.EquipLocation;

                    Items[location] = new EquippedItem
                    {
                        Id  = ObjectId.Standalone,
                        Lot = lot
                    };
                }
            });
        }
Exemplo n.º 23
0
        public async Task StartAsync()
        {
            await using var ctx      = new UchuContext();
            await using var cdClient = new CdClientContext();

            //
            // Setup new mission
            //

            var mission = await ctx.Missions.FirstOrDefaultAsync(
                m => m.CharacterId == Player.Id && m.MissionId == MissionId
                );

            var tasks = await cdClient.MissionTasksTable.Where(
                t => t.Id == MissionId
                ).ToArrayAsync();

            if (mission != default)
            {
                return;
            }

            await ctx.Missions.AddAsync(new Mission
            {
                CharacterId = Player.Id,
                MissionId   = MissionId,
                Tasks       = tasks.Select(task => new MissionTask
                {
                    TaskId = task.Uid ?? 0
                }).ToList()
            });

            await ctx.SaveChangesAsync();

            await UpdateMissionStateAsync(MissionState.Active);

            var clientMission = await cdClient.MissionsTable.FirstAsync(
                m => m.Id == MissionId
                );

            MessageMissionTypeState(MissionLockState.New, clientMission.Definedsubtype, clientMission.Definedtype);

            await CatchupAsync();

            if (Player.TryGetComponent <MissionInventoryComponent>(out var missionInventory))
            {
                await missionInventory.OnAcceptMission.InvokeAsync(this);
            }
        }
Exemplo n.º 24
0
        protected DestructibleComponent()
        {
            OnSmashed = new Event <GameObject, Player>();

            OnResurrect = new Event();

            Listen(OnStart, async() =>
            {
                if (GameObject.Settings.TryGetValue("respawn", out var resTimer))
                {
                    ResurrectTime = resTimer switch
                    {
                        uint timer => timer,
                        float timer => timer,
                        int timer => timer,
                        _ => ResurrectTime
                    };
                }

                var container = GameObject.AddComponent <LootContainerComponent>();

                await container.CollectDetailsAsync();

                GameObject.Layer = StandardLayer.Smashable;

                await using (var cdClient = new CdClientContext())
                {
                    var entry = GameObject.Lot.GetComponentId(ComponentId.DestructibleComponent);

                    var cdClientComponent = cdClient.DestructibleComponentTable.FirstOrDefault(
                        c => c.Id == entry
                        );

                    if (cdClientComponent == default)
                    {
                        Logger.Error($"{GameObject} has a corrupt Destructible Component of id: {entry}");
                    }
                }

                if (GameObject.TryGetComponent(out Stats stats))
                {
                    Stats = stats;

                    Listen(Stats.OnDeath, async() =>
                    {
                        await SmashAsync(
                            Stats.LatestDamageSource,
                            Stats.LatestDamageSource is Player player ? player : default,
Exemplo n.º 25
0
        private static async Task <bool> CheckForDatabaseUpdatesAsync()
        {
            try
            {
                await using var uchuContext = new UchuContext();
                await uchuContext.EnsureUpdatedAsync();

                await using var cdClientContext = new CdClientContext();
                await cdClientContext.EnsureUpdatedAsync();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 26
0
        public static async Task AttachmentCollectHandler(MailAttachmentCollected packet, Player player)
        {
            var response = new AttachmentCollectConfirm
            {
                MailId = packet.MailId
            };

            await using var ctx           = new UchuContext();
            await using var clientContext = new CdClientContext();

            var mail = await ctx.Mails.FirstOrDefaultAsync(m => m.Id == packet.MailId);

            if (mail == default)
            {
                response.Code = MailAttachmentCollectCode.MailForFound;
                goto sendResponse;
            }

            if (mail.AttachmentLot == -1 || mail.AttachmentCount == default)
            {
                response.Code = MailAttachmentCollectCode.InvalidAttachment;

                goto sendResponse;
            }

            await player.GetComponent <InventoryManagerComponent>().AddLotAsync(mail.AttachmentLot, mail.AttachmentCount, lootType: LootType.Mail);

            mail.AttachmentLot   = -1;
            mail.AttachmentCount = 0;

            var character = player.GetComponent <CharacterComponent>();

            character.Currency += (long)mail.AttachmentCurrency;
            response.Code       = MailAttachmentCollectCode.Success;

sendResponse:

            await ctx.SaveChangesAsync();

            player.Message(new ServerMailPacket
            {
                Id         = ServerMailPacketId.AttachmentCollectedConfirm,
                MailStruct = response
            });
        }
Exemplo n.º 27
0
        public async Task MessageUpdateMissionTaskAsync(float[] updates)
        {
            await using var cdClient = new CdClientContext();

            var clientTasks = await cdClient.MissionTasksTable.Where(
                t => t.Id == MissionId
                ).ToArrayAsync();

            var clientTask = clientTasks.First(c => c.Uid == TaskId);

            Player.Message(new NotifyMissionTaskMessage
            {
                Associate = Player,
                MissionId = MissionId,
                TaskIndex = clientTasks.IndexOf(clientTask),
                Updates   = updates
            });
        }
Exemplo n.º 28
0
        public static async Task <BehaviorBase> BuildBranch(int behaviorId)
        {
            var cachedBehavior = Cache.ToArray().FirstOrDefault(c => c.BehaviorId == behaviorId);

            if (cachedBehavior != default)
            {
                return(cachedBehavior);
            }

            await using var ctx = new CdClientContext();

            var behavior = await ctx.BehaviorTemplateTable.FirstOrDefaultAsync(
                t => t.BehaviorID == behaviorId
                );

            if (behavior?.TemplateID == null)
            {
                return(new EmptyBehavior());
            }

            var behaviorTypeId = (BehaviorTemplateId)behavior.TemplateID;

            if (!BehaviorTree.Behaviors.TryGetValue(behaviorTypeId, out var behaviorType))
            {
                Logger.Error($"No behavior type of \"{behaviorTypeId}\" found.");

                return(new EmptyBehavior());
            }

            var instance = (BehaviorBase)Activator.CreateInstance(behaviorType);

            instance.BehaviorId = behaviorId;

            instance.EffectId = behavior.EffectID ?? 0;

            instance.EffectHandler = behavior.EffectHandle;

            Cache.Add(instance);

            await instance.BuildAsync();

            return(instance);
        }
Exemplo n.º 29
0
Arquivo: Item.cs Projeto: kulaj/Uchu
        public static Item Instantiate(long itemId, Inventory inventory)
        {
            using var cdClient = new CdClientContext();
            using var ctx      = new UchuContext();

            var item = ctx.InventoryItems.FirstOrDefault(
                i => i.Id == itemId && i.Character.Id == inventory.ManagerComponent.GameObject.Id
                );

            if (item == default)
            {
                Logger.Error($"{itemId} is not an item on {inventory.ManagerComponent.GameObject}");
                return(null);
            }

            var cdClientObject = cdClient.ObjectsTable.FirstOrDefault(
                o => o.Id == item.Lot
                );

            var itemRegistryEntry = ((Lot)item.Lot).GetComponentId(ComponentId.ItemComponent);

            if (cdClientObject == default || itemRegistryEntry == default)
            {
                Logger.Error($"{itemId} [{item.Lot}] is not a valid item");
                return(null);
            }

            var instance = Instantiate <Item>
                           (
                inventory.ManagerComponent.Zone, cdClientObject.Name, objectId: itemId, lot: item.Lot
                           );

            if (!string.IsNullOrWhiteSpace(item.ExtraInfo))
            {
                instance.Settings = LegoDataDictionary.FromString(item.ExtraInfo);
            }

            instance.Inventory = inventory;
            instance.Player    = inventory.ManagerComponent.GameObject as Player;

            return(instance);
        }
Exemplo n.º 30
0
Arquivo: Item.cs Projeto: kulaj/Uchu
        protected Item()
        {
            OnConsumed = new Event();

            Listen(OnStart, () =>
            {
                IsPackage = Lot.GetComponentId(ComponentId.PackageComponent) != default;

                using var cdClient = new CdClientContext();

                var skills = cdClient.ObjectSkillsTable.Where(
                    s => s.ObjectTemplate == Lot
                    ).ToArray();

                IsConsumable = skills.Any(
                    s => s.CastOnType == (int)SkillCastType.OnConsumed
                    );
            });

            Listen(OnDestroyed, () => Inventory.UnManageItem(this));
        }