public Template(IItem item, IList<IItem> items)
        {
            Assert.IsTrue(new ID(item.TemplateID).Equals(Sitecore.TemplateIDs.Template), "item must be template");

            _item = item;
            _items = items;
        }
 public void AddItemToBuilder(IItem item, string name, SolutionMessage.Builder builder) {
   IStringConvertibleValue value = (item as IStringConvertibleValue);
   if (value != null) {
     SolutionMessage.Types.StringVariable.Builder var = SolutionMessage.Types.StringVariable.CreateBuilder();
     var.SetName(name).SetData(value.GetValue());
     builder.AddStringVars(var.Build());
   } else {
     IStringConvertibleArray array = (item as IStringConvertibleArray);
     if (array != null) {
       SolutionMessage.Types.StringArrayVariable.Builder var = SolutionMessage.Types.StringArrayVariable.CreateBuilder();
       var.SetName(name).SetLength(array.Length);
       for (int i = 0; i < array.Length; i++)
         var.AddData(array.GetValue(i));
       builder.AddStringArrayVars(var.Build());
     } else {
       IStringConvertibleMatrix matrix = (item as IStringConvertibleMatrix);
       if (matrix != null) {
         SolutionMessage.Types.StringArrayVariable.Builder var = SolutionMessage.Types.StringArrayVariable.CreateBuilder();
         var.SetName(name).SetLength(matrix.Columns);
         for (int i = 0; i < matrix.Rows; i++)
           for (int j = 0; j < matrix.Columns; j++)
             var.AddData(matrix.GetValue(i, j));
         builder.AddStringArrayVars(var.Build());
       } else {
         throw new ArgumentException(ItemName + ": Item is not of a supported type.", "item");
       }
     }
   }
 }
Beispiel #3
0
        public override void ItemClick(IItem item)
        {
            try
            {
                if (item != null)
                {
                    var model = item.Model;
                    var obj = (WcfService.Dto.ReportJobDto)model;
                    var tipo = UtilityValidation.GetStringND(obj.Tipo);
                    var viewModel = (ReportJob.ReportJobViewModel)ViewModel;
                    ISpace space = null;
                    if (tipo == Tipi.TipoReport.Fornitore.ToString())
                        space = viewModel.GetModel<ReportJobFornitoreModel>(model);
                    else if (tipo == Tipi.TipoReport.Fornitori.ToString())
                        space = viewModel.GetModel<ReportJobFornitoriModel>(model);
                    else if (tipo == Tipi.TipoReport.Committente.ToString())
                        space = viewModel.GetModel<ReportJobCommittenteModel>(model);
                    else if (tipo == Tipi.TipoReport.Committenti.ToString())
                        space = viewModel.GetModel<ReportJobCommittentiModel>(model);

                    AddSpace(space);
                }
            }
            catch (Exception ex)
            {
                UtilityError.Write(ex);
            } 
        }
    public static ItemArray<IItem> Apply(IItem initiator, IItem guide, IntValue k, PercentValue n) {
      if (!(initiator is RealVector) || !(guide is RealVector))
        throw new ArgumentException("Cannot relink path because one of the provided solutions or both have the wrong type.");
      if (n.Value <= 0.0)
        throw new ArgumentException("RelinkingAccuracy must be greater than 0.");

      RealVector v1 = initiator.Clone() as RealVector;
      RealVector v2 = guide as RealVector;

      if (v1.Length != v2.Length)
        throw new ArgumentException("The solutions are of different length.");

      IList<RealVector> solutions = new List<RealVector>();
      for (int i = 0; i < k.Value; i++) {
        RealVector solution = v1.Clone() as RealVector;
        for (int j = 0; j < solution.Length; j++)
          solution[j] = v1[j] + 1 / (k.Value - i) * (v2[j] - v1[j]);
        solutions.Add(solution);
      }

      IList<IItem> selection = new List<IItem>();
      if (solutions.Count > 0) {
        int noSol = (int)(solutions.Count * n.Value);
        if (noSol <= 0) noSol++;
        double stepSize = (double)solutions.Count / (double)noSol;
        for (int i = 0; i < noSol; i++)
          selection.Add(solutions.ElementAt((int)((i + 1) * stepSize - stepSize * 0.5)));
      }

      return new ItemArray<IItem>(selection);
    }
Beispiel #5
0
 public ItemSprite(IItem item, Texture2D sprite)
     : base(sprite)
 {
     this.mItem = item;
     ItemDescription = new StringBuilder();
     ShowItemDescription();
 }
Beispiel #6
0
    public void Hold(IItem holdable)
    {
        if (holdable == null)
        {
            return;
        }

        if (currentHeldObject != null)
        {
            Drop(holdable);
        }

        currentHeldObject = holdable;

        CollisionIgnoreManager collisionIgnore = holdable.gameObject.GetComponent<CollisionIgnoreManager>();
        if (collisionIgnore)
        {
            collisionIgnore.otherGameObject = anchorRigidbody.transform.parent.gameObject;
            collisionIgnore.Ignore();
        }

        //holdable.gameObject.transform.SetParent(transform, false);
        holdable.gameObject.transform.position = transform.position;
        holdable.gameObject.transform.rotation = transform.rotation;

        FixedJoint joint = gameObject.AddComponent<FixedJoint>();
        joint.connectedBody = holdable.gameObject.GetComponent<Rigidbody>();

        holdable.OnHold(this);
    }
            public void InitializeContext()
            {
                this.textTemplateFile = this.solution.Find<IItem>().First();

                this.store.TransactionManager.DoWithinTransaction(() =>
                {
                    var patternModel = this.store.ElementFactory.CreateElement<PatternModelSchema>();
                    var pattern = patternModel.Create<PatternSchema>();
                    var view = pattern.CreateViewSchema();
                    var parent = view.CreateElementSchema();
                    this.element = parent.CreateAutomationSettingsSchema() as AutomationSettingsSchema;
                    this.settings = element.AddExtension<CommandSettings>();

                    this.settings.TypeId = typeof(GenerateModelingCodeCommand).Name;
                    ((ICommandSettings)this.settings).Properties.Add(new PropertyBindingSettings { Name = Reflector<GenerateModelingCodeCommand>.GetPropertyName(u => u.TargetFileName) });
                    ((ICommandSettings)this.settings).Properties.Add(new PropertyBindingSettings { Name = Reflector<GenerateModelingCodeCommand>.GetPropertyName(u => u.TargetPath) });
                    ((ICommandSettings)this.settings).Properties.Add(new PropertyBindingSettings { Name = Reflector<GenerateModelingCodeCommand>.GetPropertyName(u => u.TemplateAuthoringUri) });
                    ((ICommandSettings)this.settings).Properties.Add(new PropertyBindingSettings { Name = Reflector<GenerateModelingCodeCommand>.GetPropertyName(u => u.TemplateUri) });

                });

                this.serviceProvider = new Mock<IServiceProvider>();
                this.uriService = new Mock<IUriReferenceService>();
                this.serviceProvider.Setup(sp => sp.GetService(typeof(IUriReferenceService))).Returns(this.uriService.Object);
                this.validation = new GenerateModelingCodeCommandValidation
                {
                    serviceProvider = this.serviceProvider.Object,
                };

                this.validationContext = new ValidationContext(ValidationCategories.Custom, this.settings);
            }
Beispiel #8
0
        public bool EquipItem(IItem item, IInventory inventory) {
            bool result = false;

            IWeapon weaponItem = item as IWeapon;
            if (weaponItem != null && weaponItem.IsWieldable) {
                //can't equip a wieldable weapon
            }
            else {
                if (!equipped.ContainsKey(item.WornOn)) {
                    equipped.Add(item.WornOn, item);
                    if (inventory.inventory.Any(i => i.Id == item.Id)) {//in case we are adding it from a load and not moving it from the inventory
                        inventory.inventory.RemoveWhere(i => i.Id == item.Id); //we moved the item over to equipped so we need it out of inventory
                    }
                    result = true;
                }
                else if (item.WornOn == Wearable.WIELD_LEFT || item.WornOn == Wearable.WIELD_RIGHT) { //this item can go in the free hand
                    Wearable freeHand = Wearable.WIELD_LEFT; //we default to right hand for weapons
                    if (equipped.ContainsKey(freeHand)) freeHand = Wearable.WIELD_RIGHT; //maybe this perosn is left handed
                    if (!equipped.ContainsKey(freeHand)) { //ok let's equip this
                        item.WornOn = freeHand;
                        item.Save();
                        equipped.Add(freeHand, item);
                        if (inventory.inventory.Any(i => i.Id == item.Id)) {//in case we are adding it from a load and not moving it from the inventory
                            inventory.inventory.RemoveWhere(i => i.Id == item.Id); //we moved the item over to equipped so we need it out of inventory
                        }
                        result = true;
                    }
                }
            }

            return result;
        }
 public void Add(IItem item)
 {
     if (!itens.Contains(item)) {
         item.ApplyEffect(player);
         this.itens.Add(item);
     }
 }
Beispiel #10
0
        public void AddComponent(IItem equipment)
        {
            //If this item is stackable, then rather than adding it to the
            //collection, will just increase the stacked number
            if (equipment.IsStackable)
            {
                bool found = false;

                //Loop through each item in the collection
                foreach (IItem item in Components.Keys)
                {
                    //If we find a match
                    if (item == equipment)
                    {
                        //Increase the value of the stack
                        //but don't add it to the collection
                        Components[item]++;
                        found = true;
                        break;
                    }
                }

                //If we did not find an existing item, add it to the
                //collecton
                if (!found)
                    Components.Add(equipment, 1);
            }
                //if it's not stackable, then add this single item to
                //the collection.
            else
                Components.Add(equipment, 1);
        }
        public static void Run(IItem[] items)
        {
            var book = items[0];

            // 1. serialize a single book to a JSON string
            Console.WriteLine(JsonConvert.SerializeObject(book));

            // 2. ... with nicer formatting
            Console.WriteLine(JsonConvert.SerializeObject(book, Formatting.Indented));

            // 3. serialize all items
            // ... include type, so we can deserialize sub-classes to interface type
            var settings = new JsonSerializerSettings() { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto };
            Console.WriteLine(JsonConvert.SerializeObject(items, settings));

            // 4. store json string to file "items.json" on your Desktop
            var text = JsonConvert.SerializeObject(items, settings);
            var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var filename = Path.Combine(desktop, "items.json");
            File.WriteAllText(filename, text);

            // 5. deserialize items from "items.json"
            // ... and print Description and Price of deserialized items
            var textFromFile = File.ReadAllText(filename);
            var itemsFromFile = JsonConvert.DeserializeObject<IItem[]>(textFromFile, settings);
            var currency = Currency.EUR;
            foreach (var x in itemsFromFile) Console.WriteLine($"{x.Description.Truncate(50),-50} {x.Price.ConvertTo(currency).Amount,8:0.00} {currency}");
        }
 public NewItemDialog() {
   InitializeComponent();
   treeNodes = new List<TreeNode>();
   currentSearchString = string.Empty;
   item = null;
   SelectedTypeChanged += this_SelectedTypeChanged;
 }
    public override void Execute() {
      IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
      content = activeView.Content as IItem;

      //IOptimizer and IExecutables need some special care
      if (content is IOptimizer) {
        ((IOptimizer)content).Runs.Clear();
      }
      if (content is IExecutable) {
        IExecutable exec = content as IExecutable;
        if (exec.ExecutionState != ExecutionState.Prepared) {
          exec.Prepare();
        }
      }

      HiveClient.Instance.Refresh();

      ItemTask hiveTask = ItemTask.GetItemTaskForItem(content);
      HiveTask task = hiveTask.CreateHiveTask();
      RefreshableJob rJob = new RefreshableJob();
      rJob.Job.Name = content.ToString();
      rJob.HiveTasks.Add(task);
      task.ItemTask.ComputeInParallel = content is Experiment || content is BatchRun;

      progress = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToContent(this.content, "Uploading to Hive...");
      rJob.Progress = progress;
      progress.ProgressStateChanged += progress_ProgressStateChanged;

      HiveClient.StartJob(new Action<Exception>(HandleEx), rJob, new CancellationToken());
    }
Beispiel #14
0
 public Rent(IItem item)
 {
     this.Item = item;
     this.RentDate = DateTime.Now;
     this.Deadline = this.RentDate.AddDays(30);
     this.RentState = RentState.Pending;
 }
Beispiel #15
0
 private bool CanEquip(IItem item)
 {
     var weapon = item as IWeapon;
     if (weapon != null) {
         switch (weapon.Class) {
             case WeaponClass.Simple:
                 return _character.Features.Any(x => x == Feature.SimpleWeaponProficiency);
             case WeaponClass.Martial:
                 return _character.Features.Any(x => x == Feature.MartialWeaponProficiency);
             case WeaponClass.Exotic:
                 return _character.Features.Any(x => x == Feature.ExoticWeaponProficiency);
             default:
                 break;
         }
     }
     var armor = item as IArmor;
     if (armor != null) {
         switch (armor.Class) {
             case ArmorClass.Light:
                 return _character.Features.Any(x => x == Feature.LightArmorProficiency);
             case ArmorClass.Medium:
                 return _character.Features.Any(x => x == Feature.MediumArmorProficiency);
             case ArmorClass.Heavy:
                 return _character.Features.Any(x => x == Feature.HeavyArmorProficiency);
             case ArmorClass.Shield:
                 return _character.Features.Any(x => x == Feature.ShieldProficiency);
             default:
                 break;
         }
     }
     return false;
 }
 public void Use(IItem item, World world, ICreature user)
 {
     Announcer.Instance.Announce(user.Name + " feels different. ", MessageTypes.Other);
     Announcer.Instance.Announce(user.Name + " is under the affect of " + _effect.Name + "!", MessageTypes.Other);
     user.AddTemporaryEffect(_effect);
     user.Inventory.Remove(item);
 }
Beispiel #17
0
 public void AddItem(IItem item)
 {
     if (!HasItem(item.ItemName))
     {
         _items.Add(item);                
     }
 }
        public bool CheckCheckBox(IItem sourceItem, IItem destinationParentItem, IItem destinationItem)
        {
            IItem mainTemplateItem = GetMainTemplateItem(destinationItem);

            if (mainTemplateItem != null && mainTemplateItem.Key.Equals("fff.departmentitem") && destinationItem.Key.Equals("publishingmode"))
            {
                if (destinationParentItem != null && destinationParentItem.Key.Equals("crm synkronisering"))
                {
                    IField destinationField = destinationItem.Fields.Last<IField>(currentField => (currentField.Key.Equals("source")));
                    destinationField.Content = "Modified by Phong";
                }

            }

            //Get Field that matches our FieldName. FieldName is assumed unique.
            //IField foundField = null;
            //try
            //{
            //    foundField = sourceItem.Fields.Last<IField>(currentField => (currentField.Key.Equals("__never publish")));
            //}
            //catch { }

            //Store the converted field into destination Field. FieldName is assumed unique.
            //IField destinationField = destinationItem.Fields.Last<IField>(currentField => (currentField.Key.Equals("__never publish")));

            //            destinationItem.Template.Fields

            //Sitecore6xItem itm = Sitecore6xItem.GetItem(destinationItem.Path,
            //if (destinationField != null)
            //    destinationField.Content = "1";

            return true;
        }
        private void Search(IItem rootItem, string sFind)
        {
            foreach (IItem item in rootItem.GetChildren())
            {
                if (_bStop)
                    return;

                tbSearchingIn.Text = item.Path;
                foreach (IField field in item.Fields)
                {
                    if (field.Content.ToLower().IndexOf(sFind.ToLower()) > -1)
                    {
                        lbSearchResult.Items.Add(item.Path);
                        lock (_itemsFound)
                        {
                            _itemsFound.Add(item.Path, item);
                        }
                        break;
                    }
                }
                Application.DoEvents();
                _myExpandNode(item);

                Application.DoEvents();
                if (item.HasChildren())
                {
                    Search(item, sFind);
                }
            }
        }
        /// <summary>
        /// This method will eventually defer to the ISitecoreRepository to render the field value.
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string GetField(string fieldName, IItem item, Dictionary<string, string> parameters)
        {
            if (item != null)
            {
                if (!String.IsNullOrEmpty(fieldName))
                {
                    // Get the ISitecoreRepository to check if the field actually exists.
                    if (_sitecoreRepository.FieldExists(fieldName, item))
                    {
                        // Helper to return field parameters for this particular field (the dictionary contains all fields + their parameters)
                        string fieldParameters = GetFieldParameters(fieldName, parameters);

                        if (!String.IsNullOrEmpty(fieldParameters))
                        {
                            // Get field value from Sitecore, having already checked for null/empty, and whether or not the field actually exists.
                            return _sitecoreRepository.GetFieldValue(fieldName, item, fieldParameters);
                        }
                        else
                        {
                            return _sitecoreRepository.GetFieldValue(fieldName, item);
                        }
                    }
                }
            }

            return String.Empty;
        }
Beispiel #21
0
 public Rent(IItem item, DateTime rentDate)
 {
     this.Item = item;
     this.RentDate = rentDate;
     this.Deadline = rentDate.AddDays(30);
     this.RentState = RentState.Pending;
 }
 public void Initialize()
 {
     this.item1 = this.solution.Find<IItem>().First();
     this.item2 = this.solution.Find<IItem>().Last();
     this.serviceProvider = new Mock<IServiceProvider>();
     this.serviceProvider.Setup(s => s.GetService(typeof(IUriReferenceService))).Returns(UriReferenceServiceFactory.CreateService(new[] { new SolutionUriProvider() }));
 }
Beispiel #23
0
 public Rent(IItem item, DateTime rentDate, DateTime deadline)
 {
     this.Item = item;
     this.RentDate = rentDate;
     this.Deadline = deadline;
     this.RentState = RentState.Pending;
 }
Beispiel #24
0
		public override IItem[] Perform (IItem[] items, IItem[] modifierItems)
		{
				foreach (RipItem item in items ) {
					Util.Environment.Open (item.URL);
				}
			return null;
		}
        /// <summary>
        /// Configures the files included in the template for VSIX packaging,
        /// and returns the Uri for the template.
        /// </summary>
        public IVsTemplate Configure(IItem templateItem, string displayName, string description, string path)
        {
            Guard.NotNull(() => templateItem, templateItem);

            // Calculate the new Identifier
            var unicySeed = Guid.NewGuid().ToString(@"N");
            var unicyIdentifier = unicySeed.Substring(unicySeed.Length - MaxUnicyLength);
            var remainingNamedLength = MaxTemplateIdLength - MaxUnicyLength - 1;
            var namedIdentifier = path.Substring(path.Length <= remainingNamedLength ? 0 : (path.Length - remainingNamedLength));
            var templateId = string.Format(CultureInfo.InvariantCulture, @"{0}-{1}", unicyIdentifier, namedIdentifier);

            // Update the vstemplate
            var template = VsTemplateFile.Read(templateItem.PhysicalPath);
            template.SetTemplateId(templateId);
            template.SetDefaultName(SanitizeName(displayName));
            template.SetName(displayName);
            template.SetDescription(description);
            VsHelper.CheckOut(template.PhysicalPath);
            VsTemplateFile.Write(template);

            UpdateDirectoryProperties(templateItem);

            // Set VS attributes on the vstemplate file
            if (template.Type == VsTemplateType.Item)
            {
                templateItem.Data.ItemType = @"ItemTemplate";
            }
            else
            {
                templateItem.Data.ItemType = @"ProjectTemplate";
            }

            return template;
        }
 public void Use(IItem item, World world, ICreature user)
 {
     if (item.ItemCategory == ItemCategories.Weapon)
     {
         user.Weapon = (IWeapon)item;
         Announcer.Instance.Announce(user.Name + " is now using " + item.Name + ".", MessageTypes.GetItem);
     }
 }
Beispiel #27
0
 public double Sell(IItem item)
 {
     double retVal = item.Value;
     if (Remove(item))
         return retVal;
     else
         return 0;
 }
		public IEnumerable<IItem> GetCombinedBaseTemplates(IItem item, IEnumerable<IItem> items)
		{
			var baseTemplates = new List<IItem>();

			this.GetCombinedBaseTemplates(item, baseTemplates, items);

			return baseTemplates;
		}
		public IEnumerable<string> GetBaseTemplateIds(IItem item, IEnumerable<IItem> items)
		{
			var baseTemplateIds = new List<string>();

			this.GetBaseTemplatesIds(item, item.Id, baseTemplateIds, items);

			return baseTemplateIds;
		}
	/// <summary>
	/// Combine the specified firstItem and secondItem, or returns NULL if no combination is found
	/// </summary>
	/// <param name="firstItem">First item.</param>
	/// <param name="secondItem">Second item.</param>
	public IItem Combine(IItem firstItem, IItem secondItem){
		foreach (Combination c in combinations){
			if (c.firstItem == firstItem && c.secondItem == secondItem || c.firstItem == secondItem && c.secondItem == firstItem){
				return c.result;
			}
		}
		return null;
	}
Beispiel #31
0
 public CheesySauceDecorator(IItem pizzaComponent)
 {
     pizza = pizzaComponent;
 }
Beispiel #32
0
 public void AddItem(IItem item)
 {
     _itemsInCart.Add(item);
 }
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="count">The desired count of items to get.</param>
        /// <returns>The items.</returns>
        public IEnumerable <IItem> GetItems(int count)
        {
            if (count < 1 ||
                _options.FacetDefinitions == null ||
                _options.FacetDefinitions.Length == 0)
            {
                yield break;
            }

            // init
            if (_options.Seed.HasValue)
            {
                Randomizer.Seed = new Random(_options.Seed.Value);
            }

            ItemSeeder itemSeeder = _factory.GetItemSeeder();

            _partSeeders = _factory.GetPartSeeders();
            IItemSortKeyBuilder sortKeyBuilder = _factory.GetItemSortKeyBuilder();

            // generate items
            for (int n = 1; n <= count; n++)
            {
                // pick a facet
                FacetDefinition facet = _options.FacetDefinitions[
                    _options.FacetDefinitions.Length == 1
                    ? 0
                    : Randomizer.Seed.Next(0, _options.FacetDefinitions.Length)];

                // get item
                IItem item = itemSeeder.GetItem(n, facet.Id);

                // add parts: first non layer parts, then the others.
                // This ensures that the item already has the base text part
                // before adding the layer parts, which refer to it.

                // 1) non-layer parts, required
                AddParts(facet.PartDefinitions
                         .Where(def => !IsLayerPart(def) && def.IsRequired),
                         item,
                         false);

                // 2) non-layer parts, optional
                AddParts(facet.PartDefinitions
                         .Where(def => !IsLayerPart(def) && !def.IsRequired),
                         item,
                         true);

                // 3) layer-parts
                // we must have a base text definition to have layers
                PartDefinition baseTextDef = facet.PartDefinitions.Find(
                    def => def.RoleId == PartBase.BASE_TEXT_ROLE_ID);

                if (baseTextDef != null && Randomizer.Seed.Next(0, 2) == 1)
                {
                    // ensure there is a base text. This is required for
                    // the text layer part seeder, which must rely on a base text.
                    IPart baseTextPart = item.Parts.Find(
                        p => p.TypeId == baseTextDef.TypeId);

                    // add a base text if none found
                    if (baseTextPart == null)
                    {
                        baseTextPart = GetPart(item, baseTextDef);
                        if (baseTextPart != null)
                        {
                            item.Parts.Add(baseTextPart);
                        }
                    }

                    // once we have one, eventually add layer(s)
                    if (baseTextPart != null)
                    {
                        // 3) layer parts, required
                        AddParts(facet.PartDefinitions
                                 .Where(def => IsLayerPart(def) && def.IsRequired),
                                 item,
                                 false);

                        // 4) layer parts, optional
                        AddParts(facet.PartDefinitions
                                 .Where(def => IsLayerPart(def) && !def.IsRequired),
                                 item,
                                 true);
                    }
                }

                // once all the parts are in place, override the item's sort key
                // if requested in the config.
                // Note that we do not provide a repository, as while seeding
                // there might be no database, and all the item's parts are
                // in the item itself.
                if (sortKeyBuilder != null)
                {
                    item.SortKey = sortKeyBuilder.BuildKey(item, null);
                }

                yield return(item);
            }
        }
Beispiel #34
0
 public HotbarItemWeaponOverlayControl(IItem item)
 {
     this.item = item;
 }
 /// <summary>
 /// Triggered when the ItemSelect has its selection changed.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ItemSelect_ItemSelected(object sender, IItem item)
 {
     UpdateViews(item);
 }
Beispiel #36
0
    public void Update()
    {
        UpdateAttack();
        UpdateMovement();

        void UpdateWeapon()
        {
            if (weapon == null || !actor.Inventory.Contains(weapon) || weapon.Gun.AmmoLeft + weapon.Gun.ClipLeft == 0)
            {
                weapon = actor.Inventory.FirstOrDefault(i => i.Gun != null && i.Gun.AmmoLeft + i.Gun.ClipLeft > 0);
            }
        }

        void UpdateAttack()
        {
            if (attack == null || attack.Done())
            {
                UpdateWeapon();
                if (weapon == null)
                {
                    return;
                }
                var enemies = new HashSet <Entity>();
                foreach (var point in actor.World.entities.space.Keys)
                {
                    if (((XYZ)point - actor.Position).Magnitude < 100)
                    {
                        enemies.UnionWith(actor.World.entities[point].OfType <ICharacter>());
                    }
                }
                enemies.Remove(actor);
                enemies = enemies.Where(e => (e.Position - actor.Position).Magnitude < weapon.Gun.range).ToHashSet();
                if (enemies.Any())
                {
                    var target = enemies.First();
                    attack = new ShootAction(actor, weapon, new TargetEntity(target));
                    actor.Actions.Add(attack);
                }
            }
        }

        void UpdateMovement()
        {
            if (movement == null || movement.Done())
            {
                UpdateWeapon();
                if (weapon == null)
                {
                    var weapons = new HashSet <IItem>();
                    foreach (var point in actor.World.entities.space.Keys)
                    {
                        if (((XYZ)point - actor.Position).Magnitude < 100)
                        {
                            weapons.UnionWith(actor.World.entities[point].OfType <IItem>());
                        }
                    }
                    if (!weapons.Any())
                    {
                        UpdateWander();
                        return;
                    }
                    var target = weapons.OrderBy(w => (w.Position - actor.Position).Magnitude2).First();

                    Dictionary <(int, int, int), (int, int, int)> prev = new Dictionary <(int, int, int), (int, int, int)>();
                    var points = new SimplePriorityQueue <XYZ, double>();
                    //Truncate to integer coordinates so we don't get confused by floats
                    (int, int, int)start    = target.Position.i;
                    (int, int, int)actorPos = actor.Position.i;
                    prev[start]             = start;
                    points.Enqueue(start, 0);
                    int  seen    = 0;
                    bool success = false;
                    while (points.Any() && seen < 500 && !success)
                    {
                        var point = points.Dequeue();

                        foreach (var offset in new XYZ[] { new XYZ(0, 1), new XYZ(1, 0), new XYZ(0, -1), new XYZ(-1, 0) })
                        {
                            var next = point + offset;
                            if (prev.ContainsKey(next))
                            {
                                continue;
                            }
                            else if (CanOccupy(next))
                            {
                                prev[next] = point;
                                //Truncate to integer coordinates so we don't get confused by floats
                                if (next.Equals(actorPos))
                                {
                                    success = true;
                                    break;
                                }
                                else
                                {
                                    points.Enqueue(next, (next - actorPos).Magnitude);
                                }
                            }
                        }
                    }

                    if (success)
                    {
                        LinkedList <XYZ> path = new LinkedList <XYZ>();

                        XYZ p = prev[actor.Position];
                        path.AddLast(p);
                        while (!p.Equals(start))
                        {
                            p = prev[p];
                            path.AddLast(p);
                        }

                        movement = new CompoundAction(new FollowPath(actor, path), new TakeItem(actor, target));
                        actor.Actions.Add(movement);
                    }
                    else
                    {
                        UpdateWander();
                    }
                }
                else
                {
                    UpdateWander();
                }
            }
        }

        void UpdateWander()
        {
            HashSet <(int, int, int)> known               = new HashSet <(int, int, int)>();
            HashSet <XYZ>             accessible          = new HashSet <XYZ>();
            Dictionary <(int, int, int), (XYZ, int)> prev = new Dictionary <(int, int, int), (XYZ, int)>();
            Queue <XYZ> points = new Queue <XYZ>();

            var start = actor.Position.i;

            points.Enqueue(start);
            prev[start] = (null, 0);
            int seen = 0;

            while (points.Count > 0 && seen < 500)
            {
                var point = points.Dequeue().i;
                known.Add(point);
                seen++;
                if (CanOccupy(point))
                {
                    accessible.Add(point);
                    foreach (var offset in new XYZ[] { new XYZ(0, 1), new XYZ(1, 0), new XYZ(0, -1), new XYZ(-1, 0) })
                    {
                        var next = point + offset;
                        var dist = prev[point].Item2 + 1;
                        if (known.Add(next))
                        {
                            prev[next] = (point, dist);
                            points.Enqueue(next);
                        }
                        else if (prev.TryGetValue(next, out (XYZ, int)v) && v.Item2 > dist)
                        {
                            prev[next] = (point, dist);
                        }
                    }
                }
            }

            var dest = accessible.OrderByDescending(xyz => (actor.Position - xyz).Magnitude2).ElementAt(new Random().Next(0, 4));
            var path = new LinkedList <XYZ>();

            while (dest != null)
            {
                path.AddFirst(dest);
                XYZ next;
                (next, _) = prev[dest];
                dest      = next;
            }
            movement = new FollowPath(actor, path);
            actor.Actions.Add(movement);
        }

        bool CanOccupy(XYZ position)
        {
            var v     = actor.World.voxels.Try(position);
            var below = actor.World.voxels.Try(position.PlusZ(-1));

            return(v is Air || v is Floor || below?.Collision == VoxelType.Solid);
        }
    }
Beispiel #37
0
 public ItemImagemController(IItem repository)
 {
     _repository = repository;
 }
Beispiel #38
0
 public override void CheckInFile(ISiteSetting siteSetting, IItem item, string comment, CheckinTypes checkinType)
 {
     ItemsManager.CheckInItem(siteSetting, item, this.ConnectorExplorer.ConnectorExplorer);
 }
Beispiel #39
0
 public override void UndoCheckOutFile(ISiteSetting siteSetting, IItem item)
 {
     ItemsManager.UndoCheckOutItem(siteSetting, item, this.ConnectorExplorer.ConnectorExplorer);
 }
Beispiel #40
0
        /// <summary>
        /// Toggles Translucency for an item on or off
        /// </summary>
        /// <param name="xivMtrl">The XivMtrl containing the mtrl data</param>
        /// <param name="item">The item to toggle translucency for</param>
        /// <param name="translucencyEnabled">Flag determining if translucency is to be enabled or disabled</param>
        public void ToggleTranslucency(XivMtrl xivMtrl, IItem item, bool translucencyEnabled)
        {
            xivMtrl.ShaderNumber = !translucencyEnabled ? (short)0x0D : (short)0x1D;

            ImportMtrl(xivMtrl, item);
        }
Beispiel #41
0
        public void RenderItem(IItem item, System.Drawing.RectangleF rect)
        {
            var backroundTexture = Hud.Texture.GetItemBackgroundTexture(item);

            if (backroundTexture != null)
            {
                backroundTexture.Draw(rect.X, rect.Y, rect.Width, rect.Height);
            }

            var itemTexture = Hud.Texture.GetItemTexture(item.SnoItem);

            if (itemTexture == null)
            {
                return;
            }
            itemTexture.Draw(rect.X, rect.Y, rect.Width, rect.Height);

            var socketCount = item.SocketCount;

            if (socketCount > 0)
            {
                var socketTexture = Hud.Texture.EmptySocketTexture;
                var iw            = rect.Width * 0.45f;
                var ih            = iw;
                var ix            = rect.X + (rect.Width - iw) / 2.0f;
                var iy            = rect.Y + (rect.Height - ih) / 2.0f;
                switch (socketCount)
                {
                case 1:
                    socketTexture.Draw(ix, iy, iw, ih, 0.5f);
                    break;

                case 2:
                    socketTexture.Draw(ix, iy - ih * 0.5f, iw, ih, 0.5f);
                    socketTexture.Draw(ix, iy + ih * 0.5f, iw, ih, 0.5f);
                    break;

                case 3:
                    socketTexture.Draw(ix, iy - ih * 1.0f, iw, ih, 0.5f);
                    socketTexture.Draw(ix, iy, iw, ih, 0.5f);
                    socketTexture.Draw(ix, iy + ih * 1.0f, iw, ih, 0.5f);
                    break;
                }
                if ((item.ItemsInSocket != null) && (item.ItemsInSocket.Length > 0))
                {
                    for (int i = 0; i < item.ItemsInSocket.Length; i++)
                    {
                        var socketedItem = item.ItemsInSocket[i];
                        itemTexture = Hud.Texture.GetItemTexture(socketedItem.SnoItem);
                        if (itemTexture == null)
                        {
                            continue;
                        }
                        switch (socketCount)
                        {
                        case 1:
                            itemTexture.Draw(ix, iy, iw, ih, 0.5f);
                            break;

                        case 2:
                            if (i == 0)
                            {
                                itemTexture.Draw(ix, iy - ih * 0.5f, iw, ih, 0.5f);
                            }
                            else
                            {
                                itemTexture.Draw(ix, iy + ih * 0.5f, iw, ih, 0.5f);
                            }
                            break;

                        case 3:
                            if (i == 0)
                            {
                                itemTexture.Draw(ix, iy - ih * 1.0f, iw, ih, 0.5f);
                            }
                            else if (i == 1)
                            {
                                itemTexture.Draw(ix, iy, iw, ih, 0.5f);
                            }
                            else
                            {
                                itemTexture.Draw(ix, iy + ih * 1.0f, iw, ih, 0.5f);
                            }
                            break;
                        }
                    }
                }
            }

            if (item.Unidentified)
            {
                var unidTexture = Hud.Texture.UnidTexture;
                var uw          = rect.Width * 1.0f;
                var uh          = uw;
                unidTexture.Draw(rect.X + (rect.Width - uw) / 2, rect.Y + (rect.Height - uh) / 2, uw, uh, 1.0f);
            }

            var rv = 32.0f / 600.0f * Hud.Window.Size.Height;

            DrawItemQuantity(item, rect, rv);
        }
Beispiel #42
0
 public WithWingsItemDecorator(IItem original) : base(original)
 {
     PriceAdjustment = Random.Next(5, 15);
 }
 public bool ShouldItemBeCopiedCallback(IItem sourceItem, IItem destinationParentItem)
 {
     return(true);
 }
Beispiel #44
0
        public void AddLockedRoom(IItem key, string direction, IRoom room)
        {
            var lockedRoom = new KeyValuePair <string, IRoom>(direction, room);

            LockedExits.Add(key, lockedRoom);
        }
Beispiel #45
0
 /// <summary>
 /// the item increases the critical chance for a set amount of time
 /// </summary>
 /// <param name="item"></param>
 /// <param name="critBuff">amount of increased critical chance</param>
 /// <param name="duration">duration of the buff in minutes</param>
 public TimedCritBuff(IItem item, int critBuff, float duration) : base(item)
 {
     this.critBuff = critBuff;
     this.duration = duration;
     item.AddDescription("+" + critBuff + "% de critique pendant " + duration + " minute\n");
 }
Beispiel #46
0
        public static JToken Diff(this IItem item, IRecord record)
        {
            var differ = new JsonDiffPatch();

            return(differ.Diff(record.Data, item.Data));
        }
Beispiel #47
0
 public override SC_MenuItems GetItemMenuItems(ISiteSetting siteSetting, IItem item)
 {
     return(ItemsManager.GetItemMenuItems(siteSetting, item));
 }
 public void AddItem(IItem item)
 {
     this.inventory.AddCommonItem(item);
 }
Beispiel #49
0
 protected virtual void OnUseRequested(IItem e)
 {
     UseRequested?.Invoke(this, e);
 }
 public ItemLeftCommand(IItem gameObject)
 {
     item = gameObject;
 }
        /// <summary>
        /// Updates the various tab views with the information from the selected item.
        /// Locks the UI until those tab views come back and confirm they've been loaded.
        /// </summary>
        /// <param name="selectedItem">The selected item</param>
        private async void UpdateViews(IItem item)
        {
            if (item == null)
            {
                return;
            }

            if (ItemChanging != null)
            {
                ItemChanging.Invoke(this, null);
            }

            await LockUi();

            _modelLoaded        = false;
            _texturesLoaded     = false;
            _waitingForItemLoad = true;

            var textureView          = TextureTabItem.Content as TextureView;
            var textureViewModel     = textureView.DataContext as TextureViewModel;
            var sharedItemsView      = SharedItemsTab.Content as SharedItemsView;
            var sharedItemsViewModel = sharedItemsView.DataContext as SharedItemsViewModel;

            // This guy has no funny async callback.  It's ready once these awaits are done.
            await textureViewModel.UpdateTexture(item);

            var showSharedItems = await sharedItemsViewModel.SetItem(item, this);

            if (showSharedItems)
            {
                SharedItemsTab.IsEnabled  = true;
                SharedItemsTab.Visibility = Visibility.Visible;
            }
            else
            {
                if (SharedItemsTab.IsSelected)
                {
                    SharedItemsTab.IsSelected = false;
                    TextureTabItem.IsSelected = true;
                }
                SharedItemsTab.IsEnabled  = false;
                SharedItemsTab.Visibility = Visibility.Hidden;
            }


            if (item.PrimaryCategory.Equals(XivStrings.UI) ||
                item.SecondaryCategory.Equals(XivStrings.Face_Paint) ||
                item.SecondaryCategory.Equals(XivStrings.Equipment_Decals) ||
                item.SecondaryCategory.Equals(XivStrings.Paintings))
            {
                if (TabsControl.SelectedIndex == 1)
                {
                    TabsControl.SelectedIndex = 0;
                }

                // No model to load, just set us as already loaded.
                _modelLoaded = true;

                ModelTabItem.IsEnabled  = false;
                ModelTabItem.Visibility = Visibility.Hidden;
            }
            else
            {
                ModelTabItem.IsEnabled  = true;
                ModelTabItem.Visibility = Visibility.Visible;

                var modelView      = ModelTabItem.Content as ModelView;
                var modelViewModel = modelView.DataContext as ModelViewModel;

                await modelViewModel.UpdateModel(item as IItemModel);
            }
        }
Beispiel #52
0
 public ItemController(ILogger <ItemController> logger, IItem itemService)
 {
     _logger      = logger;
     _itemService = itemService;
 }
 /// <summary>
 /// Select an item in the tree view (and switch to that item)
 /// </summary>
 /// <param name="item"></param>
 public void SetSelectedItem(IItem item)
 {
     ItemSelect.SelectedItem = item;
 }
Beispiel #54
0
 public void MergeItem(IItem sourceItem)
 {
     throw new NotImplementedException();
 }
Beispiel #55
0
 public bool CanMergeWith(IItem sourceItem)
 {
     return(this.IsMergableCheck == null || this.IsMergableCheck(sourceItem));
 }
        public void CopyItemCallback(IItem sourceItem, IItem destinationParentItem, IItem destinationItem)
        {
            if (_PluginOptions[0].Value == "False")
            {
                return;
            }

            if (_MethodInfos == null || (_MethodInfos != null && _MethodInfos.Count == 0))
            {
                return;
            }

            //Looking for FieldValue-Conversion Methods
            for (int i = 1; i < _PluginOptions.Length; i++)
            {
                IPluginOption pluginOption = _PluginOptions[i];
                if (pluginOption.Type == PluginOptionTypes.CheckBox && !pluginOption.Value.Equals("False"))
                {
                    //Get the MethodInfo
                    MethodInfo currentMethod = _MethodInfos[pluginOption.Name];
                    if (currentMethod != null)
                    {
                        object[] arguments = new object[] { sourceItem, destinationParentItem, destinationItem };
                        bool     invoked   = (bool)currentMethod.Invoke(this, arguments); //Calling Custom Converter Plugin
                    }
                }
            }

            //If Item match our Template
            //if (!String.IsNullOrEmpty(templateName) && !String.IsNullOrEmpty(fieldName) && sourceItem.Template.Key == templateName.ToLower())
            //if (templateNames != null && templateNames.Length > 0 && !String.IsNullOrEmpty(fieldName) && templateNames.Contains<string>(sourceItem.Template.Key))
            //{
            //    //Get Field that matches our FieldName. FieldName is assumed unique.
            //    IField foundField = null;
            //    try
            //    {
            //        foundField = sourceItem.Fields.Last<IField>(currentField => (currentField.Key.Equals(fieldName.ToLower())));
            //    }
            //    catch { }

            //    if (foundField != null)
            //    {
            //        string inputFieldValue = foundField.Content;

            //        //Looking for FieldValue-Conversion Methods
            //        for (int i = 3; i < _PluginOptions.Length; i++)
            //        {
            //            IPluginOption pluginOption = _PluginOptions[i];
            //            if (pluginOption.Type == PluginOptionTypes.CheckBox && !pluginOption.Value.Equals("False"))
            //            {
            //                //Get the MethodInfo
            //                MethodInfo currentMethod = _MethodInfos[pluginOption.Name];
            //                if (currentMethod != null)
            //                {
            //                    object[] arguments = new object[] { inputFieldValue };
            //                    string convertedFieldValue = currentMethod.Invoke(this, arguments).ToString(); //Using conversion method to convert field

            //                    //Store the converted field into destination Field. FieldName is assumed unique.
            //                    IField destinationField = destinationItem.Fields.Last<IField>(currentField => (currentField.Key.Equals(fieldName.ToLower())));

            //                    if (destinationField != null)
            //                        destinationField.Content = convertedFieldValue;
            //                }
            //            }
            //        }
            //    }
            //}
        }
Beispiel #57
0
 public void AddItem(IItem item)
 {
     items.Add(item);
 }
 private void Folder_BeforeItemMove(IFolder src, IItem item, IFolder moveTo, ref bool cancel)
 {
     SuppressCore(src, item, moveTo, ref cancel);
 }
Beispiel #59
0
 public ItemsController(ILogger <ItemsController> logger, ICategory iCategory, IItem iItem)
 {
     _logger   = logger;
     _category = iCategory;
     _item     = iItem;
 }
 private void AnyContainerItemRemovedHandler(IItem item, byte slotid)
 {
     this.Refresh();
 }