Inheritance: System.Web.UI.Page
        public LoggingAspectTransformation(LoggingAspectWeaver aspectWeaver, ILoggingBackend backend)
            : base(aspectWeaver)
        {
            this.backend = backend;

            this.assets = aspectWeaver.Module.Cache.GetItem(() => new Assets(aspectWeaver.Module));
        }
        public void LoadAssets()
        {
            if (null != this.assets)
            {
                return;
            }

            this.assets = new Assets();
            this.assets.PlatformBottomSource = new BitmapImage(new Uri("Sprites\\Platform-Bottom.png", UriKind.Relative));
            this.assets.PlatformTopSource = new BitmapImage(new Uri("Sprites\\Platform-Top.png", UriKind.Relative));
            this.assets.PlatformInnerSource = new BitmapImage(new Uri("Sprites\\Platform-Inner.png", UriKind.Relative));
            this.assets.CharacterSource = new BitmapSource[30];

            int spriteWidth = 42;
            int spriteHeight = 51;

            System.Drawing.Rectangle croppedSource = new System.Drawing.Rectangle(0, 0, spriteWidth, spriteHeight);
            Bitmap source = System.Drawing.Image.FromFile("Sprites\\Character.png") as Bitmap;

            for (int row = 0; row < 5; row++)
            {
                for (int col = 0; col < 6; col++)
                {
                    croppedSource.X = col * spriteWidth;
                    croppedSource.Y = row * spriteHeight;
                    Bitmap target = new System.Drawing.Bitmap((int)croppedSource.Width, (int)croppedSource.Height);
                    Graphics.FromImage(target).DrawImage(source, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), croppedSource, GraphicsUnit.Pixel);
                    BitmapSource frame = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(target.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(target.Width, target.Height));
                    int index = row * 6 + col;
                    this.assets.CharacterSource[index] = frame;
                }
            }
        }
示例#3
0
        public override void createTower(Assets.Scripts.Engine.Towers.Tower t)
        {
            base.createTower(t);

            targetMinions = new Minion[MAX_LASER_COUNT];
            lineDrawers = new LineDrawer[MAX_LASER_COUNT];

            for (int i = 0; i < targetMinions.Length; i++)
            {
                GameObject lineHolder = new GameObject("line_"+i);
                lineHolder.transform.parent = towerObject.transform;

                LineRenderer fish = lineHolder.AddComponent<LineRenderer>();
                fish.material = new Material(rayMaterial);
                fish.SetWidth(0.02f, 0.02f);

                lineDrawers[i] = lineHolder.AddComponent<LineDrawer>();
                lineDrawers[i].line = fish;
                lineDrawers[i].visible = false;
                lineDrawers[i].transforms = new Vector3[] { tower.getWorldMissileCreatePosition(), Vector3.zero };

                lineDrawers[i].animationPeriod = 0.15f;
                lineDrawers[i].startColor = new Color(1f, 0f, 0f,0.36f);
                lineDrawers[i].endColor = new Color(0.39f, 0f, 0f, 0.7f);
                
            }
        }
示例#4
0
		public virtual void createMinion (Assets.Scripts.Engine.Minions.Minion minion)
		{
			this.minion = minion;
			minion.tag = this;
			minionObject = (GameObject)GameObject.Instantiate(childStaticMinionObject);
			minionObject.name = "m_" + minion.instanceId;
			
            healthBar = minionObject.transform.FindChild("HealthBar").gameObject.GetComponent<HealthBarDrawer>();
		    if (healthBar != null)
		    {
		        healthBar.health = (int) minion.stats.health;
		        healthBar.maxHealth = (int) minion.stats.healthTotal;
		    }


		    animations = (Animation[]) minionObject.GetComponentsInChildren<Animation>();
            foreach (Animation animation in animations)
                if(animation["walk"] != null)
			        animation["walk"].speed = minion.stats.baseMovementSpeed * walkAnimationSpeedMultiplier();

			rangeProjector = (Projector)GameObject.Instantiate(childStaticRangeProjector);
			rangeProjector.transform.parent = minionObject.transform;
			rangeProjector.transform.localPosition = new Vector3(0, 0.2f, 0);
			rangeProjector.orthographicSize = 0.2f;
			rangeProjector.enabled = false;

		    soundPlayer = minionObject.AddComponent<AudioSource>();
		    soundPlayer.volume = 2;
            soundPlayer.rolloffMode = AudioRolloffMode.Linear;
		    if (spawnSound == null)
		        spawnSound = Resources.Load<AudioClip>("Sound/minion_spawn");
		    soundPlayer.clip = spawnSound;
            soundPlayer.Play();
		}
示例#5
0
        private void AddAsset(Assets.Asset asset)
        {
            var item = new ListViewItem(asset.Name);
            item.Tag = asset;

            lvAssets.Items.Add(item);
        }
示例#6
0
文件: Enemy.cs 项目: nightwolfz/Game1
 public void Init(Assets.Enemy enemy)
 {
     Health = enemy.Health;
     Shield = enemy.Shield;
     Credits = Health;
     ColorId = enemy.ColorId;
     _shootDelay = enemy.ShootDelay + (Random.Range(0, enemy.ShootDelay*2)); // Make enemies shoot a bit differently
 }
 void SetInstance()
 {
     if(Instance == null) {
         Instance = this;
     } else {
         Debug.LogError("Creation of a second assets instance was attempted. It will be destroyed.");
         Destroy (this);
     }
 }
 public Entity ReplaceAsteroid(Assets.Entitasteroids.Scripts.Sources.Features.Asteroid.AsteroidSize newSize) {
     var previousComponent = hasAsteroid ? asteroid : null;
     var component = _asteroidComponentPool.Count > 0 ? _asteroidComponentPool.Pop() : new Assets.Entitasteroids.Scripts.Sources.Features.Asteroid.AsteroidComponent();
     component.size = newSize;
     ReplaceComponent(ComponentIds.Asteroid, component);
     if (previousComponent != null) {
         _asteroidComponentPool.Push(previousComponent);
     }
     return this;
 }
 public HistogramDistanceTracker(
     string path, 
     Assets.VirtualProfiler.GlobalConfiguration config, 
     Transform targetA, 
     Transform targetB)
     : base(path, config, new Color(0, 1, 0, 1))
 {
     _targetA = targetA;
     _targetB = targetB;
     HistogramRenderer.FilePrefix = "DISTANCE";
 }
 public Entity ReplaceMood(Assets.Sources.GameLogic.Mood.Mood newMood)
 {
     var previousComponent = hasMood ? mood : null;
     var component = _moodComponentPool.Count > 0 ? _moodComponentPool.Pop() : new Assets.Sources.GameLogic.Mood.MoodComponent();
     component.Mood = newMood;
     ReplaceComponent(ComponentIds.Mood, component);
     if (previousComponent != null) {
         _moodComponentPool.Push(previousComponent);
     }
     return this;
 }
        public HistogramRenderer(string path, Assets.VirtualProfiler.GlobalConfiguration config, Color color)
        {
            _color = color;
            _config = config;
            _path = path + "/Histograms";
            if (!Directory.Exists (_path)) {
                Directory.CreateDirectory (_path);
            }

            CreateBuffer ();
        }
 public Entity ReplaceGameEventState(Assets.Sources.GameLogic.Components.EventState newEventState)
 {
     var previousComponent = hasGameEventState ? gameEventState : null;
     var component = _gameEventStateComponentPool.Count > 0 ? _gameEventStateComponentPool.Pop() : new Assets.Sources.GameLogic.Components.GameEventStateComponent();
     component.EventState = newEventState;
     ReplaceComponent(ComponentIds.GameEventState, component);
     if (previousComponent != null) {
         _gameEventStateComponentPool.Push(previousComponent);
     }
     return this;
 }
 public HistogramOrientationTracker(
     string path,
     Assets.VirtualProfiler.GlobalConfiguration config,
     Transform targetA, 
     Transform targetB)
     : base(path, config, new Color(0, 0, 1, 1))
 {
     _targetA = targetA;
     _targetB = targetB;
     HistogramRenderer.FilePrefix = "ORIENTATION";
 }
示例#14
0
        public SegmentoPrimario(UnityEngine.GameObject puntoInterno, UnityEngine.GameObject puntoExterno, Plano planosMovimiento, Assets.ArticulacionType articulacion)
        {
            // TODO: Complete member initialization
         
            this.hombro = puntoInterno;
            this.codo = puntoExterno;
            this.planosMovimiento = planosMovimiento;
            base.articulacion = articulacion;

            Update();
        }
 protected object GetBOAssets(bool update = false)
 {
     IBusinessObjects BOAssets = (IBusinessObjects)this.Session["Assets"];
     if (BOAssets == null || !(BOAssets is Assets) || update)
     {
         Session["Assets"] = null;
         BOAssets = (IBusinessObjects)Assets.GetAssets();
         this.Session["Assets"] = BOAssets;
     }
     if (BOAssets == null || BOAssets.Count == 0)
         BOAssets = new Assets();
     return BOAssets;
 }
示例#16
0
        internal static IEnumerable<TextureFrame> LoadAtals(Assets assets, string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new ArgumentNullException(nameof(fileName));

            var ext = Path.GetExtension(fileName).ToUpper();

            AtlasLoader loader;
            if (!_loaders.TryGetValue(ext, out loader))
                throw new Exception($"Loader for extension {ext} not registered");

            var texture = assets.LoadTexture2D(Path.GetFileNameWithoutExtension(fileName));
            var atalsData = assets.LoadText(fileName);
            return loader.LoadAtals(texture, atalsData);
        }
示例#17
0
    public void LoadHorizontal(Assets.Scripts.PerspectiveInitializer.ThemeState themeState)
    {
        transform.localPosition = new Vector3(-5.4f, 2.76f, 0.5f);
        transform.localRotation = Quaternion.Euler(0, 0, 0);
        transform.localScale = new Vector3(0.75f, 0.75f, 1);

        if (themeState == Assets.Scripts.PerspectiveInitializer.ThemeState.Mine)
        {
            GetComponent<Animator>().runtimeAnimatorController = dragon;
            pointLightColor = new Color(188, 85, 41, 255);
        }
        else
        {
            GetComponent<Animator>().runtimeAnimatorController = dragonIce;
            pointLightColor = new Color(41, 85, 188, 255);
        }
    }
示例#18
0
    public void LoadVertical(Assets.Scripts.PerspectiveInitializer.ThemeState themeState)
    {
        transform.localPosition = new Vector3(5.50f, 3.12f, 0.5f);
        transform.localRotation = Quaternion.Euler(0, 0, 270);
        transform.localScale = new Vector3(1, 1, 1);

        if (themeState == Assets.Scripts.PerspectiveInitializer.ThemeState.Mine)
        {
            GetComponent<Animator>().runtimeAnimatorController = dragon2;
            pointLightColor = new Color(188, 85, 41, 255);
        }
        else
        {
            GetComponent<Animator>().runtimeAnimatorController = dragon2Ice;
            pointLightColor = new Color(41, 85, 188, 255);
        }
    }
示例#19
0
文件: Program.cs 项目: tilpner/hp
        static void Main(string[] args)
        {
            Log.GlobalLevel = Log.Level.Debug;

            RenderWindow app = new RenderWindow(new VideoMode(800, 600), "HP!",
                Styles.Default, new ContextSettings(0, 0, 4));
            app.SetFramerateLimit(60);
            app.Closed += delegate { app.Close(); };
            app.SetVisible(true);
            app.SetActive(true);

            L.I("Assuming assets in \"assets\"");
            Assets assets = new Assets("assets");
            LoadAnimations(assets);

            Level level1 = assets.Level("level1.json");
            Game game = new Game(assets, level1);
            var view = new View();

            int lastFrameTime = Environment.TickCount;
            while (app.IsOpen) {
                app.DispatchEvents();

                float aspect = (float)app.Size.X / app.Size.Y;
                float targetWidth = 20, targetHeight = targetWidth / aspect;
                view.Reset(new FloatRect(0, 0, targetWidth, targetHeight));
                app.SetView(view);

                int ticks = Environment.TickCount;
                float delta = (ticks - lastFrameTime) / 1000F;
                lastFrameTime = ticks;

                game.Update(delta);
                game.Render(app);

                app.Display();
            }
        }
示例#20
0
        public Example()
        {
            InactiveMode = UpdateMode.Draw;
            ClearColor   = new Color(100, 149, 237);

            // Create our player and add it to the state
            player = new Player(new Vector2f(100, 100));
            Entities.Add(player);

            var random = new Random();

            const int width  = 100;
            const int height = 100;

            // Initialize the state's tilemap
            Map = new ChunkedTileMap(width, height, Assets.LoadTexture("Tiles.png"), 8);

            // Fill the TileMap with random tiles
            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    if (y == 0 || x == 0 || x == width - 1 || y == height - 1)
                    {
                        // Border tiles so the player can't accidentally leave the map
                        Map[x, y] = new Tile(0, true);
                    }
                    else if (x > 20 || y > 20)
                    {
                        // Leave an empty start region so the player doesn't get stuck
                        var tile = (ushort)(1 + random.Next(3));

                        // 20% chance of a tile being non-air, if the tile is red (zero), we give it
                        // a non-null userdata which will make it jumpthrough in this example
                        if (random.NextDouble() > 0.8)
                        {
                            Map[x, y] = new Tile(tile, true, tile == 1 ? (object)1 : null);
                        }
                    }
                }
            }

            // Create a bunch of ramdom coins around the map
            for (var i = 0; i < 500; i++)
            {
                Entities.Add(new Coin(random.Next(width * 8), random.Next(height * 8)));
            }

            // Pressing LMB will erase the tile that was clicked
            Input.MouseButton[Mouse.Button.Left] = args =>
            {
                if (!args.Pressed)
                {
                    return(true);
                }

                var x = (int)args.Position.X / 8;
                var y = (int)args.Position.Y / 8;

                if (x >= 0 && x < Map.Width && y >= 0 && y < Map.Height)
                {
                    Map[x, y] = new Tile(500, false);
                }

                // Tile 500 does not exist on the tile atlas and will render nothing

                return(true);
            };

            Input.Key[Keyboard.Key.Space] = args =>
            {
                if (!args.Pressed)
                {
                    return(true);
                }

                Game.PushState(new Pause());
                return(true);
            };
        }
 public AbstractHistogramTracker(string path, Assets.VirtualProfiler.GlobalConfiguration config, Color color)
 {
     _config = config;
     _histogramRenderer = new HistogramRenderer (path, config, color);
 }
示例#22
0
 internal bool RemoveItem(TradeAsset asset)
 {
     return(Assets.Contains(asset) && Assets.Remove(asset));
 }
        public Entity ReplaceGameState(Assets.Sources.GameLogic.Meta.GameState newGameState)
        {
            var entity = gameStateEntity;
            if (entity == null) {
                entity = SetGameState(newGameState);
            } else {
                entity.ReplaceGameState(newGameState);
            }

            return entity;
        }
示例#24
0
        public void AddPage(string html, string webRoot, string pagePath)
        {
            this.htmlPage = html;
            this.webRoot  = webRoot;
            //this.pagePath = pagePath;

            var parser = new AngleSharp.Parser.Html.HtmlParser();
            var doc    = parser.Parse(html);
            var images = doc.Images
                         .Where(x => x.HasAttribute("src"));
            var styles = doc.GetElementsByTagName("link")
                         .Where(l => l.Attributes["rel"].Value.Trim().ToLower() == "stylesheet")
                         .Where(c => c.HasAttribute("href"));
            var scripts = doc.GetElementsByTagName("script")
                          .Where(x => x.HasAttribute("src"));

            Assets.AddSerializedAssets(images, "src");
            Assets.AddSerializedAssets(scripts, "src");
            StyleAssets.AddSerializedAssets(styles, "href");

            var newHtml = doc.ToHtml(new HtmlMarkupFormatter());
            var entry   = zipArchive.CreateEntry("index.html", CompressionLevel.Fastest);

            using (StreamWriter writer = new StreamWriter(entry.Open()))
            {
                try
                {
                    writer.Write(newHtml);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            foreach (var serialStyle in this.StyleAssets.Assets)
            {
                //if (!serialStyle.Zipped)
                {
                    var style =
                        Zipper.GetStringAsset(serialStyle.OriginalPath, mapPathResolver, webRoot, pagePath);
                    if (!string.IsNullOrEmpty(style))
                    {
                        //var sentry = zipArchive.CreateEntry(serialStyle.Value, CompressionLevel.Fastest);
                        //using (StreamWriter writer = new StreamWriter(sentry.Open()))
                        //{
                        //    writer.Write(style);
                        //}
                        //doneAssets.Add(serialStyle.Value);
                    }
                }
            }
            //foreach (var serialAsset in serialAssets)
            //{
            //    if (!doneAssets.Contains(serialAsset.Value))
            //    {
            //        zipArchive.AddBinaryAssetToArchive(
            //            serialAsset.Value, serialAsset.Key, mapPathResolver, webRoot, pagePath);
            //        doneAssets.Add(serialAsset.Value);
            //    }
            //}
        }
示例#25
0
        /// <summary>
        /// 更新资产信息
        /// </summary>
        /// <param name="entity">资产信息</param>
        /// <returns></returns>
        public ReturnInfo UpdateAssets(AssetsInputDto entity)
        {
            ReturnInfo    RInfo = new ReturnInfo();
            StringBuilder sb    = new StringBuilder();
            //产生资产编号
            string ValidateInfo = Helper.BasicValidate(entity).ToString();

            sb.Append(ValidateInfo);
            if (sb.Length == 0)
            {
                try
                {
                    Assets assets = _AssetsRepository.GetByID(entity.AssId).FirstOrDefault();
                    if (assets != null)
                    {
                        assets.BUYDATE       = entity.BuyDate;
                        assets.CREATEUSER    = entity.CreateUser;
                        assets.DEPARTMENTID  = entity.DepartmentId;
                        assets.EXPIRYDATE    = entity.ExpiryDate;
                        assets.IMAGE         = entity.Image;
                        assets.LOCATIONID    = entity.LocationId;
                        assets.MODIFYUSER    = entity.ModifyUser;
                        assets.NAME          = entity.Name;
                        assets.NOTE          = entity.Note;
                        assets.PLACE         = entity.Place;
                        assets.PRICE         = entity.Price;
                        assets.SN            = entity.SN;
                        assets.SPECIFICATION = entity.Specification;
                        assets.TYPEID        = entity.TypeId;
                        assets.UNIT          = entity.Unit;
                        assets.VENDOR        = entity.Vendor;
                        assets.MODIFYDATE    = DateTime.Now;
                        assets.CREATEDATE    = assets.CREATEDATE;
                        _unitOfWork.RegisterDirty(assets);
                    }

                    var pr = new AssProcessRecord
                    {
                        ASSID          = entity.AssId,
                        CREATEDATE     = DateTime.Now,
                        CREATEUSER     = entity.CreateUser,
                        HANDLEDATE     = DateTime.Now,
                        HANDLEMAN      = entity.CreateUser,
                        MODIFYDATE     = DateTime.Now,
                        MODIFYUSER     = entity.ModifyUser,
                        PROCESSCONTENT = entity.CreateUser + "修改了" + entity.AssId
                    };
                    ;
                    pr.PROCESSMODE = (int)PROCESSMODE.修改内容;
                    _unitOfWork.RegisterNew(pr);

                    bool result = _unitOfWork.Commit();
                    RInfo.IsSuccess = result;
                    RInfo.ErrorInfo = sb.ToString();
                    return(RInfo);
                }
                catch (Exception ex)
                {
                    _unitOfWork.Rollback();
                    sb.Append(ex.Message);
                    RInfo.IsSuccess = false;
                    RInfo.ErrorInfo = sb.ToString();
                    return(RInfo);
                }
            }
            else
            {
                RInfo.IsSuccess = false;
                RInfo.ErrorInfo = sb.ToString();
                return(RInfo);
            }
        }
示例#26
0
            public override void InitializeStates(out BaseState defaultState)
            {
                serializable = true;
                defaultState = Alive;

                var dead    = CREATURES.STATUSITEMS.DEAD.NAME;
                var tooltip = CREATURES.STATUSITEMS.DEAD.TOOLTIP;
                var main    = Db.Get().StatusItemCategories.Main;

                Dead
                .ToggleStatusItem(dead, tooltip, string.Empty, StatusItem.IconType.Info, 0, false, OverlayModes.None.ID, 0, category: main)
                .Enter(smi =>
                {
                    if (smi.master.rm.Replanted && !smi.master.GetComponent <KPrefabID>().HasTag(GameTags.Uprooted))
                    {
                        smi.master.gameObject.AddOrGet <Notifier>().Add(smi.master.CreateDeathNotification());
                    }

                    GameUtil.KInstantiate(Assets.GetPrefab(EffectConfigs.PlantDeathId), smi.master.transform.GetPosition(), Grid.SceneLayer.FXFront).SetActive(true);
                    if (smi.master.harvestable != null && smi.master.harvestable.CanBeHarvested && GameScheduler.Instance != null)
                    {
                        GameScheduler.Instance.Schedule("SpawnFruit", 0.2f, smi.master.crop.SpawnFruit);
                    }

                    smi.master.Trigger((int)GameHashes.Died);
                    smi.master.GetComponent <KBatchedAnimController>().StopAndClear();
                    Destroy(smi.master.GetComponent <KBatchedAnimController>());
                    smi.Schedule(0.5f, smi.master.DestroySelf);
                });
                Alive
                .InitializeStates(masterTarget, Dead)
                .DefaultState(Alive.Idle)
                .ToggleComponent <Growing>();

                Alive.Idle
                .Enter(smi => smi.master.elementConsumer.EnableConsumption(true))
                .EventTransition(GameHashes.Wilt, Alive.WiltingPre, smi => smi.master.wiltCondition.IsWilting())
                .EventTransition(GameHashes.Grow, Alive.PreFruiting, smi => smi.master.growing.ReachedNextHarvest())
                .PlayAnim(AnimSet.grow, KAnim.PlayMode.Loop)
                .Exit(smi => smi.master.elementConsumer.EnableConsumption(false));

                Alive.PreFruiting
                .PlayAnim("grow", KAnim.PlayMode.Once)
                .EventTransition(GameHashes.AnimQueueComplete, Alive.Fruiting);

                Alive.FruitingLost
                .Enter(smi => smi.master.harvestable.SetCanBeHarvested(false))
                .GoTo(Alive.Idle);

                Alive.Wilting
                .PlayAnim(AnimSet.wilt1, KAnim.PlayMode.Loop)
                .EventTransition(GameHashes.WiltRecover, Alive.WiltingPst, smi => !smi.master.wiltCondition.IsWilting())
                .EventTransition(GameHashes.Harvest, Alive.Harvest);
                Alive.WiltingPst
                .PlayAnim(AnimSet.wilt1, KAnim.PlayMode.Once)
                .OnAnimQueueComplete(Alive.Idle);

                Alive.Fruiting
                .DefaultState(Alive.Fruiting.FruitingIdle)
                .EventTransition(GameHashes.Wilt, Alive.WiltingPre)
                .EventTransition(GameHashes.Harvest, Alive.Harvest)
                .EventTransition(GameHashes.Grow, Alive.FruitingLost, smi => !smi.master.growing.ReachedNextHarvest());

                Alive.Fruiting.FruitingIdle
                .PlayAnim(AnimSet.idle_full, KAnim.PlayMode.Loop)
                .Enter(smi => smi.master.harvestable.SetCanBeHarvested(true))
                .Enter(smi => smi.master.elementConsumer.EnableConsumption(true))
                .Enter(smi => smi.master.elementEmitter.SetEmitting(true))
                .Update("fruiting_idle", (smi, dt) =>
                {
                    if (!smi.IsOld())
                    {
                        return;
                    }
                    smi.GoTo(Alive.Fruiting.FruitingOld);
                }, UpdateRate.SIM_4000ms)
                .Exit(smi => smi.master.elementEmitter.SetEmitting(false))
                .Exit(smi => smi.master.elementConsumer.EnableConsumption(false));

                Alive.Fruiting.FruitingOld
                .PlayAnim(AnimSet.wilt1, KAnim.PlayMode.Loop)
                .Enter(smi => smi.master.harvestable.SetCanBeHarvested(true))
                .Update("fruiting_old", (smi, dt) =>
                {
                    if (smi.IsOld())
                    {
                        return;
                    }
                    smi.GoTo(Alive.Fruiting.FruitingIdle);
                }, UpdateRate.SIM_4000ms);

                Alive.Harvest
                .PlayAnim(AnimSet.harvest, KAnim.PlayMode.Once)
                .Enter(smi =>
                {
                    if (GameScheduler.Instance == null || smi.master == null)
                    {
                        return;
                    }

                    GameScheduler.Instance.Schedule("SpawnFruit", 0.2f, smi.master.crop.SpawnFruit);
                    smi.master.harvestable.SetCanBeHarvested(false);
                })
                .OnAnimQueueComplete(Alive.Idle);
            }
示例#27
0
 // Token: 0x060018F4 RID: 6388 RVA: 0x0008BC48 File Offset: 0x0008A048
 public void updateAttachments(byte[] state, bool viewmodel)
 {
     if (state == null || state.Length != 18)
     {
         return;
     }
     base.transform.localScale = Vector3.one;
     this._sightID             = BitConverter.ToUInt16(state, 0);
     this._tacticalID          = BitConverter.ToUInt16(state, 2);
     this._gripID     = BitConverter.ToUInt16(state, 4);
     this._barrelID   = BitConverter.ToUInt16(state, 6);
     this._magazineID = BitConverter.ToUInt16(state, 8);
     if (this.sightModel != null)
     {
         UnityEngine.Object.Destroy(this.sightModel.gameObject);
         this._sightModel = null;
     }
     try
     {
         this._sightAsset = (ItemSightAsset)Assets.find(EAssetType.ITEM, this.sightID);
     }
     catch
     {
         this._sightAsset = null;
     }
     this.tempSightMaterial = null;
     if (this.sightAsset != null && this.sightHook != null)
     {
         this._sightModel                        = UnityEngine.Object.Instantiate <GameObject>(this.sightAsset.sight).transform;
         this.sightModel.name                    = "Sight";
         this.sightModel.transform.parent        = this.sightHook;
         this.sightModel.transform.localPosition = Vector3.zero;
         this.sightModel.transform.localRotation = Quaternion.identity;
         this.sightModel.localScale              = Vector3.one;
         if (viewmodel)
         {
             Layerer.viewmodel(this.sightModel);
         }
         if (this.gunAsset != null && this.skinAsset != null && this.skinAsset.secondarySkins != null)
         {
             Material material = null;
             if (!this.skinAsset.secondarySkins.TryGetValue(this.sightID, out material) && this.skinAsset.hasSight && this.sightAsset.isPaintable)
             {
                 if (this.sightAsset.albedoBase != null && this.skinAsset.attachmentSkin != null)
                 {
                     material = UnityEngine.Object.Instantiate <Material>(this.skinAsset.attachmentSkin);
                     material.SetTexture("_AlbedoBase", this.sightAsset.albedoBase);
                     material.SetTexture("_MetallicBase", this.sightAsset.metallicBase);
                     material.SetTexture("_EmissionBase", this.sightAsset.emissionBase);
                 }
                 else if (this.skinAsset.tertiarySkin != null)
                 {
                     material = this.skinAsset.tertiarySkin;
                 }
             }
             if (material != null)
             {
                 HighlighterTool.rematerialize(this.sightModel, material, out this.tempSightMaterial);
             }
         }
     }
     if (this.tacticalModel != null)
     {
         UnityEngine.Object.Destroy(this.tacticalModel.gameObject);
         this._tacticalModel = null;
     }
     try
     {
         this._tacticalAsset = (ItemTacticalAsset)Assets.find(EAssetType.ITEM, this.tacticalID);
     }
     catch
     {
         this._tacticalAsset = null;
     }
     this.tempTacticalMaterial = null;
     if (this.tacticalAsset != null && this.tacticalHook != null)
     {
         this._tacticalModel                        = UnityEngine.Object.Instantiate <GameObject>(this.tacticalAsset.tactical).transform;
         this.tacticalModel.name                    = "Tactical";
         this.tacticalModel.transform.parent        = this.tacticalHook;
         this.tacticalModel.transform.localPosition = Vector3.zero;
         this.tacticalModel.transform.localRotation = Quaternion.identity;
         this.tacticalModel.localScale              = Vector3.one;
         if (viewmodel)
         {
             Layerer.viewmodel(this.tacticalModel);
         }
         if (this.gunAsset != null && this.skinAsset != null && this.skinAsset.secondarySkins != null)
         {
             Material material2 = null;
             if (!this.skinAsset.secondarySkins.TryGetValue(this.tacticalID, out material2) && this.skinAsset.hasTactical && this.tacticalAsset.isPaintable)
             {
                 if (this.tacticalAsset.albedoBase != null && this.skinAsset.attachmentSkin != null)
                 {
                     material2 = UnityEngine.Object.Instantiate <Material>(this.skinAsset.attachmentSkin);
                     material2.SetTexture("_AlbedoBase", this.tacticalAsset.albedoBase);
                     material2.SetTexture("_MetallicBase", this.tacticalAsset.metallicBase);
                     material2.SetTexture("_EmissionBase", this.tacticalAsset.emissionBase);
                 }
                 else if (this.skinAsset.tertiarySkin != null)
                 {
                     material2 = this.skinAsset.tertiarySkin;
                 }
             }
             if (material2 != null)
             {
                 HighlighterTool.rematerialize(this.tacticalModel, material2, out this.tempTacticalMaterial);
             }
         }
     }
     if (this.gripModel != null)
     {
         UnityEngine.Object.Destroy(this.gripModel.gameObject);
         this._gripModel = null;
     }
     try
     {
         this._gripAsset = (ItemGripAsset)Assets.find(EAssetType.ITEM, this.gripID);
     }
     catch
     {
         this._gripAsset = null;
     }
     this.tempGripMaterial = null;
     if (this.gripAsset != null && this.gripHook != null)
     {
         this._gripModel                        = UnityEngine.Object.Instantiate <GameObject>(this.gripAsset.grip).transform;
         this.gripModel.name                    = "Grip";
         this.gripModel.transform.parent        = this.gripHook;
         this.gripModel.transform.localPosition = Vector3.zero;
         this.gripModel.transform.localRotation = Quaternion.identity;
         this.gripModel.localScale              = Vector3.one;
         if (viewmodel)
         {
             Layerer.viewmodel(this.gripModel);
         }
         if (this.gunAsset != null && this.skinAsset != null && this.skinAsset.secondarySkins != null)
         {
             Material material3 = null;
             if (!this.skinAsset.secondarySkins.TryGetValue(this.gripID, out material3) && this.skinAsset.hasGrip && this.gripAsset.isPaintable)
             {
                 if (this.gripAsset.albedoBase != null && this.skinAsset.attachmentSkin != null)
                 {
                     material3 = UnityEngine.Object.Instantiate <Material>(this.skinAsset.attachmentSkin);
                     material3.SetTexture("_AlbedoBase", this.gripAsset.albedoBase);
                     material3.SetTexture("_MetallicBase", this.gripAsset.metallicBase);
                     material3.SetTexture("_EmissionBase", this.gripAsset.emissionBase);
                 }
                 else if (this.skinAsset.tertiarySkin != null)
                 {
                     material3 = this.skinAsset.tertiarySkin;
                 }
             }
             if (material3 != null)
             {
                 HighlighterTool.rematerialize(this.gripModel, material3, out this.tempGripMaterial);
             }
         }
     }
     if (this.barrelModel != null)
     {
         UnityEngine.Object.Destroy(this.barrelModel.gameObject);
         this._barrelModel = null;
     }
     try
     {
         this._barrelAsset = (ItemBarrelAsset)Assets.find(EAssetType.ITEM, this.barrelID);
     }
     catch
     {
         this._barrelAsset = null;
     }
     this.tempBarrelMaterial = null;
     if (this.barrelAsset != null && this.barrelHook != null)
     {
         this._barrelModel                        = UnityEngine.Object.Instantiate <GameObject>(this.barrelAsset.barrel).transform;
         this.barrelModel.name                    = "Barrel";
         this.barrelModel.transform.parent        = this.barrelHook;
         this.barrelModel.transform.localPosition = Vector3.zero;
         this.barrelModel.transform.localRotation = Quaternion.identity;
         this.barrelModel.localScale              = Vector3.one;
         if (viewmodel)
         {
             Layerer.viewmodel(this.barrelModel);
         }
         if (this.gunAsset != null && this.skinAsset != null && this.skinAsset.secondarySkins != null)
         {
             Material material4 = null;
             if (!this.skinAsset.secondarySkins.TryGetValue(this.barrelID, out material4) && this.skinAsset.hasBarrel && this.barrelAsset.isPaintable)
             {
                 if (this.barrelAsset.albedoBase != null && this.skinAsset.attachmentSkin != null)
                 {
                     material4 = UnityEngine.Object.Instantiate <Material>(this.skinAsset.attachmentSkin);
                     material4.SetTexture("_AlbedoBase", this.barrelAsset.albedoBase);
                     material4.SetTexture("_MetallicBase", this.barrelAsset.metallicBase);
                     material4.SetTexture("_EmissionBase", this.barrelAsset.emissionBase);
                 }
                 else if (this.skinAsset.tertiarySkin != null)
                 {
                     material4 = this.skinAsset.tertiarySkin;
                 }
             }
             if (material4 != null)
             {
                 HighlighterTool.rematerialize(this.barrelModel, material4, out this.tempBarrelMaterial);
             }
         }
     }
     if (this.magazineModel != null)
     {
         UnityEngine.Object.Destroy(this.magazineModel.gameObject);
         this._magazineModel = null;
     }
     try
     {
         this._magazineAsset = (ItemMagazineAsset)Assets.find(EAssetType.ITEM, this.magazineID);
     }
     catch
     {
         this._magazineAsset = null;
     }
     this.tempMagazineMaterial = null;
     if (this.magazineAsset != null && this.magazineHook != null)
     {
         Transform transform = null;
         if (this.magazineAsset.calibers.Length > 0)
         {
             transform = this.magazineHook.FindChild("Caliber_" + this.magazineAsset.calibers[0]);
         }
         if (transform == null)
         {
             transform = this.magazineHook;
         }
         this._magazineModel                        = UnityEngine.Object.Instantiate <GameObject>(this.magazineAsset.magazine).transform;
         this.magazineModel.name                    = "Magazine";
         this.magazineModel.transform.parent        = transform;
         this.magazineModel.transform.localPosition = Vector3.zero;
         this.magazineModel.transform.localRotation = Quaternion.identity;
         this.magazineModel.localScale              = Vector3.one;
         if (viewmodel)
         {
             Layerer.viewmodel(this.magazineModel);
         }
         if (this.gunAsset != null && this.skinAsset != null && this.skinAsset.secondarySkins != null)
         {
             Material material5 = null;
             if (!this.skinAsset.secondarySkins.TryGetValue(this.magazineID, out material5) && this.skinAsset.hasMagazine && this.magazineAsset.isPaintable)
             {
                 if (this.magazineAsset.albedoBase != null && this.skinAsset.attachmentSkin != null)
                 {
                     material5 = UnityEngine.Object.Instantiate <Material>(this.skinAsset.attachmentSkin);
                     material5.SetTexture("_AlbedoBase", this.magazineAsset.albedoBase);
                     material5.SetTexture("_MetallicBase", this.magazineAsset.metallicBase);
                     material5.SetTexture("_EmissionBase", this.magazineAsset.emissionBase);
                 }
                 else if (this.skinAsset.tertiarySkin != null)
                 {
                     material5 = this.skinAsset.tertiarySkin;
                 }
             }
             if (material5 != null)
             {
                 HighlighterTool.rematerialize(this.magazineModel, material5, out this.tempMagazineMaterial);
             }
         }
     }
     if (this.tacticalModel != null && this.tacticalModel.childCount > 0)
     {
         this._lightHook  = this.tacticalModel.transform.FindChild("Model_0").FindChild("Light");
         this._light2Hook = this.tacticalModel.transform.FindChild("Model_0").FindChild("Light2");
         if (viewmodel)
         {
             if (this.lightHook != null)
             {
                 this.lightHook.tag = "Viewmodel";
                 this.lightHook.gameObject.layer = LayerMasks.VIEWMODEL;
                 Transform transform2 = this.lightHook.FindChild("Light");
                 if (transform2 != null)
                 {
                     transform2.tag = "Viewmodel";
                     transform2.gameObject.layer = LayerMasks.VIEWMODEL;
                 }
             }
             if (this.light2Hook != null)
             {
                 this.light2Hook.tag = "Viewmodel";
                 this.light2Hook.gameObject.layer = LayerMasks.VIEWMODEL;
                 Transform transform3 = this.light2Hook.FindChild("Light");
                 if (transform3 != null)
                 {
                     transform3.tag = "Viewmodel";
                     transform3.gameObject.layer = LayerMasks.VIEWMODEL;
                 }
             }
         }
         else
         {
             LightLODTool.applyLightLOD(this.lightHook);
             LightLODTool.applyLightLOD(this.light2Hook);
         }
     }
     else
     {
         this._lightHook  = null;
         this._light2Hook = null;
     }
     if (this.sightModel != null)
     {
         this._aimHook = this.sightModel.transform.FindChild("Model_0").FindChild("Aim");
         if (this.aimHook != null)
         {
             Transform transform4 = this.aimHook.parent.FindChild("Reticule");
             if (transform4 != null)
             {
                 Renderer component = transform4.GetComponent <Renderer>();
                 Material material6 = component.material;
                 material6.SetColor("_Color", OptionsSettings.criticalHitmarkerColor);
                 material6.SetColor("_EmissionColor", OptionsSettings.criticalHitmarkerColor);
             }
         }
         this._reticuleHook = this.sightModel.transform.FindChild("Model_0").FindChild("Reticule");
     }
     else
     {
         this._aimHook      = null;
         this._reticuleHook = null;
     }
     if (this.aimHook != null)
     {
         this._scopeHook = this.aimHook.FindChild("Scope");
     }
     else
     {
         this._scopeHook = null;
     }
     if (this.rope != null && viewmodel)
     {
         this.rope.tag = "Viewmodel";
         this.rope.gameObject.layer = LayerMasks.VIEWMODEL;
     }
     this.wasSkinned = true;
     this.applyVisual();
 }
        public dataModel.Item[] GetItemByIds(string[] itemIds, coreModel.ItemResponseGroup respGroup = coreModel.ItemResponseGroup.ItemLarge)
        {
            if (itemIds == null)
            {
                throw new ArgumentNullException("itemIds");
            }

            if (!itemIds.Any())
            {
                return(new dataModel.Item[] { });
            }

            // Use breaking query EF performance concept https://msdn.microsoft.com/en-us/data/hh949853.aspx#8
            var retVal         = Items.Include(x => x.Images).Where(x => itemIds.Contains(x.Id)).ToArray();
            var propertyValues = PropertyValues.Where(x => itemIds.Contains(x.ItemId)).ToArray();

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.Outlines))
            {
                respGroup |= coreModel.ItemResponseGroup.Links;
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.Links))
            {
                var relations = CategoryItemRelations.Where(x => itemIds.Contains(x.ItemId)).ToArray();
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemAssets))
            {
                var assets = Assets.Where(x => itemIds.Contains(x.ItemId)).ToArray();
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemEditorialReviews))
            {
                var editorialReviews = EditorialReviews.Where(x => itemIds.Contains(x.ItemId)).ToArray();
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.Variations))
            {
                // TODO: Call GetItemByIds for variations recursively (need to measure performance and data amount first)

                var variationIds = Items.Where(x => itemIds.Contains(x.ParentId)).Select(x => x.Id).ToArray();

                // Always load info, images and property values for variations
                var variations = Items.Include(x => x.Images).Where(x => variationIds.Contains(x.Id)).ToArray();
                var variationPropertyValues = PropertyValues.Where(x => variationIds.Contains(x.ItemId)).ToArray();

                if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemAssets))
                {
                    var variationAssets = Assets.Where(x => variationIds.Contains(x.ItemId)).ToArray();
                }

                if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemEditorialReviews))
                {
                    var variationEditorialReviews = EditorialReviews.Where(x => variationIds.Contains(x.ItemId)).ToArray();
                }
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemAssociations))
            {
                var assosiations         = Associations.Where(x => itemIds.Contains(x.ItemId)).ToArray();
                var assosiatedProductIds = assosiations.Where(x => x.AssociatedItemId != null)
                                           .Select(x => x.AssociatedItemId).Distinct().ToArray();

                var assosiatedItems = GetItemByIds(assosiatedProductIds, coreModel.ItemResponseGroup.ItemInfo | coreModel.ItemResponseGroup.ItemAssets);
            }

            // Load parents
            var parentIds = retVal.Where(x => x.Parent == null && x.ParentId != null).Select(x => x.ParentId).ToArray();
            var parents   = GetItemByIds(parentIds, respGroup);

            return(retVal);
        }
    protected override void SetResultDescriptions(GameObject seed_or_plant)
    {
        string            text       = string.Empty;
        GameObject        gameObject = seed_or_plant;
        PlantableSeed     component  = seed_or_plant.GetComponent <PlantableSeed>();
        List <Descriptor> list       = new List <Descriptor>();

        if ((Object)component != (Object)null)
        {
            list = component.GetDescriptors(component.gameObject);
            if ((Object)targetReceptacle.rotatable != (Object)null && targetReceptacle.Direction != component.direction)
            {
                if (component.direction == SingleEntityReceptacle.ReceptacleDirection.Top)
                {
                    text += UI.UISIDESCREENS.PLANTERSIDESCREEN.ROTATION_NEED_FLOOR;
                }
                else if (component.direction == SingleEntityReceptacle.ReceptacleDirection.Side)
                {
                    text += UI.UISIDESCREENS.PLANTERSIDESCREEN.ROTATION_NEED_WALL;
                }
                else if (component.direction == SingleEntityReceptacle.ReceptacleDirection.Bottom)
                {
                    text += UI.UISIDESCREENS.PLANTERSIDESCREEN.ROTATION_NEED_CEILING;
                }
                text += "\n\n";
            }
            gameObject = Assets.GetPrefab(component.PlantID);
            if (!string.IsNullOrEmpty(component.domesticatedDescription))
            {
                text += component.domesticatedDescription;
            }
        }
        else
        {
            InfoDescription component2 = gameObject.GetComponent <InfoDescription>();
            if ((bool)component2)
            {
                text += component2.description;
            }
        }
        descriptionLabel.SetText(text);
        List <Descriptor> plantLifeCycleDescriptors = GameUtil.GetPlantLifeCycleDescriptors(gameObject);

        if (plantLifeCycleDescriptors.Count > 0)
        {
            HarvestDescriptorPanel.SetDescriptors(plantLifeCycleDescriptors);
            HarvestDescriptorPanel.gameObject.SetActive(true);
        }
        List <Descriptor> plantRequirementDescriptors = GameUtil.GetPlantRequirementDescriptors(gameObject);

        if (list.Count > 0)
        {
            GameUtil.IndentListOfDescriptors(list, 1);
            plantRequirementDescriptors.InsertRange(plantRequirementDescriptors.Count, list);
        }
        if (plantRequirementDescriptors.Count > 0)
        {
            RequirementsDescriptorPanel.SetDescriptors(plantRequirementDescriptors);
            RequirementsDescriptorPanel.gameObject.SetActive(true);
        }
        List <Descriptor> plantEffectDescriptors = GameUtil.GetPlantEffectDescriptors(gameObject);

        if (plantEffectDescriptors.Count > 0)
        {
            EffectsDescriptorPanel.SetDescriptors(plantEffectDescriptors);
            EffectsDescriptorPanel.gameObject.SetActive(true);
        }
        else
        {
            EffectsDescriptorPanel.gameObject.SetActive(false);
        }
    }
示例#30
0
        internal static async Task MainSafe(CommandSettings args)
        {
            try
            {
                Console.WriteLine(Header);

                if (args.GetVersions)
                {
                    var releases1 = await GetReleases().ConfigureAwait(false);

                    Console.WriteLine("--- AVAILABLE VERSIONS ---");
                    foreach (var r in releases1)
                    {
                        Console.WriteLine(FormatRelease(r, true));
                    }

                    if (args.Exit)
                    {
                        Environment.Exit(0);
                    }
                }

                Console.WriteLine($"AppData folder: {args.AppData.FullName}");

                if (!ValidateServerPath(args.Path.FullName, out var targetFilePath))
                {
                    Console.WriteLine($"Couldn't find '{TARGET_FILE_NAME}' in '{targetFilePath}'");
                    throw new FileNotFoundException("Check the validation of the path parameter");
                }

                if (!(args.GitHubToken is null))
                {
                    Console.WriteLine("Token detected! Using the token...");
                    GitHubClient.Credentials = new Credentials(args.GitHubToken, AuthenticationType.Bearer);
                }

                Console.WriteLine("Receiving releases...");
                Console.WriteLine($"Prereleases included - {args.PreReleases}");
                Console.WriteLine($"Target release version - {(string.IsNullOrEmpty(args.TargetVersion) ? "(null)" : args.TargetVersion)}");

                var releases = await GetReleases().ConfigureAwait(false);

                Console.WriteLine("Searching for the latest release that matches the parameters...");

                if (!TryFindRelease(args, releases, out var targetRelease))
                {
                    Console.WriteLine("--- RELEASES ---");
                    Console.WriteLine(string.Join(Environment.NewLine, releases.Select(FormatRelease)));
                    throw new InvalidOperationException("Couldn't find release");
                }

                Console.WriteLine("Release found!");
                Console.WriteLine(FormatRelease(targetRelease !));

                var exiledAsset = targetRelease !.Assets.FirstOrDefault(a => a.Name.Equals(EXILED_ASSET_NAME, StringComparison.OrdinalIgnoreCase));
                if (exiledAsset is null)
                {
                    Console.WriteLine("--- ASSETS ---");
                    Console.WriteLine(string.Join(Environment.NewLine, targetRelease.Assets.Select(FormatAsset)));
                    throw new InvalidOperationException("Couldn't find asset");
                }

                Console.WriteLine("Asset found!");
                Console.WriteLine(FormatAsset(exiledAsset));

                using var httpClient = new HttpClient
                      {
                          Timeout = TimeSpan.FromSeconds(SecondsWaitForDownload)
                      };
                httpClient.DefaultRequestHeaders.Add("User-Agent", Header);

                using var downloadResult = await httpClient.GetAsync(exiledAsset.BrowserDownloadUrl).ConfigureAwait(false);

                using var downloadArchiveStream = await downloadResult.Content.ReadAsStreamAsync().ConfigureAwait(false);

                using var gzInputStream  = new GZipInputStream(downloadArchiveStream);
                using var tarInputStream = new TarInputStream(gzInputStream);

                TarEntry entry;
                while (!((entry = tarInputStream.GetNextEntry()) is null))
                {
                    entry.Name = entry.Name.Replace('/', Path.DirectorySeparatorChar);
                    ProcessTarEntry(args, targetFilePath, tarInputStream, entry);
                }

                Console.WriteLine("Installation complete");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("Read the exception message, read the readme, and if you still don't understand what to do, then contact #support in our discord server with the attached screenshot of the full exception");
                if (!args.Exit)
                {
                    Console.Read();
                }
            }

            if (args.Exit)
            {
                Environment.Exit(0);
            }
        }
        public void Initialize(GraphicsDevice graphicsDevice, FullScreenTriangle fullScreenTriangle, Assets assets)
        {
            _graphicsDevice     = graphicsDevice;
            _fullScreenTriangle = fullScreenTriangle;
            _assets             = assets;

            _lightBlendState = new BlendState
            {
                AlphaSourceBlend      = Blend.One,
                ColorSourceBlend      = Blend.One,
                ColorDestinationBlend = Blend.One,
                AlphaDestinationBlend = Blend.One
            };
        }
示例#32
0
 protected override bool ExportInner(ProjectAssetContainer container, string filePath)
 {
     return(AssetExporter.Export(container, Assets.Select(t => t.Convert(container)), filePath));
 }
示例#33
0
文件: Game.cs 项目: tilpner/hp
 public Player(Assets assets) {
     Box = new BBAA(v2f(0, 0), v2f(0.8F, 0.8F));
     anim = assets.Animation("cat");
     anim.Scale = Box.Size;
 }
        public string AssignAsset(int assetID, string data)
        {
            AssignAssetSave info;

            try
            {
                info = Newtonsoft.Json.JsonConvert.DeserializeObject <AssignAssetSave>(data);
            }
            catch (Exception e)
            {
                return("error");
            }

            LoginUser loginUser = TSAuthentication.GetLoginUser();
            Asset     o         = Assets.GetAsset(loginUser, assetID);

            //Location 1=assigned (shipped), 2=warehouse, 3=junkyard
            o.Location   = "1";
            o.AssignedTo = info.RefID;
            DateTime now = DateTime.UtcNow;

            o.DateModified = now;
            o.ModifierID   = loginUser.UserID;
            o.Collection.Save();

            AssetHistory     assetHistory     = new AssetHistory(loginUser);
            AssetHistoryItem assetHistoryItem = assetHistory.AddNewAssetHistoryItem();

            assetHistoryItem.AssetID            = assetID;
            assetHistoryItem.OrganizationID     = loginUser.OrganizationID;
            assetHistoryItem.ActionTime         = DateTime.UtcNow;
            assetHistoryItem.ActionDescription  = "Asset Shipped on " + info.DateShipped.Month.ToString() + "/" + info.DateShipped.Day.ToString() + "/" + info.DateShipped.Year.ToString();
            assetHistoryItem.ShippedFrom        = loginUser.OrganizationID;
            assetHistoryItem.ShippedFromRefType = (int)ReferenceType.Organizations;
            assetHistoryItem.ShippedTo          = info.RefID;
            assetHistoryItem.TrackingNumber     = info.TrackingNumber;
            assetHistoryItem.ShippingMethod     = info.ShippingMethod;
            assetHistoryItem.ReferenceNum       = info.ReferenceNumber;
            assetHistoryItem.Comments           = info.Comments;

            assetHistoryItem.DateCreated  = now;
            assetHistoryItem.Actor        = loginUser.UserID;
            assetHistoryItem.RefType      = info.RefType;
            assetHistoryItem.DateModified = now;
            assetHistoryItem.ModifierID   = loginUser.UserID;

            assetHistory.Save();

            AssetAssignments assetAssignments = new AssetAssignments(loginUser);
            AssetAssignment  assetAssignment  = assetAssignments.AddNewAssetAssignment();

            assetAssignment.HistoryID = assetHistoryItem.HistoryID;

            assetAssignments.Save();

            string description = String.Format("Assigned asset to {0}.", info.AssigneeName);

            ActionLogs.AddActionLog(loginUser, ActionLogType.Update, ReferenceType.Assets, assetID, description);

            AssetsView assetsView = new AssetsView(loginUser);

            assetsView.LoadByAssetID(assetID);

            StringBuilder productVersionNumberDisplayName = new StringBuilder();

            if (!string.IsNullOrEmpty(assetsView[0].ProductVersionNumber))
            {
                productVersionNumberDisplayName.Append(" - " + assetsView[0].ProductVersionNumber);
            }

            StringBuilder serialNumberDisplayValue = new StringBuilder();

            if (string.IsNullOrEmpty(assetsView[0].SerialNumber))
            {
                serialNumberDisplayValue.Append("Empty");
            }
            else
            {
                serialNumberDisplayValue.Append(assetsView[0].SerialNumber);
            }

            StringBuilder warrantyExpirationDisplayValue = new StringBuilder();

            if (assetsView[0].WarrantyExpiration == null)
            {
                warrantyExpirationDisplayValue.Append("Empty");
            }
            else
            {
                warrantyExpirationDisplayValue.Append(((DateTime)assetsView[0].WarrantyExpiration).ToString(GetDateFormatNormal()));
            }

            return(string.Format(@"<div class='list-group-item'>
                            <a href='#' id='{0}' class='assetLink'><h4 class='list-group-item-heading'>{1}</h4></a>
                            <div class='row'>
                                <div class='col-xs-8'>
                                    <p class='list-group-item-text'>{2}{3}</p>
                                </div>
                            </div>
                            <div class='row'>
                                <div class='col-xs-8'>
                                    <p class='list-group-item-text'>SN: {4} - Warr. Exp.: {5}</p>
                                </div>
                            </div>
                            </div>"

                                 , assetID
                                 , assetsView[0].DisplayName
                                 , assetsView[0].ProductName
                                 , productVersionNumberDisplayName
                                 , serialNumberDisplayValue
                                 , warrantyExpirationDisplayValue));
        }
示例#35
0
 public static Sky Get(string path)
 {
     return(Assets.Get <Sky>(path));
 }
示例#36
0
        public override void UpdateState(List <UnturnedPlayer> players)
        {
            ushort maxHealth = ushort.MaxValue;

            if (StructureManager.regions != null)
            {
                for (var i0 = 0; i0 < StructureManager.regions.GetLength(0); i0++)
                {
                    for (var i1 = 0; i1 < StructureManager.regions.GetLength(1); i1++)
                    {
                        var region = StructureManager.regions[i0, i1];
                        if (region == null)
                        {
                            continue;
                        }
                        for (var i = 0; i < region.structures.Count; i++)
                        {
                            var structure = region.structures[i];
                            if (structure?.structure == null)
                            {
                                continue;
                            }
                            if (!Region.Type.IsInRegion(new SerializablePosition(structure.point)))
                            {
                                continue;
                            }

                            var asset = (ItemStructureAsset)Assets.find(EAssetType.ITEM, structure.structure.id);
                            if (asset == null)
                            {
                                continue;
                            }

                            if (GetValueSafe() && structure.structure.health < maxHealth)
                            {
                                structure.structure.health = maxHealth;
                            }
                            else if (!GetValueSafe() && structure.structure.health > asset.health)
                            {
                                structure.structure.health = asset.health;
                            }
                        }
                    }
                }
            }

            if (BarricadeManager.regions == null)
            {
                return;
            }
            {
                for (var i0 = 0; i0 < BarricadeManager.regions.GetLength(0); i0++)
                {
                    for (var i1 = 0; i1 < BarricadeManager.regions.GetLength(1); i1++)
                    {
                        var region = BarricadeManager.regions[i0, i1];
                        if (region == null)
                        {
                            continue;
                        }
                        for (var i = 0; i < region.barricades.Count; i++)
                        {
                            var barricade = region.barricades[i];
                            if (barricade?.barricade == null)
                            {
                                continue;
                            }
                            if (!Region.Type.IsInRegion(new SerializablePosition(barricade.point)))
                            {
                                continue;
                            }

                            var asset = (ItemBarricadeAsset)Assets.find(EAssetType.ITEM, barricade.barricade.id);
                            if (asset == null)
                            {
                                continue;
                            }

                            if (asset.build == EBuild.FARM)
                            {
                                continue;
                            }

                            if (GetValueSafe() && barricade.barricade.health < maxHealth)
                            {
                                barricade.barricade.health = maxHealth;
                            }
                            else if (!GetValueSafe() && barricade.barricade.health > asset.health)
                            {
                                barricade.barricade.health = asset.health;
                            }
                        }
                    }
                }
            }
        }
 private void ShowItemsUI(Player callPlayer, byte page)//target player idnex in provider.clients
 {
     try
     {
         EffectManager.sendUIEffect(8101, 26, callPlayer.channel.owner.playerID.steamID, true);
         if (MyItemsPages[page - 1].Count != 0)
         {
             for (byte i = 0; i < MyItemsPages[page - 1].Count; i++)
             {
                 EffectManager.sendUIEffectText(26, callPlayer.channel.owner.playerID.steamID, true, $"item{i}", $"{((ItemAsset)Assets.find(EAssetType.ITEM, MyItemsPages[pagesCount - 1][i].ID)).itemName}\r\nID: {MyItemsPages[pagesCount - 1][i].ID}\r\nCount: {MyItemsPages[pagesCount - 1][i].Count}");
             }
         }
         for (byte i = (byte)MyItemsPages[0].Count; i < 24; i++)
         {
             EffectManager.sendUIEffectText(26, callPlayer.channel.owner.playerID.steamID, true, $"item{i}", $"");
         }
         EffectManager.sendUIEffectText(26, callPlayer.channel.owner.playerID.steamID, true, "page", $"{page}");
         EffectManager.sendUIEffectText(26, callPlayer.channel.owner.playerID.steamID, true, "pagemax", $"{pagesCount}");
         EffectManager.sendUIEffectText(26, callPlayer.channel.owner.playerID.steamID, true, "playerName", $"Cloud: {callPlayer.channel.owner.playerID.characterName}");
     }
     catch (System.Exception e)
     {
         Rocket.Core.Logging.Logger.LogException(e, "Exception in ManageCloudUI.ShowItemsUI(Player, byte)");
         QuitUI(callPlayer, 8101);
         return;
     }
 }
示例#38
0
        void Manager_AssetAdded(object sender, Assets.AssetManagerEventArgs e)
        {
            var asset = e.Asset;

            //ignore if not in the current category
            var selectedCategory = this.GetSelectedCategory();
            if ((selectedCategory != m_CategoryAll) && (e.Asset.Category != selectedCategory))
                return;

            this.AddAsset(e.Asset);
        }
示例#39
0
        public override void _Process(float delta)
        {
            base._Process(delta);

            DebugFloor.GlobalTransform = new Transform(new Basis(Vector3.Right, Mathf.Pi / 2f).Orthonormalized(), new Vector3((TileX + 0.5f) * Assets.WallWidth, 0f, (TileZ + 0.5f) * Assets.WallWidth));

            if (!Main.Room.Paused)
            {
                if (Main.ActionRoom.Level.GetActorAt(TileX, TileZ) == this)
                {
                    Main.ActionRoom.Level.SetActorAt(TileX, TileZ);
                }

                Seconds += delta;
                if (Seconds > State.Seconds)
                {
                    State = State.Next;
                }

                if (NewState)
                {
                    NewState = false;
                    if (!Settings.DigiSoundMuted &&
                        State?.XML?.Attribute("DigiSound")?.Value is string digiSound &&
                        Assets.DigiSoundSafe(digiSound) is AudioStreamSample audioStreamSample)
                    {
                        Play = audioStreamSample;
                    }
                    State?.Act?.Invoke(this, delta);                     // Act methods are called once per state
                }

                State?.Think?.Invoke(this, delta);                 // Think methods are called once per frame -- NOT per tic!
                if (Visible && State != null &&
                    State.Shape is short shape &&
                    (ushort)(shape + (State.Rotate ?
                                      Direction8.Modulus(
                                          Direction8.AngleToPoint(
                                              GlobalTransform.origin,
                                              GetViewport().GetCamera().GlobalTransform.origin
                                              ).MirrorZ + (Direction ?? 0),
                                          8)
                                        : 0)) is ushort newFrame &&
                    newFrame != Page)
                {
                    Page = newFrame;
                }

                // START DEBUGGING

                /*
                 * if (!State.Alive && SightPlayer())
                 * {
                 *      if (!Settings.DigiSoundMuted
                 * && ActorXML?.Attribute("DigiSound")?.Value is string digiSound
                 * && Assets.DigiSoundSafe(digiSound) is AudioStreamSample audioStreamSample)
                 *              Play = audioStreamSample;
                 *      if (Assets.States.TryGetValue(ActorXML?.Attribute("Chase")?.Value, out State chase))
                 *              State = chase;
                 * }
                 */
                // END DEBUGGING

                if (State.Mark)
                {
                    Main.ActionRoom.Level.SetActorAt(TileX, TileZ, this);
                }
            }
        }
示例#40
0
文件: Game.cs 项目: tilpner/hp
 public Game(Assets assets, Level level) {
     player = new Player(assets);
     player.Box.Position = level.Start;
     this.level = level;
     infoText = new Text("Foo", assets.Font("Ubuntu-R.ttf"), 20);
     infoText.Color = Color.Black;
 }
    public GameObject CreatePrefab()
    {
        GameObject template = EntityTemplates.CreateLooseEntity("Burger", ITEMS.FOOD.BURGER.NAME, ITEMS.FOOD.BURGER.DESC, 1f, false, Assets.GetAnim("frost_burger_kanim"), "object", Grid.SceneLayer.Front, EntityTemplates.CollisionShape.RECTANGLE, 0.8f, 0.4f, true, 0, SimHashes.Creature, null);

        return(EntityTemplates.ExtendEntityToFood(template, FOOD.FOOD_TYPES.BURGER));
    }
        public GameObject CreatePrefab()
        {
            var placedEntity = EntityTemplates.CreatePlacedEntity(ID, NAME, DESC, 1f, Assets.GetAnim("resonantplant_kanim"),
                                                                  "idle_empty", Grid.SceneLayer.BuildingFront, 1, 2, DECOR.NONE);

            EntityTemplates.ExtendEntityToBasicPlant(placedEntity, K,
                                                     MIN_GROW_TEMP,
                                                     MAX_GROW_TEMP,
                                                     MAX_GROW_TEMP + 80,
                                                     new [] { SimHashes.CarbonDioxide },
                                                     false,
                                                     0f,
                                                     0.15f,
                                                     SEED_ID);

            var pressureVulnerable = placedEntity.AddOrGet <PressureVulnerable>();

            pressureVulnerable.Configure((float)0.15f, (float)0f, 99000f, 99900f, new[]
            {
                SimHashes.CarbonDioxide
            });

            Storage storage = placedEntity.AddOrGet <Storage>();

            storage.showInUI   = false;
            storage.capacityKg = 2f;

            var elementConsumer = placedEntity.AddOrGet <ElementConsumer>();

            elementConsumer.showInStatusPanel = true;
            elementConsumer.showDescriptor    = true;
            elementConsumer.storeOnConsume    = false;
            elementConsumer.configuration     = ElementConsumer.Configuration.Element;
            elementConsumer.elementToConsume  = SimHashes.CarbonDioxide;
            elementConsumer.consumptionRadius = 4;
            elementConsumer.sampleCellOffset  = new Vector3(0.0f, 1f);
            elementConsumer.consumptionRate   = CO2_PER_SECOND;

            placedEntity.AddOrGet <StandardCropPlant>();
            placedEntity.AddOrGet <IlluminationVulnerable>().SetPrefersDarkness(false);
            EntityTemplates.CreateAndRegisterPreviewForPlant(
                EntityTemplates.CreateAndRegisterSeedForPlant(placedEntity,
                                                              SeedProducer.ProductionType.Harvest,
                                                              SEED_ID,
                                                              SEED_NAME,
                                                              SEED_DESC,
                                                              Assets.GetAnim((HashedString)"seed_resonantplant_kanim"),
                                                              "object", 0, new List <Tag>
            {
                GameTags.CropSeed
            }, SingleEntityReceptacle.ReceptacleDirection.Top, new Tag(), 2,
                                                              CREATURES.SPECIES.PRICKLEFLOWER.DOMESTICATEDDESC, EntityTemplates.CollisionShape.CIRCLE, 0.25f,
                                                              0.25f,
                                                              null, string.Empty
                                                              ),
                "Resonantplant_preview",
                Assets.GetAnim("resonantplant_kanim"),
                "place", 1, 2);
            SoundEventVolumeCache.instance.AddVolume("bristleblossom_kanim", "resonantplant_harvest",
                                                     NOISE_POLLUTION.CREATURES.TIER3);
            SoundEventVolumeCache.instance.AddVolume("bristleblossom_kanim", "resonantplant_grow",
                                                     NOISE_POLLUTION.CREATURES.TIER3);
            placedEntity.AddOrGet <CoalPlant>();

            return(placedEntity);
        }
示例#43
0
 public bool ContainsItem(TradeAsset asset)
 {
     return(Assets.Contains(asset));
 }
示例#44
0
		public virtual void addEffect (Assets.Scripts.Engine.Effects.MinionEffects.MinionEffect effect)
		{
			// TODO
		}
 public Entity SetGameState(Assets.Sources.GameLogic.Meta.GameState newGameState)
 {
     if (hasGameState) {
         throw new SingleEntityException(Matcher.GameState);
     }
     var entity = CreateEntity();
     entity.AddGameState(newGameState);
     return entity;
 }
 public Entity AddGameEventState(Assets.Sources.GameLogic.Components.EventState newEventState)
 {
     var component = _gameEventStateComponentPool.Count > 0 ? _gameEventStateComponentPool.Pop() : new Assets.Sources.GameLogic.Components.GameEventStateComponent();
     component.EventState = newEventState;
     return AddComponent(ComponentIds.GameEventState, component);
 }
    public GameObject CreatePrefab()
    {
        GameObject gameObject = EntityTemplates.CreateLooseEntity("Antihistamine", ITEMS.PILLS.ANTIHISTAMINE.NAME, ITEMS.PILLS.ANTIHISTAMINE.DESC, 1f, true, Assets.GetAnim("pill_allergies_kanim"), "object", Grid.SceneLayer.Front, EntityTemplates.CollisionShape.RECTANGLE, 0.8f, 0.4f, true, 0, SimHashes.Creature, null);

        EntityTemplates.ExtendEntityToMedicine(gameObject, MEDICINE.ANTIHISTAMINE);
        ComplexRecipe.RecipeElement[] array = new ComplexRecipe.RecipeElement[2]
        {
            new ComplexRecipe.RecipeElement("PrickleFlowerSeed", 1f),
            new ComplexRecipe.RecipeElement(SimHashes.Dirt.CreateTag(), 1f)
        };
        ComplexRecipe.RecipeElement[] array2 = new ComplexRecipe.RecipeElement[1]
        {
            new ComplexRecipe.RecipeElement("Antihistamine", 10f)
        };
        string        id            = ComplexRecipeManager.MakeRecipeID("Apothecary", array, array2);
        ComplexRecipe complexRecipe = new ComplexRecipe(id, array, array2);

        complexRecipe.time        = 100f;
        complexRecipe.description = ITEMS.PILLS.ANTIHISTAMINE.RECIPEDESC;
        complexRecipe.nameDisplay = ComplexRecipe.RecipeNameDisplay.Result;
        complexRecipe.fabricators = new List <Tag>
        {
            "Apothecary"
        };
        complexRecipe.sortOrder = 10;
        recipe = complexRecipe;
        return(gameObject);
    }
示例#48
0
        public void bakeFoliageSurface(FoliageBakeSettings bakeSettings, FoliageTile foliageTile)
        {
            int num  = (foliageTile.coord.y * FoliageSystem.TILE_SIZE_INT - this.coord.y * Landscape.TILE_SIZE_INT) / FoliageSystem.TILE_SIZE_INT * FoliageSystem.SPLATMAP_RESOLUTION_PER_TILE;
            int num2 = num + FoliageSystem.SPLATMAP_RESOLUTION_PER_TILE;
            int num3 = (foliageTile.coord.x * FoliageSystem.TILE_SIZE_INT - this.coord.x * Landscape.TILE_SIZE_INT) / FoliageSystem.TILE_SIZE_INT * FoliageSystem.SPLATMAP_RESOLUTION_PER_TILE;
            int num4 = num3 + FoliageSystem.SPLATMAP_RESOLUTION_PER_TILE;

            for (int i = num; i < num2; i++)
            {
                for (int j = num3; j < num4; j++)
                {
                    SplatmapCoord splatmapCoord = new SplatmapCoord(i, j);
                    float         num5          = (float)this.coord.x * Landscape.TILE_SIZE + (float)splatmapCoord.y * Landscape.SPLATMAP_WORLD_UNIT;
                    float         num6          = (float)this.coord.y * Landscape.TILE_SIZE + (float)splatmapCoord.x * Landscape.SPLATMAP_WORLD_UNIT;
                    Bounds        bounds        = default(Bounds);
                    bounds.min = new Vector3(num5, 0f, num6);
                    bounds.max = new Vector3(num5 + Landscape.SPLATMAP_WORLD_UNIT, 0f, num6 + Landscape.SPLATMAP_WORLD_UNIT);
                    for (int k = 0; k < Landscape.SPLATMAP_LAYERS; k++)
                    {
                        float num7 = this.sourceSplatmap[i, j, k];
                        if (num7 >= 0.01f)
                        {
                            LandscapeMaterialAsset landscapeMaterialAsset = Assets.find <LandscapeMaterialAsset>(this.materials[k]);
                            if (landscapeMaterialAsset != null)
                            {
                                FoliageInfoCollectionAsset foliageInfoCollectionAsset = Assets.find <FoliageInfoCollectionAsset>(landscapeMaterialAsset.foliage);
                                if (foliageInfoCollectionAsset != null)
                                {
                                    foliageInfoCollectionAsset.bakeFoliage(bakeSettings, this, bounds, num7);
                                }
                            }
                        }
                    }
                }
            }
        }
示例#49
0
文件: Game.cs 项目: tilpner/hp
 public BlockType LoadBlockType(Assets assets) {
     var sp = assets.Sprite(Sprite);
     sp.Scale = new Vector2f(1F / sp.Texture.Size.X, 1F / sp.Texture.Size.Y);
     return new BlockType(Name, sp, Collider, Friction);
 }
    public GameObject CreatePrefab()
    {
        GameObject gameObject = EntityTemplates.CreatePlacedEntity("ColdBreather", STRINGS.CREATURES.SPECIES.COLDBREATHER.NAME, STRINGS.CREATURES.SPECIES.COLDBREATHER.DESC, 400f, Assets.GetAnim("coldbreather_kanim"), "grow_seed", Grid.SceneLayer.BuildingFront, 1, 2, DECOR.BONUS.TIER1, NOISE_POLLUTION.NOISY.TIER2, SimHashes.Creature, null, 293f);

        gameObject.AddOrGet <ReceptacleMonitor>();
        gameObject.AddOrGet <EntombVulnerable>();
        gameObject.AddOrGet <WiltCondition>();
        gameObject.AddOrGet <Prioritizable>();
        gameObject.AddOrGet <Uprootable>();
        gameObject.AddOrGet <UprootedMonitor>();
        gameObject.AddOrGet <DrowningMonitor>();
        EntityTemplates.ExtendPlantToFertilizable(gameObject, new PlantElementAbsorber.ConsumeInfo[1]
        {
            new PlantElementAbsorber.ConsumeInfo
            {
                tag = SimHashes.Phosphorite.CreateTag(),
                massConsumptionRate = 0.006666667f
            }
        });
        TemperatureVulnerable temperatureVulnerable = gameObject.AddOrGet <TemperatureVulnerable>();

        temperatureVulnerable.Configure(213.15f, 183.15f, 368.15f, 463.15f);
        gameObject.AddOrGet <OccupyArea>().objectLayers = new ObjectLayer[1]
        {
            ObjectLayer.Building
        };
        ColdBreather coldBreather = gameObject.AddOrGet <ColdBreather>();

        coldBreather.deltaEmitTemperature = -5f;
        coldBreather.emitOffsetCell       = new Vector3(0f, 1f);
        coldBreather.consumptionRate      = 1f;
        gameObject.AddOrGet <KBatchedAnimController>().randomiseLoopedOffset = true;
        Storage storage = BuildingTemplates.CreateDefaultStorage(gameObject, false);

        storage.showInUI = false;
        ElementConsumer elementConsumer = gameObject.AddOrGet <ElementConsumer>();

        elementConsumer.storeOnConsume    = true;
        elementConsumer.configuration     = ElementConsumer.Configuration.AllGas;
        elementConsumer.capacityKG        = 2f;
        elementConsumer.consumptionRate   = 0.25f;
        elementConsumer.consumptionRadius = 1;
        elementConsumer.sampleCellOffset  = new Vector3(0f, 0f);
        SimTemperatureTransfer component = gameObject.GetComponent <SimTemperatureTransfer>();

        component.SurfaceArea = 10f;
        component.Thickness   = 0.001f;
        GameObject plant = gameObject;

        SeedProducer.ProductionType productionType = SeedProducer.ProductionType.Hidden;
        string     id   = "ColdBreatherSeed";
        string     name = STRINGS.CREATURES.SPECIES.SEEDS.COLDBREATHER.NAME;
        string     desc = STRINGS.CREATURES.SPECIES.SEEDS.COLDBREATHER.DESC;
        KAnimFile  anim = Assets.GetAnim("seed_coldbreather_kanim");
        List <Tag> list = new List <Tag>();

        list.Add(GameTags.CropSeed);
        list = list;
        GameObject seed = EntityTemplates.CreateAndRegisterSeedForPlant(plant, productionType, id, name, desc, anim, "object", 1, list, SingleEntityReceptacle.ReceptacleDirection.Top, default(Tag), 2, STRINGS.CREATURES.SPECIES.COLDBREATHER.DOMESTICATEDDESC, EntityTemplates.CollisionShape.CIRCLE, 0.3f, 0.3f, null, string.Empty, false);

        EntityTemplates.CreateAndRegisterPreviewForPlant(seed, "ColdBreather_preview", Assets.GetAnim("coldbreather_kanim"), "place", 1, 2);
        SoundEventVolumeCache.instance.AddVolume("coldbreather_kanim", "ColdBreather_grow", NOISE_POLLUTION.CREATURES.TIER3);
        SoundEventVolumeCache.instance.AddVolume("coldbreather_kanim", "ColdBreather_intake", NOISE_POLLUTION.CREATURES.TIER3);
        return(gameObject);
    }
示例#51
0
 public SerializedObject GetInputAxisSerializedObject() => new SerializedObject(Assets.FirstOrDefault());
 // Token: 0x060025FE RID: 9726 RVA: 0x000DE800 File Offset: 0x000DCC00
 public static void load()
 {
     LevelZombies._models                 = new GameObject().transform;
     LevelZombies.models.name             = "Zombies";
     LevelZombies.models.parent           = Level.spawns;
     LevelZombies.models.tag              = "Logic";
     LevelZombies.models.gameObject.layer = LayerMasks.LOGIC;
     LevelZombies.tables = new List <ZombieTable>();
     if (ReadWrite.fileExists(Level.info.path + "/Spawns/Zombies.dat", false, false))
     {
         Block block = ReadWrite.readBlock(Level.info.path + "/Spawns/Zombies.dat", false, false, 0);
         byte  b     = block.readByte();
         if (b > 3 && b < 5)
         {
             block.readSteamID();
         }
         if (b > 2)
         {
             byte b2 = block.readByte();
             for (byte b3 = 0; b3 < b2; b3 += 1)
             {
                 Color  newColor     = block.readColor();
                 string newName      = block.readString();
                 bool   flag         = block.readBoolean();
                 ushort newHealth    = block.readUInt16();
                 byte   newDamage    = block.readByte();
                 byte   newLootIndex = block.readByte();
                 ushort newLootID;
                 if (b > 6)
                 {
                     newLootID = block.readUInt16();
                 }
                 else
                 {
                     newLootID = 0;
                 }
                 uint newXP;
                 if (b > 7)
                 {
                     newXP = block.readUInt32();
                 }
                 else if (flag)
                 {
                     newXP = 40u;
                 }
                 else
                 {
                     newXP = 3u;
                 }
                 float newRegen = 10f;
                 if (b > 5)
                 {
                     newRegen = block.readSingle();
                 }
                 string newDifficultyGUID = string.Empty;
                 if (b > 8)
                 {
                     newDifficultyGUID = block.readString();
                 }
                 ZombieSlot[] array = new ZombieSlot[4];
                 byte         b4    = block.readByte();
                 for (byte b5 = 0; b5 < b4; b5 += 1)
                 {
                     List <ZombieCloth> list = new List <ZombieCloth>();
                     float newChance         = block.readSingle();
                     byte  b6 = block.readByte();
                     for (byte b7 = 0; b7 < b6; b7 += 1)
                     {
                         ushort num = block.readUInt16();
                         if ((ItemAsset)Assets.find(EAssetType.ITEM, num) != null)
                         {
                             list.Add(new ZombieCloth(num));
                         }
                     }
                     array[(int)b5] = new ZombieSlot(newChance, list);
                 }
                 LevelZombies.tables.Add(new ZombieTable(array, newColor, newName, flag, newHealth, newDamage, newLootIndex, newLootID, newXP, newRegen, newDifficultyGUID));
             }
         }
         else
         {
             byte b8 = block.readByte();
             for (byte b9 = 0; b9 < b8; b9 += 1)
             {
                 Color        newColor2     = block.readColor();
                 string       newName2      = block.readString();
                 byte         newLootIndex2 = block.readByte();
                 ZombieSlot[] array2        = new ZombieSlot[4];
                 byte         b10           = block.readByte();
                 for (byte b11 = 0; b11 < b10; b11 += 1)
                 {
                     List <ZombieCloth> list2 = new List <ZombieCloth>();
                     float newChance2         = block.readSingle();
                     byte  b12 = block.readByte();
                     for (byte b13 = 0; b13 < b12; b13 += 1)
                     {
                         ushort num2 = block.readUInt16();
                         if ((ItemAsset)Assets.find(EAssetType.ITEM, num2) != null)
                         {
                             list2.Add(new ZombieCloth(num2));
                         }
                     }
                     array2[(int)b11] = new ZombieSlot(newChance2, list2);
                 }
                 LevelZombies.tables.Add(new ZombieTable(array2, newColor2, newName2, false, 100, 15, newLootIndex2, 0, 5u, 10f, string.Empty));
             }
         }
     }
     LevelZombies._spawns = new List <ZombieSpawnpoint> [(int)Regions.WORLD_SIZE, (int)Regions.WORLD_SIZE];
     for (byte b14 = 0; b14 < Regions.WORLD_SIZE; b14 += 1)
     {
         for (byte b15 = 0; b15 < Regions.WORLD_SIZE; b15 += 1)
         {
             LevelZombies.spawns[(int)b14, (int)b15] = new List <ZombieSpawnpoint>();
         }
     }
     if (Level.isEditor)
     {
         if (ReadWrite.fileExists(Level.info.path + "/Spawns/Animals.dat", false, false))
         {
             River river = new River(Level.info.path + "/Spawns/Animals.dat", false);
             byte  b16   = river.readByte();
             if (b16 > 0)
             {
                 for (byte b17 = 0; b17 < Regions.WORLD_SIZE; b17 += 1)
                 {
                     for (byte b18 = 0; b18 < Regions.WORLD_SIZE; b18 += 1)
                     {
                         ushort num3 = river.readUInt16();
                         for (ushort num4 = 0; num4 < num3; num4 += 1)
                         {
                             byte    newType  = river.readByte();
                             Vector3 newPoint = river.readSingleVector3();
                             LevelZombies.spawns[(int)b17, (int)b18].Add(new ZombieSpawnpoint(newType, newPoint));
                         }
                     }
                 }
             }
             river.closeRiver();
         }
         else
         {
             for (byte b19 = 0; b19 < Regions.WORLD_SIZE; b19 += 1)
             {
                 for (byte b20 = 0; b20 < Regions.WORLD_SIZE; b20 += 1)
                 {
                     LevelZombies.spawns[(int)b19, (int)b20] = new List <ZombieSpawnpoint>();
                     if (ReadWrite.fileExists(string.Concat(new object[]
                     {
                         Level.info.path,
                         "/Spawns/Animals_",
                         b19,
                         "_",
                         b20,
                         ".dat"
                     }), false, false))
                     {
                         River river2 = new River(string.Concat(new object[]
                         {
                             Level.info.path,
                             "/Spawns/Animals_",
                             b19,
                             "_",
                             b20,
                             ".dat"
                         }), false);
                         byte b21 = river2.readByte();
                         if (b21 > 0)
                         {
                             ushort num5 = river2.readUInt16();
                             for (ushort num6 = 0; num6 < num5; num6 += 1)
                             {
                                 byte    newType2  = river2.readByte();
                                 Vector3 newPoint2 = river2.readSingleVector3();
                                 LevelZombies.spawns[(int)b19, (int)b20].Add(new ZombieSpawnpoint(newType2, newPoint2));
                             }
                             river2.closeRiver();
                         }
                     }
                 }
             }
         }
     }
     else if (Provider.isServer)
     {
         LevelZombies._zombies = new List <ZombieSpawnpoint> [LevelNavigation.bounds.Count];
         for (int i = 0; i < LevelZombies.zombies.Length; i++)
         {
             LevelZombies.zombies[i] = new List <ZombieSpawnpoint>();
         }
         if (ReadWrite.fileExists(Level.info.path + "/Spawns/Animals.dat", false, false))
         {
             River river3 = new River(Level.info.path + "/Spawns/Animals.dat", false);
             byte  b22    = river3.readByte();
             if (b22 > 0)
             {
                 for (byte b23 = 0; b23 < Regions.WORLD_SIZE; b23 += 1)
                 {
                     for (byte b24 = 0; b24 < Regions.WORLD_SIZE; b24 += 1)
                     {
                         ushort num7 = river3.readUInt16();
                         for (ushort num8 = 0; num8 < num7; num8 += 1)
                         {
                             byte    newType3 = river3.readByte();
                             Vector3 vector   = river3.readSingleVector3();
                             byte    b25;
                             if (LevelNavigation.tryGetBounds(vector, out b25) && LevelNavigation.checkNavigation(vector))
                             {
                                 LevelZombies.zombies[(int)b25].Add(new ZombieSpawnpoint(newType3, vector));
                             }
                         }
                     }
                 }
             }
             river3.closeRiver();
         }
         else
         {
             for (byte b26 = 0; b26 < Regions.WORLD_SIZE; b26 += 1)
             {
                 for (byte b27 = 0; b27 < Regions.WORLD_SIZE; b27 += 1)
                 {
                     if (ReadWrite.fileExists(string.Concat(new object[]
                     {
                         Level.info.path,
                         "/Spawns/Animals_",
                         b26,
                         "_",
                         b27,
                         ".dat"
                     }), false, false))
                     {
                         River river4 = new River(string.Concat(new object[]
                         {
                             Level.info.path,
                             "/Spawns/Animals_",
                             b26,
                             "_",
                             b27,
                             ".dat"
                         }), false);
                         byte b28 = river4.readByte();
                         if (b28 > 0)
                         {
                             ushort num9 = river4.readUInt16();
                             for (ushort num10 = 0; num10 < num9; num10 += 1)
                             {
                                 byte    newType4 = river4.readByte();
                                 Vector3 vector2  = river4.readSingleVector3();
                                 byte    b29;
                                 if (LevelNavigation.tryGetBounds(vector2, out b29) && LevelNavigation.checkNavigation(vector2))
                                 {
                                     LevelZombies.zombies[(int)b29].Add(new ZombieSpawnpoint(newType4, vector2));
                                 }
                             }
                             river4.closeRiver();
                         }
                     }
                 }
             }
         }
     }
 }
示例#53
0
        private void DrawToScreenOrRenderTarget(SpriteBatch batch, Vector2 screenSize, RenderTarget2D target)
        {
            if (target != null)
            {
                batch.RenderTarget = target;
                batch.SamplerState = SamplerState.PointClamp;
            }
            else
            {
                screenSize = Program.ScaleBatch(batch);
            }

            batch.Transform = Matrix.CreateTranslation(_shakeOffset.X, _shakeOffset.Y, 0) * batch.Transform;

            string bg = "combat/plains.png";

            batch.Texture(new Vector2(0, -(float)_offset.Value), Assets.Get <Texture2D>(bg), Color.White);
            batch.Texture(new Vector2(0, 270 - (float)_offset.Value * 2), Assets.Get <Texture2D>("combat/menu.png"), Color.White);

            Font font = Assets.Get <Font>("fonts/bitcell.ttf");

            Matrix oldTransform = batch.Transform;

            batch.Transform = Matrix.CreateScale(2) * Matrix.CreateTranslation(80, 160 - (float)_offset.Value, 0) * oldTransform;
            Combatant.Draw(batch, false);
            Combatant.Draw(batch, true);

            batch.Transform = Matrix.CreateScale(2) * Matrix.CreateTranslation(screenSize.X - 80 - 32, 160 - (float)_offset.Value, 0) * oldTransform;
            if (Enemy is NPC)
            {
                (Enemy as NPC).Draw(batch);
            }

            batch.Transform = oldTransform;

            Menu.Draw(batch, new Rectangle(0, (int)(270 - (float)_offset.Value * 2), 480, Assets.Get <Texture2D>("combat/menu.png").Height), this);

            if (_showWarning)
            {
                Vector2 measure = font.Measure(32, "OH SHIT!!! " + Enemy.Name + " ENCOUNTERED");

                batch.Text(font, 32, "OH SHIT!!! " + Enemy.Name + " ENCOUNTERED", screenSize / 2 - measure / 2, Color.Red);
            }

            if (_inventoryUI != null)
            {
                batch.Rectangle(new Rectangle(0, 0, 480, 270), Color.Black * ((1.0f - _inventoryUI.MenuOffset) * 0.6f));
                _inventoryUI.ManualDraw();
            }

            if (target != null)
            {
                batch.RenderTarget = null;
            }
            else
            {
                Program.BlackBorders(batch);
            }
        }
示例#54
0
    public static GameObject BasePuft(string id, string name, string desc, string traitId, string anim_file, bool is_baby, string symbol_override_prefix, float warningLowTemperature, float warningHighTemperature)
    {
        float          mass        = 50f;
        KAnimFile      anim        = Assets.GetAnim(anim_file);
        string         initialAnim = "idle_loop";
        EffectorValues tIER        = DECOR.BONUS.TIER0;
        GameObject     gameObject  = EntityTemplates.CreatePlacedEntity(id, name, desc, mass, anim, initialAnim, Grid.SceneLayer.Creatures, 1, 1, tIER, default(EffectorValues), SimHashes.Creature, null, 293f);
        GameObject     template    = gameObject;

        FactionManager.FactionID faction = FactionManager.FactionID.Prey;
        string  navGridName      = "FlyerNavGrid1x1";
        NavType navType          = NavType.Hover;
        string  onDeathDropID    = "Meat";
        int     onDeathDropCount = 1;

        mass = warningLowTemperature - 45f;
        float lethalHighTemperature = warningHighTemperature + 50f;

        EntityTemplates.ExtendEntityToBasicCreature(template, faction, traitId, navGridName, navType, 32, 2f, onDeathDropID, onDeathDropCount, true, true, warningLowTemperature, warningHighTemperature, mass, lethalHighTemperature);
        if (!string.IsNullOrEmpty(symbol_override_prefix))
        {
            gameObject.AddOrGet <SymbolOverrideController>().ApplySymbolOverridesByAffix(Assets.GetAnim(anim_file), symbol_override_prefix, null, 0);
        }
        KPrefabID component = gameObject.GetComponent <KPrefabID>();

        component.AddTag(GameTags.Creatures.Flyer, false);
        component.prefabInitFn += delegate(GameObject inst)
        {
            inst.GetAttributes().Add(Db.Get().Attributes.MaxUnderwaterTravelCost);
        };
        gameObject.AddOrGet <LoopingSounds>();
        LureableMonitor.Def def = gameObject.AddOrGetDef <LureableMonitor.Def>();
        def.lures = new Tag[1]
        {
            GameTags.SlimeMold
        };
        gameObject.AddOrGetDef <ThreatMonitor.Def>();
        gameObject.AddOrGetDef <SubmergedMonitor.Def>();
        SoundEventVolumeCache.instance.AddVolume("puft_kanim", "Puft_voice_idle", NOISE_POLLUTION.CREATURES.TIER2);
        SoundEventVolumeCache.instance.AddVolume("puft_kanim", "Puft_air_intake", NOISE_POLLUTION.CREATURES.TIER4);
        SoundEventVolumeCache.instance.AddVolume("puft_kanim", "Puft_toot", NOISE_POLLUTION.CREATURES.TIER5);
        SoundEventVolumeCache.instance.AddVolume("puft_kanim", "Puft_air_inflated", NOISE_POLLUTION.CREATURES.TIER5);
        SoundEventVolumeCache.instance.AddVolume("puft_kanim", "Puft_voice_die", NOISE_POLLUTION.CREATURES.TIER5);
        SoundEventVolumeCache.instance.AddVolume("puft_kanim", "Puft_voice_hurt", NOISE_POLLUTION.CREATURES.TIER5);
        EntityTemplates.CreateAndRegisterBaggedCreature(gameObject, true, false, false);
        string inhaleSound = "Puft_air_intake";

        if (is_baby)
        {
            inhaleSound = "PuftBaby_air_intake";
        }
        ChoreTable.Builder chore_table = new ChoreTable.Builder().Add(new DeathStates.Def(), true).Add(new AnimInterruptStates.Def(), true).Add(new GrowUpStates.Def(), true)
                                         .Add(new IncubatingStates.Def(), true)
                                         .Add(new BaggedStates.Def(), true)
                                         .Add(new StunnedStates.Def(), true)
                                         .Add(new DebugGoToStates.Def(), true)
                                         .Add(new DrowningStates.Def(), true)
                                         .PushInterruptGroup()
                                         .Add(new CreatureSleepStates.Def(), true)
                                         .Add(new FixedCaptureStates.Def(), true)
                                         .Add(new RanchedStates.Def(), true)
                                         .Add(new UpTopPoopStates.Def(), true)
                                         .Add(new LayEggStates.Def(), true)
                                         .Add(new InhaleStates.Def
        {
            inhaleSound = inhaleSound
        }, true)
                                         .Add(new MoveToLureStates.Def(), true)
                                         .Add(new CallAdultStates.Def(), true)
                                         .PopInterruptGroup()
                                         .Add(new IdleStates.Def
        {
            customIdleAnim = new IdleStates.Def.IdleAnimCallback(BasePuftConfig.CustomIdleAnim)
        }, true);
        EntityTemplates.AddCreatureBrain(gameObject, chore_table, GameTags.Creatures.Species.PuftSpecies, symbol_override_prefix);
        return(gameObject);
    }
        public int ReturnAsset(int assetID, string data)
        {
            AssignAssetSave info;

            try
            {
                info = Newtonsoft.Json.JsonConvert.DeserializeObject <AssignAssetSave>(data);
            }
            catch (Exception e)
            {
                return(-1);
            }

            LoginUser loginUser = TSAuthentication.GetLoginUser();
            Asset     o         = Assets.GetAsset(loginUser, assetID);

            //Location 1=assigned (shipped), 2=warehouse, 3=junkyard
            o.Location   = "2";
            o.AssignedTo = null;
            DateTime now = DateTime.UtcNow;

            o.DateModified = now;
            o.ModifierID   = loginUser.UserID;
            o.Collection.Save();

            AssetAssignmentsView assetAssignmentsView = new AssetAssignmentsView(loginUser);

            assetAssignmentsView.LoadByAssetID(assetID);

            AssetHistory     assetHistory     = new AssetHistory(loginUser);
            AssetHistoryItem assetHistoryItem = assetHistory.AddNewAssetHistoryItem();

            assetHistoryItem.AssetID            = assetID;
            assetHistoryItem.OrganizationID     = loginUser.OrganizationID;
            assetHistoryItem.ActionTime         = DateTime.UtcNow;
            assetHistoryItem.ActionDescription  = "Item returned to warehouse on " + info.DateShipped.Month.ToString() + "/" + info.DateShipped.Day.ToString() + "/" + info.DateShipped.Year.ToString();
            assetHistoryItem.ShippedFrom        = assetAssignmentsView[0].ShippedTo;
            assetHistoryItem.ShippedFromRefType = assetAssignmentsView[0].RefType;
            assetHistoryItem.ShippedTo          = loginUser.OrganizationID;
            assetHistoryItem.RefType            = (int)ReferenceType.Organizations;
            assetHistoryItem.TrackingNumber     = info.TrackingNumber;
            assetHistoryItem.ShippingMethod     = info.ShippingMethod;
            assetHistoryItem.ReferenceNum       = info.ReferenceNumber;
            assetHistoryItem.Comments           = info.Comments;

            assetHistoryItem.DateCreated  = now;
            assetHistoryItem.Actor        = loginUser.UserID;
            assetHistoryItem.DateModified = now;
            assetHistoryItem.ModifierID   = loginUser.UserID;

            assetHistory.Save();

            AssetAssignments assetAssignments = new AssetAssignments(loginUser);

            foreach (AssetAssignmentsViewItem assetAssignmentViewItem in assetAssignmentsView)
            {
                assetAssignments.DeleteFromDB(assetAssignmentViewItem.AssetAssignmentsID);
            }

            ActionLogs.AddActionLog(loginUser, ActionLogType.Update, ReferenceType.Assets, assetID, "Returned asset.");

            return(assetID);
        }
示例#56
0
        /// <summary>
        /// Adds more items to the spawner list, including geysers, artifacts, and POI items.
        /// </summary>
        /// <param name="instance">The sandbox tool menu to modify.</param>
        private static void AddToSpawnerMenu(SandboxToolParameterMenu instance)
        {
            // Transpiling it is possible (and a bit faster) but way more brittle
            var selector = instance.entitySelector;
            var filters  = ListPool <SearchFilter, SandboxToolParameterMenu> .Allocate();

            filters.AddRange(selector.filters);
            // POI Props
            filters.Add(new SearchFilter(SandboxToolsStrings.FILTER_POIPROPS,
                                         (entity) => {
                var prefab = entity as KPrefabID;
                bool ok    = prefab != null;
                if (ok)
                {
                    string name = prefab.PrefabTag.Name;
                    // Include anti-entropy thermo nullifier and neural vacillator
                    // Vacillator's ID is private, we have to make do
                    ok = (name.StartsWith("Prop") && name.Length > 4 && char.IsUpper(
                              name, 4)) || name == MassiveHeatSinkConfig.ID ||
                         name == "GeneShuffler";
                }
                return(ok);
            }, null, Def.GetUISprite(Assets.GetPrefab("PropLadder"))));
            // Artifacts
            filters.Add(new SearchFilter(SandboxToolsStrings.FILTER_ARTIFACTS,
                                         (entity) => {
                var prefab = entity as KPrefabID;
                bool ok    = prefab != null;
                if (ok)
                {
                    ok = prefab.PrefabTag.Name.StartsWith("artifact_");
                }
                return(ok);
            }, null, Def.GetUISprite(Assets.GetPrefab("artifact_eggrock"))));
            // Geysers
            filters.Add(new SearchFilter(SandboxToolsStrings.FILTER_GEYSERS,
                                         (entity) => {
                var prefab = entity as KPrefabID;
                return(prefab != null && (prefab.GetComponent <Geyser>() != null || prefab.
                                          PrefabTag.Name == "OilWell"));
            }, null, Def.GetUISprite(Assets.GetPrefab("GeyserGeneric_slush_water"))));
            // TODO Vanilla/DLC code
            if (PPatchTools.GetTypeSafe("FullereneCometConfig") == null)
            {
                // Update the special filter to add other comet types
                foreach (var filter in filters)
                {
                    if (filter.Name == STRINGS.UI.SANDBOXTOOLS.FILTERS.ENTITIES.SPECIAL)
                    {
                        var oldCondition = filter.condition;
                        filter.condition = (entity) => {
                            var prefab = entity as KPrefabID;
                            return((prefab != null && prefab.GetComponent <Comet>() != null) ||
                                   oldCondition.Invoke(entity));
                        };
                    }
                }
            }
            // Add matching assets
            var options = ListPool <object, SandboxToolParameterMenu> .Allocate();

            foreach (var prefab in Assets.Prefabs)
            {
                foreach (var filter in filters)
                {
                    if (filter.condition(prefab))
                    {
                        options.Add(prefab);
                        break;
                    }
                }
            }
#if DEBUG
            PUtil.LogDebug("Added {0:D} options to spawn menu".F(options.Count));
#endif
            selector.options = options.ToArray();
            selector.filters = filters.ToArray();
            options.Recycle();
            filters.Recycle();
        }
示例#57
0
 void CategoryManager_CategoryAdded(object sender, Assets.CategoryManagerEventArgs e)
 {
     cbCategories.Items.Add(e.Category);
 }
        public int SaveAsset(string data)
        {
            NewAssetSave info;

            try
            {
                info = Newtonsoft.Json.JsonConvert.DeserializeObject <NewAssetSave>(data);
            }
            catch (Exception e)
            {
                return(-1);
            }

            LoginUser loginUser = TSAuthentication.GetLoginUser();
            Assets    assets    = new Assets(loginUser);
            Asset     asset     = assets.AddNewAsset();

            asset.OrganizationID     = TSAuthentication.OrganizationID;
            asset.Name               = info.Name;
            asset.ProductID          = info.ProductID;
            asset.ProductVersionID   = info.ProductVersionID;
            asset.SerialNumber       = info.SerialNumber;
            asset.WarrantyExpiration = DataUtils.DateToUtc(TSAuthentication.GetLoginUser(), info.WarrantyExpiration);
            asset.Notes              = info.Notes;
            //Location 1=assigned (shipped), 2=warehouse, 3=junkyard
            asset.Location = "2";

            asset.DateCreated  = DateTime.UtcNow;
            asset.DateModified = DateTime.UtcNow;
            asset.CreatorID    = loginUser.UserID;
            asset.ModifierID   = loginUser.UserID;

            asset.Collection.Save();

            string description = String.Format("Created asset {0} ", GetAssetReference(asset));

            ActionLogs.AddActionLog(TSAuthentication.GetLoginUser(), ActionLogType.Insert, ReferenceType.Assets, asset.AssetID, description);

            foreach (CustomFieldSaveInfo field in info.Fields)
            {
                CustomValue customValue = CustomValues.GetValue(TSAuthentication.GetLoginUser(), field.CustomFieldID, asset.AssetID);
                if (field.Value == null)
                {
                    customValue.Value = "";
                }
                else
                {
                    if (customValue.FieldType == CustomFieldType.DateTime)
                    {
                        customValue.Value = ((DateTime)field.Value).ToString();
                        //DateTime dt;
                        //if (DateTime.TryParse(((string)field.Value), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out dt))
                        //{
                        //    customValue.Value = dt.ToUniversalTime().ToString();
                        //}
                    }
                    else
                    {
                        customValue.Value = field.Value.ToString();
                    }
                }

                customValue.Collection.Save();
            }

            AssetHistory     history     = new AssetHistory(loginUser);
            AssetHistoryItem historyItem = history.AddNewAssetHistoryItem();

            historyItem.OrganizationID    = loginUser.OrganizationID;
            historyItem.Actor             = loginUser.UserID;
            historyItem.AssetID           = asset.AssetID;
            historyItem.ActionTime        = DateTime.UtcNow;
            historyItem.ActionDescription = "Asset created.";
            historyItem.ShippedFrom       = 0;
            historyItem.ShippedTo         = 0;
            historyItem.TrackingNumber    = string.Empty;
            historyItem.ShippingMethod    = string.Empty;
            historyItem.ReferenceNum      = string.Empty;
            historyItem.Comments          = string.Empty;

            history.Save();

            return(asset.AssetID);
        }
示例#59
0
 public StarMapView(StarMap gameObject, Assets assets)
 {
     _gameObject = gameObject;
     _assets = assets;
 }
示例#60
0
        public void Execute(IRocketPlayer caller, params string[] command)
        {
            if (!LIGHT.Instance.Configuration.Instance.EnableShop)
            {
                UnturnedChat.Say(caller, LIGHT.Instance.Translate("shop_disable"));
                return;
            }
            UnturnedPlayer player = (UnturnedPlayer)caller;

            if (command.Length == 0)
            {
                UnturnedChat.Say(player, LIGHT.Instance.Translate("buy_command_usage"));
                return;
            }

            byte   amttobuy    = 1;
            string Itemname    = "";
            byte   CheckItemID = 0;
            bool   IsID        = byte.TryParse(command[0], out CheckItemID);
            bool   IsAmtKeyed  = false;

            if (command.Length > 1)
            {
                IsAmtKeyed = byte.TryParse(command[command.Length - 1], out amttobuy);
            }
            for (int i = 0; i < (command.Length - 1); i++)
            {
                if (i == (command.Length - 2))
                {
                    Itemname += command[i];
                }
                else
                {
                    Itemname += command[i] + " ";
                }
            }
            if (!IsAmtKeyed)
            {
                amttobuy = 1;
                if (command.Length == 2)
                {
                    Itemname = command[0] + " " + command[1];
                }
                else if (command.Length == 1)
                {
                    Itemname = command[0];
                }
            }
            string[] components = Parser.getComponentsFromSerial(command[0], '.');
            if (components.Length == 2 && components[0] != "v")
            {
                UnturnedChat.Say(player, LIGHT.Instance.Translate("buy_command_usage"));
                return;
            }
            ushort id;

            switch (components[0])
            {
            case "v":
                if (!LIGHT.Instance.Configuration.Instance.CanBuyVehicles)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("buy_vehicles_off"));
                    return;
                }
                string name = "";
                if (!ushort.TryParse(components[1], out id))
                {
                    Asset[] array  = Assets.find(EAssetType.VEHICLE);
                    Asset[] array2 = array;
                    for (int i = 0; i < array2.Length; i++)
                    {
                        VehicleAsset vAsset = (VehicleAsset)array2[i];
                        if (vAsset != null && vAsset.Name != null && vAsset.Name.ToLower().Contains(components[1].ToLower()))
                        {
                            id   = vAsset.Id;
                            name = vAsset.Name;
                            break;
                        }
                    }
                }
                if (name == null && id == 0)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("could_not_find", components[1]));
                    return;
                }
                else if (name == null && id != 0)
                {
                    try
                    {
                        name = ((VehicleAsset)Assets.find(EAssetType.VEHICLE, id)).Name;
                    }
                    catch
                    {
                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("vehicle_invalid"));
                        return;
                    }
                }
                decimal cost    = LIGHT.Instance.ShopDB.GetVehicleCost(id);
                decimal balance = Uconomy.Instance.Database.GetBalance(player.Id);
                if (cost <= 0m)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("vehicle_not_available", name));
                    return;
                }
                if (balance < cost)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.DefaultTranslations.Translate("not_enough_currency_msg", Uconomy.Instance.Configuration.Instance.MoneyName, name));
                    return;
                }
                if (!player.GiveVehicle(id))
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("error_giving_item", name));
                    return;
                }
                decimal newbal = Uconomy.Instance.Database.IncreaseBalance(player.CSteamID.ToString(), (cost * -1));
                if (OnShopBuy != null)
                {
                    OnShopBuy(player, cost, 1, id, "vehicle");
                }
                player.Player.gameObject.SendMessage("ZaupShopOnBuy", new object[] { player, cost, amttobuy, id, "vehicle" }, SendMessageOptions.DontRequireReceiver);
                UnturnedChat.Say(player, LIGHT.Instance.Translate("vehicle_buy_msg", name, cost, Uconomy.Instance.Configuration.Instance.MoneyName, newbal, Uconomy.Instance.Configuration.Instance.MoneyName));
                break;

            default:
                if (!LIGHT.Instance.Configuration.Instance.CanBuyItems)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("buy_items_off"));
                    return;
                }
                name = null;
                if (!ushort.TryParse(Itemname, out id))
                {
                    Asset[] array  = Assets.find(EAssetType.ITEM);
                    Asset[] array2 = array;
                    for (int i = 0; i < array2.Length; i++)
                    {
                        ItemAsset vAsset = (ItemAsset)array2[i];
                        if (vAsset != null && vAsset.Name != null && vAsset.Name.ToLower().Contains(Itemname.ToLower()))
                        {
                            id   = vAsset.Id;
                            name = vAsset.Name;
                            break;
                        }
                    }
                }
                if (name == null && id == 0)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("could_not_find", Itemname));
                    return;
                }
                else if (name == null && id != 0)
                {
                    try
                    {
                        name = ((ItemAsset)Assets.find(EAssetType.ITEM, id)).Name;
                    }
                    catch
                    {
                        UnturnedChat.Say(player, LIGHT.Instance.Translate("item_invalid"));
                        return;
                    }
                }
                cost = decimal.Round(LIGHT.Instance.ShopDB.GetItemCost(id) * amttobuy, 2);
                if (LIGHT.Instance.Configuration.Instance.SaleEnable)
                {
                    decimal saleprice = Convert.ToDecimal(Convert.ToDouble(LIGHT.Instance.Configuration.Instance.SalePercentage) / 100.00);
                    if (LIGHT.Instance.sale.salesStart == true)
                    {
                        cost = decimal.Round((cost * (Convert.ToDecimal(1.00) - saleprice)), 2);
                    }
                }
                balance = Uconomy.Instance.Database.GetBalance(player.Id);
                if (cost <= 0m)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("item_not_available", name));
                    return;
                }
                if (balance < cost)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("not_enough_currency_msg", Uconomy.Instance.Configuration.Instance.MoneyName, amttobuy, name));
                    return;
                }
                player.GiveItem(id, amttobuy);
                string[] freeItem = LIGHT.Instance.Database.GetFreeItem(caller.Id);
                bool     free     = false;
                for (int x = 0; x < freeItem.Length; x++)
                {
                    if (freeItem[x].Trim() == id.ToString().Trim())
                    {
                        free = true;
                        cost = 0;
                        break;
                    }
                }
                newbal = Uconomy.Instance.Database.IncreaseBalance(player.Id, (cost * -1));
                if (OnShopBuy != null)
                {
                    OnShopBuy(player, cost, amttobuy, id);
                }
                player.Player.gameObject.SendMessage("ZaupShopOnBuy", new object[] { player, cost, amttobuy, id, "item" }, SendMessageOptions.DontRequireReceiver);
                if (free)
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("item_buy_freemsg", amttobuy, name, LIGHT.Instance.Database.CheckUserGroup(caller.Id)));
                }
                else
                {
                    UnturnedChat.Say(player, LIGHT.Instance.Translate("item_buy_msg", name, cost, Uconomy.Instance.Configuration.Instance.MoneyName, newbal, Uconomy.Instance.Configuration.Instance.MoneyName, amttobuy));
                }
                break;
            }
        }