Example #1
0
 protected ResourceLoader(string path, int cacheMb)
 {
     Path = path;
     Cache = new ResourceCache(cacheMb);
     Extractor = new ZipFile(path);
     BuildIndex();
 }
Example #2
0
 void Awake()
 {
     Instance = this;
     m_Food = Resources.Load( "Prefabs/Food" );
     m_Trap = Resources.Load( "Prefabs/Trap" );
     m_Trash = Resources.Load( "Prefabs/Trash" );
 }
Example #3
0
 public EditorScreen()
 {
     _spriteRenderer = new SpriteRenderer();
     _cache = new ResourceCache();
     _entities = new EntitySet();
     _generators = new Dictionary<string, IEntityGenerator>();
     RegisterGenerators();
 }
Example #4
0
 public void Unload(ResourceCache cache)
 {
     if (Texture2D != null)
     {
         Texture2D.Dispose();
         Texture2D = null;
     }
     IsLoaded = false;
 }
	public static void Initialize() {
		LevelManager = new LevelManager();
		PlayerManager = new PlayerManager();
		EnemyManager = new EnemyManager();
 		ResourceCache = (new GameObject()).AddComponent<ResourceCache>();
		EntityTemplateManager = new EntityTemplateManager();
		SoundManager = new SoundManager();
		StatsManager = new StatsManager();
	}
Example #6
0
 public void Load(ResourceCache resources, string mapFile)
 {
     var mapThread = LoadMap(mapFile).ContinueWith(
         task =>
         {
             var texPath = task.Result;
             if (!string.IsNullOrWhiteSpace(texPath))
                 _tex = resources.Load<Texture>(texPath);
         });
 }
Example #7
0
        public void MinMockTesting()
        {
            ResourceCache target = new ResourceCache();

            WriteToFile("mockData.txt", minMockData);

            target.AddAllInfo(minMockData);

            var result = target.GetAllInfoStartedWith(new DateTime(1999, 1, 1, 1, 1, 1, 1));

            WriteToFile("resultData.txt", result);
        }
Example #8
0
 public void Load(ResourceCache cache)
 {
     try
     {
         Texture2D = Texture2D.Load(XamlGraphicsDevice.Instance.ToolkitDevice, ResourceKey);
         IsLoaded = true;
     }
     catch (Exception ex)
     {
         IsLoaded = false;
         Debug.WriteLine("Unable to load Texture {0} - {1}", ResourceKey, ex.Message);
     }
 }
Example #9
0
        public Entity Generate(EntitySet set, ResourceCache cache, string entityName, Dictionary<string, object> parameters)
        {
            var e = set.Create(entityName);

            var visual = e.AddComponent<Sprite>();
            visual.Load(cache, "Data/Texture/tree.png");

            var clickArea = e.AddComponent<ClickArea>();
            clickArea.BaseWidth = 96;
            clickArea.BaseHeight = 96;

            return e;
        }
Example #10
0
        public ResourceCache CreateResourceCache()
        {
            //            var debug = GetDebugSettingValue();
            //            if (debug != "false")
            //            {
            //                var cache1 = new ResourceCache(TimeSpan.FromMilliseconds(CacheFactory.GetExpirationTime()));
            //
            //                new TreeCacheGarbageCollector(cache1, CacheFactory.GetArchiveDumpingTime(), resourceDumper);
            //
            //                var mock = ProfilingSamples.createHighLoadMockData();
            //
            //                cache1.AddAllInfo(mock);
            //
            //                return cache1;
            //            }

            var cache = new ResourceCache(TimeSpan.FromMilliseconds(CacheFactory.GetExpirationTime()));

            new TreeCacheGarbageCollector(cache, CacheFactory.GetArchiveDumpingTime(), resourceDumper);
            return cache;
        }
        private static bool ExtractResource(Sound Definition, HaloOnlineCacheContext CacheContext, IReadOnlyList <string> args)
        {
            if (args.Count != 1)
            {
                return(false);
            }

            var filePath = args[0];

            var resource = Definition.Resource;

            if (resource == null || resource.Page.Index < 0 || !resource.GetLocation(out var location))
            {
                Console.WriteLine("Resource is null.");
                return(false);
            }

            var cachePath = CacheContext.ResourceCacheNames[location];

            try
            {
                using (var stream = File.OpenRead(CacheContext.TagCacheFile.DirectoryName + "\\" + cachePath))
                {
                    var cache = new ResourceCache(stream);
                    using (var outStream = File.Open(filePath, FileMode.Create, FileAccess.Write))
                    {
                        cache.Decompress(stream, resource.Page.Index, resource.Page.CompressedBlockSize, outStream);
                        Console.WriteLine("Wrote 0x{0:X} bytes to {1}.", outStream.Position, filePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to extract resource: {0}", ex.Message);
            }

            return(true);
        }
Example #12
0
        // Token: 0x06000751 RID: 1873 RVA: 0x00040650 File Offset: 0x0003E850
        public static void Accept(PlayerController player, GameObject npc)
        {
            npc.GetComponent <tk2dSpriteAnimator>().PlayForDuration("do_effect", 2f, "idle", false);
            bool harderlotj = JammedSquire.NoHarderLotJ;

            if (harderlotj)
            {
                //npc.GetComponent<tk2dSpriteAnimator>().PlayForDuration("do_effect", -2f, "idle", false);
                string header2 = "Curse 2.0 Enabled";
                string text2   = "The Jammed show true potential.";
                JammedSquire.Notify(header2, text2);
                JammedSquire.NoHarderLotJ = false;
                player.PlayEffectOnActor(ResourceCache.Acquire("Global VFX/VFX_Curse") as GameObject, Vector3.zero, true, false, false);
            }
            else
            {
                //npc.GetComponent<tk2dSpriteAnimator>().PlayForDuration("do_effect", -2f, "idle", false);
                string header = "Curse 2.0 Disabled";
                string text   = "The Jammed hold back.";
                JammedSquire.Notify(header, text);
                JammedSquire.NoHarderLotJ = true;
            }
        }
        private void ProjectViewOpenProectClickHandler(ProjectsViewModel viewModel)
        {
            TextblockPanelName.Text = "Project Details";
            RoleCache.GetInstance().Clear();
            EmployeeCache.GetInstance().Clear();
            ResourceCache.GetInstance().Clear();
            CustomerCache.GetInstance().Clear();
            ProcessCache.GetInstance().Clear();
            ProjectCache.GetInstance().Clear();
            var resources = ResourceCache.GetInstance().Resources;

            resources = ResourceCache.GetInstance().UpdateAllQSizes();

            DataContext = new AddEditProjectViewModel
            {
                Project            = viewModel.SelectedProject,
                BackClickedHandler = AddEditProjectViewBackClickHandler,
                Customers          = CustomerCache.GetInstance().Customers,
                Processes          = new ObservableCollection <Process>(viewModel.SelectedProject.Processes),
                Resources          = resources.OrderByDescending(r => r.QSize).ToList <Resource>(),
                Employees          = EmployeeCache.GetInstance().Employees
            };
        }
Example #14
0
        static int _m_Recycle(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                ResourceCache gen_to_be_invoked = (ResourceCache)translator.FastGetCSObj(L, 1);



                {
                    AssetItem _item = (AssetItem)translator.GetObject(L, 2, typeof(AssetItem));

                    gen_to_be_invoked.Recycle(_item);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #15
0
 private void HandleHeal(float damage, bool fatal, HealthHaver enemy)
 {
     if (blobEnemies.Contains(enemy.aiActor.EnemyGuid) && fatal == true)
     {
         if (UnityEngine.Random.value < 0.05f)
         {
             PlayableCharacters characterIdentity = Owner.characterIdentity;
             if (characterIdentity != PlayableCharacters.Robot)
             {
                 Owner.PlayEffectOnActor(ResourceCache.Acquire("Global VFX/vfx_healing_sparkles_001") as GameObject, Vector3.zero, true, false, false);
                 Owner.healthHaver.ApplyHealing(0.5f);
             }
             else if (characterIdentity == PlayableCharacters.Robot)
             {
                 if (UnityEngine.Random.value < 0.5f)
                 {
                     Owner.PlayEffectOnActor(ResourceCache.Acquire("Global VFX/vfx_healing_sparkles_001") as GameObject, Vector3.zero, true, false, false);
                     Owner.healthHaver.Armor = Owner.healthHaver.Armor + 1;
                 }
             }
         }
     }
 }
Example #16
0
        void SpawnMutant(Vector3 pos, string name = "Mutant")
        {
            Node mutantNode = armyNode.CreateChild(name);

            mutantNode.Position = pos;
            mutantNode.SetScale(0.1f);
            var modelObject = mutantNode.CreateComponent <AnimatedModel>();

            modelObject.CastShadows = true;
            modelObject.Model       = ResourceCache.GetModel("Models/Mutant.mdl");
            modelObject.SetMaterial(ResourceCache.GetMaterial("Materials/mutant_M.xml"));
            mutantNode.CreateComponent <AnimationController>().Play(IdleAnimation, 0, true, 0.2f);

            // Create the CrowdAgent
            var agent = mutantNode.CreateComponent <CrowdAgent>();

            agent.Height = 0.2f;
            agent.NavigationPushiness = NavigationPushiness.Medium;
            agent.MaxSpeed            = 0.4f;
            agent.MaxAccel            = 0.4f;
            agent.Radius            = 0.03f;
            agent.NavigationQuality = NavigationQuality.High;
        }
Example #17
0
        void CreateLogo()
        {
            cache = ResourceCache;
            var logoTexture = cache.GetTexture2D("Textures/LogoLarge.png");

            if (logoTexture == null)
            {
                return;
            }

            ui                 = UI;
            logoSprite         = ui.Root.CreateSprite();
            logoSprite.Texture = logoTexture;
            int w = logoTexture.Width;
            int h = logoTexture.Height;

            logoSprite.SetScale(256.0f / w);
            logoSprite.SetSize(w, h);
            logoSprite.SetHotSpot(0, h);
            logoSprite.SetAlignment(HorizontalAlignment.Left, VerticalAlignment.Bottom);
            logoSprite.Opacity  = 0.75f;
            logoSprite.Priority = -100;
        }
Example #18
0
        void SetupInstructions()
        {
            var instructions = new Text()
            {
                Value = "Use WASD keys and mouse/touch to move",
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center
            };
            var font = ResourceCache.GetFont("Fonts/Anonymous Pro.ttf");

            instructions.SetFont(font, 15);
            UI.Root.AddChild(instructions);

            // Animating text
            Text text = new Text();

            text.Name = "animatingText";
            text.SetFont(font, 15);
            text.HorizontalAlignment = HorizontalAlignment.Center;
            text.VerticalAlignment   = VerticalAlignment.Center;
            text.SetPosition(0, UI.Root.Height / 4 + 20);
            UI.Root.AddChild(text);
        }
Example #19
0
        static int _m_PreLoad(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                ResourceCache gen_to_be_invoked = (ResourceCache)translator.FastGetCSObj(L, 1);



                {
                    string _assetPath = LuaAPI.lua_tostring(L, 2);

                    gen_to_be_invoked.PreLoad(_assetPath);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #20
0
        private static bool ExtractResource(ModelAnimationGraph Definition, HaloOnlineCacheContext CacheContext, IReadOnlyList <string> args)
        {
            int groupIndex = -1;

            if (!Int32.TryParse(args[0], out groupIndex))
            {
                return(false);
            }

            var filePath = args[1]; // warthog.raw

            if (groupIndex == -1)
            {
                Console.WriteLine("Resource is null.");
                return(false);
            }

            try
            {
                Definition.ResourceGroups[groupIndex].Resource.GetLocation(out var location);
                using (var stream = File.OpenRead(CacheContext.TagCacheFile.DirectoryName + "\\" + CacheContext.ResourceCacheNames[location]))
                {
                    var cache = new ResourceCache(stream);
                    using (var outStream = File.Open(filePath, FileMode.Create, FileAccess.Write))
                    {
                        cache.Decompress(stream, Definition.ResourceGroups[groupIndex].Resource.Page.Index, 0x7FFFFFFF, outStream);
                        Console.WriteLine("Wrote 0x{0:X} bytes to {1}.", outStream.Position, filePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to extract resource: {0}", ex.Message);
            }

            return(true);
        }
Example #21
0
        private async Task Create3DObject()
        {
            // Scene
            var scene = new Scene();

            scene.CreateComponent <Octree>();

            // Node (Rotation and Position)
            Node node = scene.CreateChild();

            node.Position = new Vector3(0, 0, 5);
            node.Rotation = new Quaternion(10, 60, 10);
            node.SetScale(1f);

            // Pyramid Model
            StaticModel modelObject = node.CreateComponent <StaticModel>();

            modelObject.Model = ResourceCache.GetModel("Models/Pyramid.mdl");

            // Light
            Node light = scene.CreateChild(name: "light");

            light.SetDirection(new Vector3(0.4f, -0.5f, 0.3f));
            light.CreateComponent <Light>();

            // Camera
            Node   cameraNode = scene.CreateChild(name: "camera");
            Camera camera     = cameraNode.CreateComponent <Camera>();

            // Viewport
            Renderer.SetViewport(0, new Viewport(scene, camera, null));

            // Action
            await node.RunActionsAsync(
                new RepeatForever(new RotateBy(duration: 1,
                                               deltaAngleX: 0, deltaAngleY: 90, deltaAngleZ: 0)));
        }
Example #22
0
 /// <summary> Loads an asset from the Resources of the Unity project </summary>
 /// <param name="pathInResourcesFolder"> a path like Colors/colorScheme1 in a Resource folder of
 /// your project and WITHOUT a file extension </param>
 /// <param name="forceAssetDbReimport"> If true will force the unity AssetDatabase to reload
 /// the asset if its already cached, only relevant in Editor, ignored in runtime </param>
 /// <returns></returns>
 public static T LoadV2 <T>(string pathInResourcesFolder, bool forceAssetDbReimport = false)
 {
     if (pathInResourcesFolder.IsNullOrEmpty())
     {
         throw new ArgumentNullException("pathInResourcesFolder null or emtpy");
     }
     if (forceAssetDbReimport)
     {
         ForceAssetDatabaseReimport(pathInResourcesFolder);
     }
     pathInResourcesFolder = RemovePathPrefixIfNeeded(pathInResourcesFolder);
     pathInResourcesFolder = RemoveExtensionIfNeeded(pathInResourcesFolder, ".prefab");
     pathInResourcesFolder = RemoveExtensionIfNeeded(pathInResourcesFolder, ".asset");
     if ((typeof(T).IsCastableTo <string>()))
     {
         TextAsset textAsset = LoadV2 <TextAsset>(pathInResourcesFolder, forceAssetDbReimport);
         if (textAsset == null)
         {
             throw new FileNotFoundException("No text asset found at " + pathInResourcesFolder);
         }
         return((T)(object)textAsset.text);
     }
     if ((typeof(MemoryStream).IsCastableTo <T>()))
     {
         TextAsset textAsset = LoadV2 <TextAsset>(pathInResourcesFolder, forceAssetDbReimport);
         if (textAsset == null)
         {
             throw new FileNotFoundException("No text asset found at " + pathInResourcesFolder);
         }
         return((T)(object)new MemoryStream(textAsset.bytes));
     }
     if (ResourceCache.TryLoad(pathInResourcesFolder, out T result))
     {
         return(result);
     }
     return((T)(object)Resources.Load(pathInResourcesFolder, typeof(T)));
 }
Example #23
0
        private void ExtractAnimationResource(string tagIndex, string cachePath, string dataPath, int permutationIndex)
        {
            var tag = ArgumentParser.ParseTagIndex(Info, tagIndex);
            int resourceIndex;
            ModelAnimationGraph animation;

            using (var tagsStream = Info.OpenCacheRead())
            {
                var tagContext = new TagSerializationContext(tagsStream, Info.Cache, Info.StringIDs, tag);
                animation = Info.Deserializer.Deserialize <ModelAnimationGraph>(tagContext);
            }

            try
            {
                using (var stream = File.OpenRead(Info.CacheFile.DirectoryName + "\\" + cachePath))
                {
                    var cache = new ResourceCache(stream);
                    using (var outStream = File.Open(dataPath, FileMode.Create, FileAccess.Write))
                    {
                        try
                        {
                            resourceIndex = animation.ResourceGroups[permutationIndex].Resource.Index;
                            cache.Decompress(stream, resourceIndex, 0xFFFFFFFF, outStream);
                            Console.WriteLine("Wrote 0x{0:X} bytes to {1}. Resource index: {2}, 0x{3}.", outStream.Position, dataPath, resourceIndex, resourceIndex.ToString("X"));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed to extract resource: {0}", ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to extract resource: {0}", ex.Message);
            }
        }
Example #24
0
        private GameServer(Configuration config)
            : base(config)
        {
            RegisterMappings();
            CommandManager = new CommandManager(this);
            CommandManager.Add(new ServerCommand())
            .Add(new ReloadCommand())
            .Add(new GameCommands())
            .Add(new BanCommands())
            .Add(new UnbanCommands())
            .Add(new UserkickCommand())
            .Add(new KickCommand())
            .Add(new AllkickCommand())
            .Add(new RoomkickCommand())
            .Add(new AdminCommands())
            .Add(new NoticeCommand())
            .Add(new WholeNoticeCommand())
            .Add(new ClanCommands())
            .Add(new InventoryCommands())
            .Add(new SearchCommand())
            .Add(new CommandWrapper())
            .Add(new HelpCommand());

            PlayerManager  = new PlayerManager();
            ResourceCache  = new ResourceCache();
            ChannelManager = new ChannelManager(ResourceCache.GetChannels());
            ClubManager    = new ClubManager(ResourceCache.GetClubs());

            _worker       = new ThreadLoop(TimeSpan.FromMilliseconds(100), Worker);
            _worker2      = new ThreadLoop(TimeSpan.FromSeconds(1), Worker2);
            _workerDelta  = new AccurateDelta(TimeSpan.Zero);
            _worker2Delta = new AccurateDelta(TimeSpan.Zero);

            _serverlistManager = new ServerlistMgr();
            AverageWorkerDelta.Enqueue(0);
            HighWorkerDelta.TryAdd(0, 0);
        }
Example #25
0
    protected virtual void Awake()
    {
        Application.targetFrameRate = targetFrameRate;

        ResourceCache.LoadAll(Literals.Common);
        ResourceCache.LoadAll(SceneManager.GetActiveScene().name);

        var rootCanvas = GameObject.Find(Literals.RootCanvas);

        if (rootCanvas == null)
        {
            rootCanvas = ResourceCache.Instantiate(Literals.RootCanvas);
        }

        if (GameObject.Find(Literals.MatchSound) == null)
        {
            ResourceCache.Instantiate(Literals.MatchSound);
        }

#if DISABLE_LOG
        if (Application.platform == RuntimePlatform.Android ||
            Application.platform == RuntimePlatform.IPhonePlayer)
        {
            Debug.logger.logEnabled = false;
        }
#endif

#if DISABLE_FPS
#else
        if (rootCanvas != null && GameObject.Find(Literals.FPSPanel) == null)
        {
            ResourceCache.Load(Literals.FPSPanel);
            var fpsPanel = ResourceCache.Instantiate(Literals.FPSPanel);
            fpsPanel.transform.SetParent(rootCanvas.transform, false);
        }
#endif
    }
Example #26
0
        /// <summary>
        /// Configures the default view service.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="options">The default view service options.</param>
        /// <exception cref="System.ArgumentNullException">
        /// factory
        /// or
        /// options
        /// </exception>
        /// <exception cref="System.InvalidOperationException">ViewService is already configured</exception>
        public static void ConfigureDefaultViewService(this IdentityServerServiceFactory factory,
                                                       DefaultViewServiceOptions options)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (factory.ViewService != null)
            {
                throw new InvalidOperationException("A ViewService is already configured");
            }

            factory.ViewService = new Registration <IViewService, DefaultViewService>();
            factory.Register(new Registration <DefaultViewServiceOptions>(options));

            if (options.ViewLoader == null)
            {
                options.ViewLoader = new Registration <IViewLoader, FileSystemWithEmbeddedFallbackViewLoader>();
            }

            if (options.CacheViews)
            {
                factory.Register(new Registration <IViewLoader>(options.ViewLoader, InnerRegistrationName));
                var cache = new ResourceCache();
                factory.Register(new Registration <IViewLoader>(
                                     resolver => new CachingLoader(cache, resolver.Resolve <IViewLoader>(InnerRegistrationName))));
            }
            else
            {
                factory.Register(options.ViewLoader);
            }
        }
Example #27
0
        protected override unsafe void Start()
        {
            UnhandledException += OnUnhandledException;
            Log.LogLevel        = LogLevel.Debug;

            base.Start();

            // Mutant
            mutantNode = Scene.CreateChild();
            mutantNode.SetScale(0.3f);
            mutantNode.Position = new Vector3(0, -0.5f, 1);

            var model = mutantNode.CreateComponent <AnimatedModel>();

            model.Model    = ResourceCache.GetModel("Models/Mutant.mdl");
            model.Material = ResourceCache.GetMaterial("Materials/mutant_M.xml");

            var animation = mutantNode.CreateComponent <AnimationController>();

            animation.Play("Animations/Mutant_HipHop1.ani", 0, true, 0.2f);

            Input.TouchBegin += OnTouchBegin;
            Input.TouchEnd   += OnTouchEnd;
        }
        public ProtoAntennaDevice(ProtoPartModuleSnapshot antenna, uint part_id, Vessel v)
        {
            if (!Features.Deploy)
            {
                has_ec = true;
            }
            else
            {
                has_ec = ResourceCache.Info(v, "ElectricCharge").amount > double.Epsilon;
            }

            if (Features.KCommNet)
            {
                this.antenna  = FlightGlobals.FindProtoPartByID(part_id).FindModule("ModuleDataTransmitter");
                this.animator = FlightGlobals.FindProtoPartByID(part_id).FindModule("ModuleDeployableAntenna");
            }
            else
            {
                this.antenna  = antenna;
                this.animator = FlightGlobals.FindProtoPartByID(part_id).FindModule("ModuleAnimationGroup");
            }
            this.part_id = part_id;
            vessel       = v;
        }
Example #29
0
        public override void OnResumed()
        {
            if (Scene == null)
            {
                var mdl = ResourceCache.GetModel(_modelName);
                CreateSimpleScene(mdl.BoundingBox.Size.Length * 4.0f);
                var node        = Scene.CreateChild();
                var staticModel = node.CreateComponent <StaticModel>();
                staticModel.Model = mdl;
                var z = Scene.GetOrCreateComponent <Zone>();
                z.FogColor           = Color.Blue;
                Camera.Node.Position = mdl.BoundingBox.Size * 2.0f;
                Camera.Node.LookAt(node.Position, Vector3.Up, TransformSpace.World);

                var light = Camera.Node.CreateChild();
                light.Position = Vector3.Up;
                var l = light.CreateComponent <Light>();
                l.Radius            = mdl.BoundingBox.Size.Length * 2.0f;
                l.LightType         = LightType.Point;
                NextInputSubscriber = new FreeCameraController(CameraNode);
            }

            base.OnResumed();
        }
Example #30
0
        static int _m_IsHaveAsset(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                ResourceCache gen_to_be_invoked = (ResourceCache)translator.FastGetCSObj(L, 1);



                {
                    string _assetPath = LuaAPI.lua_tostring(L, 2);

                    bool gen_ret = gen_to_be_invoked.IsHaveAsset(_assetPath);
                    LuaAPI.lua_pushboolean(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #31
0
 private void OnHitEnemy(Projectile bullet, SpeculativeRigidbody enemy, bool fatal)
 {
     if (bullet.Owner is PlayerController && (bullet.Owner as PlayerController).PlayerHasActiveSynergy("Parallel Lines"))
     {
         if (UnityEngine.Random.value <= 0.1f)
         {
             if (UnityEngine.Random.value <= 0.5f)
             {
                 GameObject silencerVFX = (GameObject)ResourceCache.Acquire("Global VFX/BlankVFX_Ghost");
                 AkSoundEngine.PostEvent("Play_OBJ_silenceblank_small_01", base.gameObject);
                 GameObject       gameObject                = new GameObject("silencer");
                 SilencerInstance silencerInstance          = gameObject.AddComponent <SilencerInstance>();
                 float            additionalTimeAtMaxRadius = 0.25f;
                 silencerInstance.TriggerSilencer(bullet.specRigidbody.UnitCenter, 25f, 5f, silencerVFX, 0f, 3f, 3f, 3f, 250f, 5f, additionalTimeAtMaxRadius, bullet.Owner as PlayerController, false, false);
             }
             else
             {
                 ExplosionData data = DataCloners.CopyExplosionData(StaticExplosionDatas.explosiveRoundsExplosion);
                 data.ignoreList.Add(bullet.ProjectilePlayerOwner().specRigidbody);
                 Exploder.Explode(bullet.specRigidbody.UnitCenter, data, Vector2.zero);
             }
         }
     }
 }
Example #32
0
        Slider CreateSlider(int x, int y, int xSize, int ySize, string text)
        {
            UIElement     root  = UI.Root;
            ResourceCache cache = ResourceCache;
            Font          font  = cache.GetFont("Fonts/Anonymous Pro.ttf");
            // Create text and slider below it
            Text sliderText = new Text();

            root.AddChild(sliderText);
            sliderText.SetPosition(x, y);
            sliderText.SetFont(font, 12);
            sliderText.Value = text;

            Slider slider = new Slider();

            root.AddChild(slider);
            slider.SetStyleAuto(null);
            slider.SetPosition(x, y + 20);
            slider.SetSize(xSize, ySize);
            // Use 0-1 range for controlling sound/music master volume
            slider.Range = 1.0f;

            return(slider);
        }
Example #33
0
        async void CreateScene()
        {
            var cache = ResourceCache;

            scene  = new Scene();
            octree = scene.CreateComponent <Octree>();

            plotNode = scene.CreateChild();

            var baseNode = plotNode.CreateChild().CreateChild();
            var plane    = baseNode.CreateComponent <StaticModel>();

            plane.Model = ResourceCache.GetModel("Models/Plane.mdl");

            var cameraNode = scene.CreateChild("camera");

            camera = cameraNode.CreateComponent <Camera>();
            cameraNode.Position = new Vector3(10, 15, 10) / 1.75f;
            cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);

            await plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 360, 360, 0)));

            movementsEnabled = true;
        }
Example #34
0
        public override void FixedUpdate()
        {
            if (FixGame(thisModule))
            {
                return;
            }

            hasEC = ResourceCache.Info(part.vessel, "ElectricCharge").amount > double.Epsilon;

            vessel_info vi;

            // get vessel info from the cache to verify if it is transmitting or relaying
            if (Cache.HasVesselInfo(part.vessel, out vi))
            {
                isTransmitting = (vi.transmitting.Length > 0 || vi.relaying.Length > 0);
            }

            if (GetIsActive())
            {
                part.ModulesOnUpdate();
                vessel_resources resources = ResourceCache.Get(part.vessel);
                if (!isTransmitting || isMoving)
                {
                    resources.Consume(part.vessel, "ElectricCharge", actualECCost * Kerbalism.elapsed_s);
                }
                // Just show the value on screen for antennaModule
                else
                {
                    actualECCost = antenna.cost;
                }
            }
            else
            {
                actualECCost = 0;
            }
        }
Example #35
0
        static int _m_PreLoadAsync(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                ResourceCache gen_to_be_invoked = (ResourceCache)translator.FastGetCSObj(L, 1);



                {
                    System.Collections.Generic.List <string> _assetPaths = (System.Collections.Generic.List <string>)translator.GetObject(L, 2, typeof(System.Collections.Generic.List <string>));
                    System.Action _okCall = translator.GetDelegate <System.Action>(L, 3);

                    gen_to_be_invoked.PreLoadAsync(_assetPaths, _okCall);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #36
0
        void CreateMovingBarrels(DynamicNavigationMesh navMesh)
        {
            Node        barrel = scene.CreateChild("Barrel");
            StaticModel model  = barrel.CreateComponent <StaticModel>();

            model.Model = ResourceCache.GetModel("Models/Cylinder.mdl");
            Material material = ResourceCache.GetMaterial("Materials/StoneTiled.xml");

            model.SetMaterial(material);
            material.SetTexture(TextureUnit.Diffuse, ResourceCache.GetTexture2D("Textures/TerrainDetail2.dds"));
            model.CastShadows = true;
            for (int i = 0; i < 20; ++i)
            {
                Node  clone = barrel.Clone(CreateMode.Replicated);
                float size  = 0.5f + NextRandom(1.0f);
                clone.Scale    = new Vector3(size / 1.5f, size * 2.0f, size / 1.5f);
                clone.Position = navMesh.FindNearestPoint(new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f), Vector3.One);
                CrowdAgent agent = clone.CreateComponent <CrowdAgent>();
                agent.Radius            = clone.Scale.X * 0.5f;
                agent.Height            = size;
                agent.NavigationQuality = NavigationQuality.Low;
            }
            barrel.Remove();
        }
Example #37
0
    void MakePoolOfGems()
    {
        var gemViews = new List <GemView>();

        foreach (GemType gemType in Enum.GetValues(typeof(GemType)))
        {
            if (gemType == GemType.Nil)
            {
                continue;
            }

            var countOfPool = 20;
            while (countOfPool > 0)
            {
                gemViews.Add(ResourceCache.Instantiate <GemView>(gemType.ToString()));
                countOfPool -= 1;
            }
        }

        foreach (var gemView in gemViews)
        {
            gemView.ReturnToPool(false);
        }
    }
Example #38
0
        static int _m_LoadAsync(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                ResourceCache gen_to_be_invoked = (ResourceCache)translator.FastGetCSObj(L, 1);



                {
                    string _assetPath = LuaAPI.lua_tostring(L, 2);
                    System.Action <AssetItem> _call = translator.GetDelegate <System.Action <AssetItem> >(L, 3);

                    gen_to_be_invoked.LoadAsync(_assetPath, _call);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #39
0
        protected override void Start()
        {
            base.Start();

            EnableGestureManipulation = true;

            mutantNode          = Scene.CreateChild();
            mutantNode.Position = new Vector3(0, 0, 1f);
            mutantNode.SetScale(0.1f);
            var mutant = mutantNode.CreateComponent <AnimatedModel>();

            mutant.Model = ResourceCache.GetModel("Models/Mutant.mdl");
            mutant.SetMaterial(ResourceCache.GetMaterial("Materials/mutant_M.xml"));
            animation = mutantNode.CreateComponent <AnimationController>();
            PlayAnimation(IdleAni);

            RegisterCortanaCommands(new Dictionary <string, Action>
            {
                //play animations using Cortana
                { "idle", () => PlayAnimation(IdleAni) },
                { "kill", () => PlayAnimation(KillAni) },
                { "hip hop", () => PlayAnimation(HipHopAni) },
                { "jump", () => PlayAnimation(JumpAni) },
                { "jump attack", () => PlayAnimation(JumpAttack) },
                { "kick", () => PlayAnimation(KickAni) },
                { "punch", () => PlayAnimation(PunchAni) },
                { "run", () => PlayAnimation(RunAni) },
                { "swipe", () => PlayAnimation(SwipeAni) },
                { "walk", () => PlayAnimation(WalkAni) },

                { "bigger", () => mutantNode.ScaleNode(1.2f) },
                { "smaller", () => mutantNode.ScaleNode(0.8f) },
                { "increase the brightness", () => IncreaseBrightness(1.2f) },
                { "decrease the brightness", () => IncreaseBrightness(0.8f) },
            });
        }
        private IEnumerator HandleTimer(AIActor self, float duration)
        {
            float elapsed = 0;

            while (elapsed < duration)
            {
                elapsed += BraveTime.DeltaTime;
                if (self.healthHaver.IsDead)
                {
                    yield break;
                }
                yield return(null);
            }
            if (self.healthHaver.IsDead)
            {
                yield break;
            }
            GameObject gameObject = (GameObject)ResourceCache.Acquire("Global VFX/VFX_Teleport_Beam");

            SpawnManager.SpawnVFX(gameObject, self.specRigidbody.UnitCenter, Quaternion.Euler(0, 0, 0));
            self.healthHaver.PreventAllDamage = false;
            self.EraseFromExistence(true);
            yield break;
        }
Example #41
0
File: UI.cs Project: corefan/urho
		public void LoadLayoutToElement(UIElement container, ResourceCache cache, string name)
		{
			UI_LoadLayoutToElement(Handle, container.Handle, cache.Handle, name);
		}
Example #42
0
File: UI.cs Project: Zamir7/urho
 public void LoadLayoutToElement(UIElement container, ResourceCache cache, string name)
 {
     Runtime.ValidateRefCounted(this);
     UI_LoadLayoutToElement(Handle, container.Handle, cache.Handle, name);
 }
Example #43
0
        public void HighLoadTesting()
        {
            int k = 0;
            ResourceCache target = new ResourceCache();

            target.AddAllInfo(mockData);
        }
Example #44
0
        private TaskStateInfo SubmitTask(TaskRunContext task, ResourceCache resourceCache)
        {
            TaskStateInfo taskStateInfo;

            lock (resourceCache.StateLock)
            {
                try
                {
                    bool nodesOverloaded = false;

                    var nodeStates = resourceCache.NodeStateInfo;
                    foreach (var nodeConfig in task.NodesConfig)
                    {
                        var nodeState = nodeStates.Single(n => n.NodeName == nodeConfig.NodeName);

                        if (nodeState.CoresAvailable <= nodeConfig.Cores)
                            nodesOverloaded = true;

                        nodeState.TasksSubmitted++;
                        nodeState.CoresReserved += nodeConfig.Cores;
                    }

                    if (nodesOverloaded)
                    {
                        Log.Error("Nodes overload for resource " + task.Resource.ResourceName);
                        throw new Exception("Wrong config for task " + task.TaskId.ToString() + ". Selected nodes are overloaded");
                    }

                    task.LocalId = task.Controller.Run(task);
                    taskStateInfo = new TaskStateInfo(TaskState.Started, task.LocalId.ToString());
                }
                catch (Exception e)
                {
                    RevokeTask(task, resourceCache);

                    Log.Error(String.Format("Unable to run task {1}: {2}{0}{3}", Environment.NewLine,
                        task.TaskId, e.Message, e.StackTrace
                    ));

                    throw;
                }
            }

            return taskStateInfo;
        }
Example #45
0
		void CreateLogo()
		{
			cache = ResourceCache;
			var logoTexture = cache.GetTexture2D("Textures/LogoLarge.png");

			if (logoTexture == null)
				return;

			ui = UI;
			logoSprite = ui.Root.CreateSprite();
			logoSprite.Texture = logoTexture;
			int w = logoTexture.Width;
			int h = logoTexture.Height;
			logoSprite.SetScale(256.0f / w);
			logoSprite.SetSize(w, h);
			logoSprite.SetHotSpot(0, h);
			logoSprite.SetAlignment(HorizontalAlignment.Left, VerticalAlignment.Bottom);
			logoSprite.Opacity = 0.75f;
			logoSprite.Priority = -100;
		}
Example #46
0
		public bool LoadXmlFromCache(ResourceCache cache, string file)
		{
			return Scene_LoadXMLFromCache(handle, cache.Handle, file);
		}
		/// <summary>
		/// Initialize the ResourceManager.
		/// </summary>
		public void Initialize(IRuntimeServices rs)
		{
			runtimeServices = rs;

			runtimeServices.Info(string.Format("Default ResourceManager initializing. ({0})", GetType()));

			ResourceLoader resourceLoader;

			AssembleResourceLoaderInitializers();

			for(int i = 0; i < sourceInitializerList.Count; i++)
			{
				ExtendedProperties configuration = (ExtendedProperties) sourceInitializerList[i];
				String loaderClass = configuration.GetString("class");

				if (loaderClass == null)
				{
					runtimeServices.Error(
						string.Format(
							"Unable to find '{0}.resource.loader.class' specification in configuration. This is a critical value.  Please adjust configuration.",
							configuration.GetString(RESOURCE_LOADER_IDENTIFIER)));
					continue;
				}

				resourceLoader = ResourceLoaderFactory.getLoader(runtimeServices, loaderClass);
				resourceLoader.CommonInit(runtimeServices, configuration);
				resourceLoader.Init(configuration);
				resourceLoaders.Add(resourceLoader);
			}

			// now see if this is overridden by configuration
			logWhenFound = runtimeServices.GetBoolean(RuntimeConstants.RESOURCE_MANAGER_LOGWHENFOUND, true);

			// now, is a global cache specified?
			String resourceManagerCacheClassName = runtimeServices.GetString(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS);
			Object o = null;

			if (resourceManagerCacheClassName != null && resourceManagerCacheClassName.Length > 0)
			{
				try
				{
					Type type = Type.GetType(resourceManagerCacheClassName);
					o = Activator.CreateInstance(type);
				}
				catch(System.Exception)
				{
					String err =
						string.Format(
							"The specified class for ResourceCache ({0}) does not exist (or is not accessible to the current classLoader).",
							resourceManagerCacheClassName);
					runtimeServices.Error(err);
					o = null;
				}

				if (!(o is ResourceCache))
				{
					String err =
						string.Format(
							"The specified class for ResourceCache ({0}) does not implement NVelocity.Runtime.Resource.ResourceCache. Using default ResourceCache implementation.",
							resourceManagerCacheClassName);
					runtimeServices.Error(err);
					o = null;
				}
			}

			// if we didn't get through that, just use the default.
			if (o == null)
			{
				o = new ResourceCacheImpl();
			}

			globalCache = (ResourceCache) o;
			globalCache.initialize(runtimeServices);
			runtimeServices.Info("Default ResourceManager initialization complete.");
		}
 public static ResourceCache CreateResourceCache(string path, int lifeTime, int gcInterval)
 {
     var result = new ResourceCache(new TimeSpan(0,0,0,0,lifeTime));
     var dumper = new DataDumper(path, "resource");
     var gc = new TreeCacheGarbageCollector(result,gcInterval,dumper);
     return result;
 }
	/// <summary> Initialize the ResourceManager. It is assumed
	/// that assembleSourceInitializers() has been
	/// called before this is run.
	/// </summary>
	public virtual void  initialize(RuntimeServices rs) {
	    rsvc = rs;

	    rsvc.info("Default ResourceManager initializing. (" + this.GetType() + ")");

	    ResourceLoader resourceLoader;

	    assembleResourceLoaderInitializers();

	    for (int i = 0; i < sourceInitializerList.Count; i++) {
		ExtendedProperties configuration = (ExtendedProperties) sourceInitializerList[i];
		System.String loaderClass = configuration.GetString("class");

		if (loaderClass == null) {
		    rsvc.error("Unable to find '" + configuration.GetString(RESOURCE_LOADER_IDENTIFIER) + ".resource.loader.class' specification in configuation." + " This is a critical value.  Please adjust configuration.");
		    continue;
		}

		resourceLoader = ResourceLoaderFactory.getLoader(rsvc, loaderClass);
		resourceLoader.commonInit(rsvc, configuration);
		resourceLoader.init(configuration);
		resourceLoaders.Add(resourceLoader);

	    }

	    /*
	    * now see if this is overridden by configuration
	    */

	    logWhenFound = rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.RESOURCE_MANAGER_LOGWHENFOUND, true);

	    /*
	    *  now, is a global cache specified?
	    */
	    System.String claz = rsvc.getString(NVelocity.Runtime.RuntimeConstants_Fields.RESOURCE_MANAGER_CACHE_CLASS);
	    System.Object o = null;

	    if (claz != null && claz.Length > 0) {
		try {
		    Type type = System.Type.GetType(claz);
		    o = System.Activator.CreateInstance(type);
		} catch (System.Exception cnfe) {
		    System.String err = "The specified class for ResourceCache (" + claz + ") does not exist (or is not accessible to the current classlaoder).";
		    rsvc.error(err);
		    o = null;
		}

		if (!(o is ResourceCache)) {
		    System.String err = "The specified class for ResourceCache (" + claz + ") does not implement NVelocity.Runtime.Resource.ResourceCache." + " Using default ResourceCache implementation.";
		    rsvc.error(err);
		    o = null;
		}
	    }

	    /*
	    *  if we didn't get through that, just use the default.
	    */
	    if (o == null) {
		o = new ResourceCacheImpl();
	    }

	    globalCache = (ResourceCache) o;
	    globalCache.initialize(rsvc);
	    rsvc.info("Default ResourceManager initialization complete.");
	}
 public void packageResources(ResourceCache resources, Report report)
 {
     throw new NotImplementedException();
 }
Example #51
0
        private void RevokeTask(TaskRunContext task, ResourceCache resourceCahce)
        {
            lock (resourceCahce.StateLock)
            {
                var nodeStates = resourceCahce.NodeStateInfo;
                foreach (var nodeConfig in task.NodesConfig)
                {
                    var nodeState = nodeStates.Single(n => n.NodeName == nodeConfig.NodeName);

                    nodeState.TasksSubmitted--;
                    nodeState.CoresReserved -= nodeConfig.Cores;

                    if (nodeState.TasksSubmitted < 0)
                    {
                        Log.Warn();
                        nodeState.TasksSubmitted = 0;
                    }

                    if (nodeState.CoresReserved < 0)
                    {
                        Log.Warn();
                        nodeState.CoresReserved = 0;
                    }
                }
            }
        }
Example #52
0
File: Scene.cs Project: Zamir7/urho
 public bool LoadXmlFromCache(ResourceCache cache, string file)
 {
     Runtime.ValidateRefCounted(this);
     return Scene_LoadXMLFromCache(handle, cache.Handle, file);
 }
Example #53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CachingLoader" /> class.
 /// </summary>
 /// <param name="cache">The cache.</param>
 /// <param name="inner">The inner.</param>
 public CachingLoader(ResourceCache cache, IViewLoader inner)
 {
     this.cache = cache;
     this.inner = inner;
 }
Example #54
0
 public void Load(ResourceCache resources, string textureName)
 {
     _tex = resources.Load<Texture>(textureName);
 }