public void DownloadItems(AsyncDownloader downloader, Action <string> setStatus)
        {
            this.downloader = downloader;
            DownloadMusicFiles();
            digPatcher = new SoundPatcher(ResourceList.DigSounds, "dig_", "step_cloth1");
            digPatcher.FetchFiles(digSoundsUri, altDigSoundsUri, this, DigSoundsExist);
            stepPatcher = new SoundPatcher(ResourceList.StepSounds, "step_", "classic jar");
            stepPatcher.FetchFiles(stepSoundsUri, altStepSoundsUri, this, StepSoundsExist);

            flags = 0;
            foreach (var entry in ResourceList.Files)
            {
                flags |= entry.Value;
            }

            if ((flags & ResourceList.cMask) != 0)
            {
                downloader.DownloadData(jarClassicUri, false, "classic_jar");
            }
            if ((flags & ResourceList.mMask) != 0)
            {
                downloader.DownloadData(jar162Uri, false, "162_jar");
            }
            if ((flags & ResourceList.gMask) != 0)
            {
                downloader.DownloadData(pngGuiPatchUri, false, "gui_patch");
            }
            if ((flags & ResourceList.tMask) != 0)
            {
                downloader.DownloadData(pngTerrainPatchUri, false, "terrain_patch");
            }
            SetFirstStatus(setStatus);
        }
        public void DownloadAsync()
        {
            AsyncDownloader downloader = new AsyncDownloader();
            string          url        = "http://localhost:51234/";
            string          expected   = "That's a nice string you have there";

            HttpListener listener = new HttpListener();

            listener.Prefixes.Add(url);
            listener.Start();

            listener.BeginGetContext(result =>
            {
                HttpListenerContext context = listener.EndGetContext(result);
                using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
                {
                    writer.Write(expected);
                    writer.Flush();
                }
            }, null);

            string actual = downloader.DownloadAsync(url).Result;

            listener.Stop();
            listener.Close();

            Assert.AreEqual(expected, actual);
        }
Пример #3
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            String Boundary = txtBoundary.Text;

            if (!string.IsNullOrEmpty(Boundary) && !string.IsNullOrWhiteSpace(Boundary))
            {
                // Parsing the boundary from string to boundary model.
                BoundaryModel bModel = osm.ParseOsmosis(Boundary);
                if (bModel != null)
                {
                    Tile leftBottom = Tile.CreateAroundLocation(bModel.left, bModel.bottom, Config.ZOOM);
                    Tile topRight   = Tile.CreateAroundLocation(bModel.top, bModel.right, Config.ZOOM);

                    var minX = Math.Min(leftBottom.X, topRight.X);
                    var maxX = Math.Max(leftBottom.X, topRight.X);
                    var minY = Math.Min(leftBottom.Y, topRight.Y);
                    var maxY = Math.Max(leftBottom.Y, topRight.Y);

                    // Defining tile area.
                    TileRange       range           = new TileRange(minX, minY, maxX, maxY, Config.ZOOM);
                    AsyncDownloader asyncDownloader = new AsyncDownloader(this);
                    asyncDownloader.Download(range);
                }
                else
                {
                }
            }
        }
Пример #4
0
        public void DownloadItems(AsyncDownloader downloader, Action <string> setStatus)
        {
            this.downloader = downloader;
            byte fetchFlags = ResourceList.GetFetchFlags();

            if ((fetchFlags & ResourceList.mask_classic) != 0)
            {
                QueueItem(jarClassicUri, "classic jar");
            }
            if ((fetchFlags & ResourceList.mask_modern) != 0)
            {
                QueueItem(jar162Uri, "1.6.2 jar");
            }
            if ((fetchFlags & ResourceList.mask_gui) != 0)
            {
                QueueItem(pngGuiPatchUri, "gui.png patch");
            }
            if ((fetchFlags & ResourceList.mask_terrain) != 0)
            {
                QueueItem(pngTerrainPatchUri, "terrain.png patch");
            }

            DownloadMusicFiles();
            digPatcher = new SoundPatcher(ResourceList.DigSounds, "dig_");
            digPatcher.FetchFiles(digSoundsUri, altDigSoundsUri, this, DigSoundsExist);
            stepPatcher = new SoundPatcher(ResourceList.StepSounds, "step_");
            stepPatcher.FetchFiles(stepSoundsUri, altStepSoundsUri, this, StepSoundsExist);

            setStatus(MakeNext());
        }
Пример #5
0
        protected async Task <string> DownloadHtml(string url)
        {
            var asyncDownloader  = new AsyncDownloader();
            var downloaderOutput = await asyncDownloader.GetString(url);

            return(downloaderOutput.DownloadOk ? downloaderOutput.Output : null);


            {
                //return new ParserResult(downloaderOutput.Output);
            }
            //            return new ParserResult(null).AddLog($"Nepodařilo se stažení hlavní stránky: '{url}'");
        }
        public void DownloadAsyncTimeout()
        {
            AsyncDownloader downloader = new AsyncDownloader();
            string          url        = "http://localhost:51234/";
            int             timeout    = 250;

            HttpListener listener = new HttpListener();

            listener.Prefixes.Add(url);
            listener.Start();

            Assert.That(async() => await downloader.DownloadAsync(url, timeout), Throws.InstanceOf <TaskCanceledException>());

            listener.Stop();
            listener.Close();
        }
Пример #7
0
 public void DownloadItems(AsyncDownloader downloader, Action <string> setStatus)
 {
     this.downloader = downloader;
     DownloadMusicFiles();
     digPatcher = new SoundPatcher(digSounds, "dig_",
                                   "step_cloth1", digPath);
     digPatcher.FetchFiles(digSoundsUri, altDigSoundsUri, this);
     stepPatcher = new SoundPatcher(stepSounds, "step_",
                                    "classic jar", stepPath);
     stepPatcher.FetchFiles(stepSoundsUri, altStepSoundsUri, this);
     if (!defaultZipExists)
     {
         downloader.DownloadData(jarClassicUri, false, "classic_jar");
         downloader.DownloadData(jar162Uri, false, "162_jar");
         downloader.DownloadData(pngTerrainPatchUri, false, "terrain_patch");
         downloader.DownloadData(pngGuiPatchUri, false, "gui_patch");
     }
     SetFirstStatus(setStatus);
 }
Пример #8
0
        public override void Dispose()
        {
            MapRenderer.Dispose();
            MapBordersRenderer.Dispose();
            EnvRenderer.Dispose();
            WeatherRenderer.Dispose();
            SetNewScreen(null);
            fpsScreen.Dispose();
            SelectionManager.Dispose();
            TerrainAtlas.Dispose();
            TerrainAtlas1D.Dispose();
            ModelCache.Dispose();
            Picking.Dispose();
            ParticleManager.Dispose();
            Players.Dispose();
            AsyncDownloader.Dispose();
            AudioPlayer.Dispose();
            AxisLinesRenderer.Dispose();

            Chat.Dispose();
            if (activeScreen != null)
            {
                activeScreen.Dispose();
            }
            Graphics.DeleteIb(defaultIb);
            Graphics.Dispose();
            Drawer2D.DisposeInstance();
            Animations.Dispose();
            Graphics.DeleteTexture(ref CloudsTexId);
            Graphics.DeleteTexture(ref RainTexId);
            Graphics.DeleteTexture(ref SnowTexId);
            Graphics.DeleteTexture(ref GuiTexId);
            Graphics.DeleteTexture(ref GuiClassicTexId);

            if (Options.HasChanged)
            {
                Options.Save();
            }
            base.Dispose();
        }
Пример #9
0
        private static IEnumerable <IListResultFileset> CreateResultSequence(IEnumerable <KeyValuePair <long, IParsedVolume> > filteredList, BackendManager backendManager, Options options)
        {
            List <IListResultFileset> list = new List <IListResultFileset>();

            foreach (KeyValuePair <long, IParsedVolume> entry in filteredList)
            {
                AsyncDownloader downloader = new AsyncDownloader(new IRemoteVolume[] { new RemoteVolume(entry.Value.File) }, backendManager);
                foreach (IAsyncDownloadedFile file in downloader)
                {
                    // We must obtain the partial/full status from the fileset file in the dlist files.
                    // Without this, the restore dialog will show all versions as full, or all versions
                    // as partial.  While the dlist files are already downloaded elsewhere, doing so again
                    // here is the most direct way to obtain the partial/full status without a major
                    // refactoring.  Since restoring directly from the backend files should be a relatively
                    // rare event, we can work on improving the performance later.
                    VolumeBase.FilesetData filesetData = VolumeReaderBase.GetFilesetData(entry.Value.CompressionModule, file.TempFile, options);
                    list.Add(new ListResultFileset(entry.Key, filesetData.IsFullBackup ? BackupType.FULL_BACKUP : BackupType.PARTIAL_BACKUP, entry.Value.Time.ToLocalTime(), -1, -1));
                }
            }

            return(list.ToArray());
        }
Пример #10
0
        private async void DownloadMp3Stream(FileRow fileRow)
        {
            fileRow.AddLog(string.Format("Zahájení stahování streamu: {0}", fileRow.UrlPage));

            var asyncDownloader = new AsyncDownloader();
            var output          = await asyncDownloader.GetData(fileRow.UrlMp3Download,
                                                                p =>
            {
                fileRow.Progress      = p.ProgressPercentage;
                fileRow.BytesReceived = p.BytesReceived;
                TotalProgress.UpdateProgress(Files);
            });

            if (output.DownloadOk)
            {
                SaveMp3(fileRow, output.Output);
            }
            else
            {
                fileRow.AddLog(string.Format("Chyba při stahování streamu: {0}.", output.Exception?.Message), FileRowState.Error);
            }
        }
Пример #11
0
        public async Task DownloadPart(string uri, string filename)
        {
            var progressReporter = _patcherContext.CreateProgressIndicator();

            var fileDirectory = Path.GetDirectoryName(filename);

            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }

            Task.Run(async() =>
            {
                await AsyncDownloader.DownloadFileWithCallbackAsync(uri, filename, (d, s) =>
                {
                    progressReporter.SetLeftText(Path.GetFileName(filename));
                    progressReporter.SetRightText(s);
                    progressReporter.SetProgressBar(d);
                }, true);
            }).Wait();

            progressReporter.SetIsIndeterminate(true);
            progressReporter.SetRightText(Properties.Resources.Decompressing);

            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite))
                using (var ms = new MemoryStream())
                {
                    fs.CopyTo(ms);
                    var buffer = ms.ToArray();
                    buffer = ZlibStream.UncompressBuffer(buffer);
                    fs.SetLength(buffer.Length);
                    fs.Position = 0;
                    fs.Write(buffer, 0, buffer.Length);
                    fs.Flush();
                }

            _patcherContext.DestroyProgressIndicator(progressReporter);
        }
Пример #12
0
        void CheckScheduledTasks(double time)
        {
            imageCheckAccumulator += time;
            ticksAccumulator      += time;
            cameraAccumulator     += time;

            if (imageCheckAccumulator > imageCheckPeriod)
            {
                imageCheckAccumulator -= imageCheckPeriod;
                AsyncDownloader.PurgeOldEntries(10);
            }

            int ticksThisFrame = 0;

            while (ticksAccumulator >= ticksPeriod)
            {
                Network.Tick(ticksPeriod);
                Players.Tick(ticksPeriod);
                ParticleManager.Tick(ticksPeriod);
                Animations.Tick(ticksPeriod);
                AudioPlayer.Tick(ticksPeriod);
                BlockHandRenderer.Tick(ticksPeriod);
                ticksThisFrame++;
                ticksAccumulator -= ticksPeriod;
            }

            while (cameraAccumulator >= cameraPeriod)
            {
                Camera.Tick(cameraPeriod);
                cameraAccumulator -= cameraPeriod;
            }

            if (ticksThisFrame > ticksFrequency / 3)
            {
                Utils.LogDebug("Falling behind (did {0} ticks this frame)", ticksThisFrame);
            }
        }
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     loader = new AsyncDownloader();
     loader.DataToDownload = AudioList.Cast<ItemToLoad>().ToList();
     loader.DataToDownload.ForEach(PrepareFilePath);
     loader.DownloadingComplete += new EventHandler(loader_DownloadingComplete);
     loader.ProgressChanged += new EventHandler(loader_ProgressChanged);
     prgOverall.Value = 0;
     loader.Download();
 }
Пример #14
0
        internal void OnLoad()
        {
                        #if ANDROID
            Graphics = new OpenGLESApi();
                        #elif !USE_DX
            Graphics = new OpenGLApi(window);
                        #else
            Graphics = new Direct3D9Api(window);
                        #endif
            Graphics.MakeApiInfo();
            ErrorHandler.ExtraInfo = Graphics.ApiInfo;

                        #if ANDROID
            Drawer2D = new CanvasDrawer2D(Graphics);
                        #else
            Drawer2D = new GdiPlusDrawer2D(Graphics);
                        #endif
            UpdateClientSize();

            Entities = new EntityList(this);
            TextureCache.Init();

                        #if SURVIVAL_TEST
            if (Options.GetBool(OptionsKey.SurvivalMode, false))
            {
                Mode = new SurvivalGameMode();
            }
            else
            {
                Mode = new CreativeGameMode();
            }
                        #endif

            Input           = new InputHandler(this);
            ParticleManager = new ParticleManager(); Components.Add(ParticleManager);
            TabList         = new TabList(); Components.Add(TabList);
            LoadOptions();
            LoadGuiOptions();
            Chat = new Chat(); Components.Add(Chat);

            Events.OnNewMap        += OnNewMapCore;
            Events.OnNewMapLoaded  += OnNewMapLoadedCore;
            Events.TextureChanged  += TextureChangedCore;
            Events.LowVRAMDetected += OnLowVRAMDetected;

            BlockInfo.Allocate(256);
            BlockInfo.Init();

            ModelCache = new ModelCache(this);
            ModelCache.InitCache();
            Downloader = new AsyncDownloader(Drawer2D); Components.Add(Downloader);
            Lighting   = new BasicLighting(); Components.Add(Lighting);

            Drawer2D.UseBitmappedChat = ClassicMode || !Options.GetBool(OptionsKey.UseChatFont, false);
            Drawer2D.BlackTextShadows = Options.GetBool(OptionsKey.BlackText, false);
            Graphics.Mipmaps          = Options.GetBool(OptionsKey.Mipmaps, false);

            Atlas1D.game  = this;
            Atlas2D.game  = this;
            Animations    = new Animations(); Components.Add(Animations);
            Inventory     = new Inventory(); Components.Add(Inventory);
            Inventory.Map = new BlockID[BlockInfo.Count];

            BlockInfo.SetDefaultPerms();
            World       = new World(this);
            LocalPlayer = new LocalPlayer(this); Components.Add(LocalPlayer);
            Entities.List[EntityList.SelfID] = LocalPlayer;

            MapRenderer        = new MapRenderer(this);
            ChunkUpdater       = new ChunkUpdater(this);
            EnvRenderer        = new EnvRenderer(); Components.Add(EnvRenderer);
            MapBordersRenderer = new MapBordersRenderer(); Components.Add(MapBordersRenderer);

            string renType = Options.Get(OptionsKey.RenderType, "normal");
            int    flags   = CalcRenderType(renType);
            if (flags == -1)
            {
                flags = 0;
            }

            MapBordersRenderer.legacy = (flags & 1) != 0;
            EnvRenderer.legacy        = (flags & 1) != 0;
            EnvRenderer.minimal       = (flags & 2) != 0;

            if (IPAddress == null)
            {
                Server = new Singleplayer.SinglePlayerServer(this);
            }
            else
            {
                Server = new Network.NetworkProcessor(this);
            }
            Components.Add(Server);
            Graphics.LostContextFunction = Server.Tick;

            Cameras.Add(new FirstPersonCamera(this));
            Cameras.Add(new ThirdPersonCamera(this, false));
            Cameras.Add(new ThirdPersonCamera(this, true));
            Camera = Cameras[0];
            UpdateProjection();

            Gui               = new GuiInterface(this); Components.Add(Gui);
            CommandList       = new CommandList(); Components.Add(CommandList);
            SelectionManager  = new SelectionManager(); Components.Add(SelectionManager);
            WeatherRenderer   = new WeatherRenderer(); Components.Add(WeatherRenderer);
            HeldBlockRenderer = new HeldBlockRenderer(); Components.Add(HeldBlockRenderer);

            Graphics.DepthTest = true;
            Graphics.DepthTestFunc(CompareFunc.LessEqual);
            //Graphics.DepthWrite = true;
            Graphics.AlphaBlendFunc(BlendFunc.SourceAlpha, BlendFunc.InvSourceAlpha);
            Graphics.AlphaTestFunc(CompareFunc.Greater, 0.5f);
            Culling           = new FrustumCulling();
            Picking           = new PickedPosRenderer(); Components.Add(Picking);
            AudioPlayer       = new AudioPlayer(); Components.Add(AudioPlayer);
            AxisLinesRenderer = new AxisLinesRenderer(); Components.Add(AxisLinesRenderer);
            SkyboxRenderer    = new SkyboxRenderer(); Components.Add(SkyboxRenderer);

            List <string> nonLoaded = PluginLoader.LoadAll(this);

            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].Init(this);
            }
            ExtractInitialTexturePack();
            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].Ready(this);
            }
            InitScheduledTasks();

            if (nonLoaded != null)
            {
                for (int i = 0; i < nonLoaded.Count; i++)
                {
                    Overlay warning = new PluginOverlay(this, nonLoaded[i]);
                    Gui.ShowOverlay(warning, false);
                }
            }

            LoadIcon();
            string connectString = "Connecting to " + IPAddress + ":" + Port + "..";
            if (Graphics.WarnIfNecessary(Chat))
            {
                MapBordersRenderer.UseLegacyMode(true);
                EnvRenderer.UseLegacyMode(true);
            }
            Gui.SetNewScreen(new LoadingScreen(this, connectString, ""));
            Server.BeginConnect();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string file = string.Empty;
            foreach (UserVideo video in VideoList)
            {
                string containerPath = string.Empty;

                if (!string.IsNullOrEmpty(video.PlayerUrl))
                {
                    containerPath = video.PlayerUrl;
                    file = System.IO.Path.Combine((Application.Current as App).AppFolder, "Video",
                                                       System.IO.Path.GetFileName(video.Title));
                }
                else
                {
                    containerPath = video.Image;
                    file = System.IO.Path.Combine((Application.Current as App).AppFolder, "Video",
                                                    System.IO.Path.GetFileName(containerPath));
                }

                if (System.IO.File.Exists(file))
                    System.IO.File.Delete(file);

                string url = Utils.VideoDownloadHelper.FindFirst(containerPath, "src=\"", "\"");
                if (string.IsNullOrEmpty(url))
                    url = video.PlayerUrl;
                string videoPath = Utils.VideoDownloadHelper.GetVideo(url);

                //Check if this video hosted on YouTube
                if (videoPath.ToLower().Contains("assets/videos/.vk"))
                {
                    video.State = LoadState.Fail;
                    continue;
                }

                if (!string.IsNullOrEmpty(videoPath))
                    file = string.Format("{0}{1}", file, System.IO.Path.GetExtension(videoPath));

                video.Url = videoPath;
                video.PathToSave = file;
            }

            loader = new AsyncDownloader();
            loader.DownloadingComplete += new EventHandler(loader_DownloadingComplete);
            loader.ProgressChanged += new EventHandler(loader_ProgressChanged);

            loader.DataToDownload = VideoList.Cast<ItemToLoad>().Where((load) => load.State == LoadState.None).ToList();
            loader.Download();
        }
Пример #16
0
        private void Download(List <PatchFileInfo> files)
        {
            // Log the beginning of the download
            Log.Info(Properties.Resources.BeginningDownload);

            _patcherContext.UpdateMainProgress(Properties.Resources.BeginningDownload, isIndeterminate: true,
                                               isProgressbarVisible: true);

            // create the actions that will run in parrallel
            var list = new List <Action>();

            var completed   = 0;
            int failedCount = 0;

            foreach (var patchFileInfo in files)
            {
                var ftpAddress = OfficialPatchInfo.MainFtp;
                if (!ftpAddress.EndsWith("/"))
                {
                    ftpAddress += "/";
                }

                // Im kinda stuck on how I wanna do this haha

                //var downloader = new FileDownloader(new ProgressReporterViewModel(), patchFileInfo.RemoteName,
                //    patchFileInfo.Filename, patchFileInfo.Size, CancellationToken.None);

                list.Add(() =>
                {
                    try
                    {
                        var progressIndicator = _patcherContext.CreateProgressIndicator();

                        var fileDirectory = Path.GetDirectoryName(Path.Combine(PatchInfo.PatchName, patchFileInfo.Filename));

                        if (!Directory.Exists(fileDirectory))
                        {
                            Directory.CreateDirectory(fileDirectory);
                        }

                        Task.Run(async() =>
                        {
                            await AsyncDownloader.DownloadFileWithCallbackAsync(string.Concat(ftpAddress, PatchInfo.EndVersion, "/",
                                                                                              patchFileInfo.RemoteName),
                                                                                Path.Combine(PatchInfo.PatchName, patchFileInfo.Filename), (d, s) =>
                            {
                                progressIndicator.SetLeftText(Path.GetFileName(patchFileInfo.Filename));
                                progressIndicator.SetRightText(s);
                                progressIndicator.SetProgressBar(d);
                            });
                        }).Wait();

                        _patcherContext.DestroyProgressIndicator(progressIndicator);
                    }
                    catch (Exception ex)
                    {
                        Log.Exception(ex);
                        Interlocked.Increment(ref failedCount);
                    }
                    finally
                    {
                        Interlocked.Increment(ref completed);

                        _patcherContext.UpdateMainProgress(Properties.Resources.DownloadingFiles,
                                                           $"{completed}/{files.Count}", completed / (double)files.Count * 100.0,
                                                           isProgressbarVisible: true);
                    }
                });
            }

            Parallel.Invoke(new ParallelOptions {
                MaxDegreeOfParallelism = 10
            }, list.ToArray());

            Log.Info(Properties.Resources.DownloadComplete);

            _patcherContext.UpdateMainProgress(Properties.Resources.DownloadComplete);
        }
Пример #17
0
        internal void OnLoad()
        {
            Mouse    = window.Mouse;
            Keyboard = window.Keyboard;

                        #if ANDROID
            Graphics = new OpenGLESApi();
                        #elif !USE_DX
            Graphics = new OpenGLApi();
                        #else
            Graphics = new Direct3D9Api(this);
                        #endif
            Graphics.MakeApiInfo();
            ErrorHandler.AdditionalInfo = Graphics.ApiInfo;

                        #if ANDROID
            Drawer2D = new CanvasDrawer2D(Graphics);
                        #else
            Drawer2D = new GdiPlusDrawer2D(Graphics);
                        #endif

            Entities = new EntityList(this);
            AcceptedUrls.Load();
            DeniedUrls.Load();
            ETags.Load();
            LastModified.Load();

            if (Options.GetBool(OptionsKey.SurvivalMode, false))
            {
                Mode = new SurvivalGameMode();
            }
            else
            {
                Mode = new CreativeGameMode();
            }
            Components.Add(Mode);

            Input           = new InputHandler(this);
            defaultIb       = Graphics.MakeDefaultIb();
            ParticleManager = new ParticleManager(); Components.Add(ParticleManager);
            TabList         = new TabList(); Components.Add(TabList);
            LoadOptions();
            LoadGuiOptions();
            Chat = new Chat(); Components.Add(Chat);

            WorldEvents.OnNewMap       += OnNewMapCore;
            WorldEvents.OnNewMapLoaded += OnNewMapLoadedCore;
            Events.TextureChanged      += TextureChangedCore;

            BlockInfo.Init();
            ModelCache = new ModelCache(this);
            ModelCache.InitCache();
            AsyncDownloader = new AsyncDownloader(Drawer2D); Components.Add(AsyncDownloader);
            Lighting        = new BasicLighting(); Components.Add(Lighting);

            Drawer2D.UseBitmappedChat = ClassicMode || !Options.GetBool(OptionsKey.UseChatFont, false);
            Drawer2D.BlackTextShadows = Options.GetBool(OptionsKey.BlackText, false);
            Graphics.Mipmaps          = Options.GetBool(OptionsKey.Mipmaps, false);

            TerrainAtlas1D = new TerrainAtlas1D(this);
            TerrainAtlas   = new TerrainAtlas2D(this);
            Animations     = new Animations(); Components.Add(Animations);
            Inventory      = new Inventory(); Components.Add(Inventory);

            BlockInfo.SetDefaultPerms();
            World       = new World(this);
            LocalPlayer = new LocalPlayer(this); Components.Add(LocalPlayer);
            Entities.List[EntityList.SelfID] = LocalPlayer;
            Width = window.Width; Height = window.Height;

            MapRenderer = new MapRenderer(this);
            string renType = Options.Get(OptionsKey.RenderType) ?? "normal";
            if (!SetRenderType(renType))
            {
                SetRenderType("normal");
            }

            if (IPAddress == null)
            {
                Server = new Singleplayer.SinglePlayerServer(this);
            }
            else
            {
                Server = new Network.NetworkProcessor(this);
            }
            Graphics.LostContextFunction = Server.Tick;

            Cameras.Add(new FirstPersonCamera(this));
            Cameras.Add(new ThirdPersonCamera(this, false));
            Cameras.Add(new ThirdPersonCamera(this, true));
            Camera = Cameras[0];
            UpdateProjection();

            Gui               = new GuiInterface(this); Components.Add(Gui);
            CommandList       = new CommandList(); Components.Add(CommandList);
            SelectionManager  = new SelectionManager(); Components.Add(SelectionManager);
            WeatherRenderer   = new WeatherRenderer(); Components.Add(WeatherRenderer);
            HeldBlockRenderer = new HeldBlockRenderer(); Components.Add(HeldBlockRenderer);

            Graphics.DepthTest = true;
            Graphics.DepthTestFunc(CompareFunc.LessEqual);
            //Graphics.DepthWrite = true;
            Graphics.AlphaBlendFunc(BlendFunc.SourceAlpha, BlendFunc.InvSourceAlpha);
            Graphics.AlphaTestFunc(CompareFunc.Greater, 0.5f);
            Culling           = new FrustumCulling();
            Picking           = new PickedPosRenderer(); Components.Add(Picking);
            AudioPlayer       = new AudioPlayer(); Components.Add(AudioPlayer);
            AxisLinesRenderer = new AxisLinesRenderer(); Components.Add(AxisLinesRenderer);
            SkyboxRenderer    = new SkyboxRenderer(); Components.Add(SkyboxRenderer);

            plugins = new PluginLoader(this);
            List <string> nonLoaded = plugins.LoadAll();

            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].Init(this);
            }
            ExtractInitialTexturePack();
            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].Ready(this);
            }
            InitScheduledTasks();

            if (nonLoaded != null)
            {
                for (int i = 0; i < nonLoaded.Count; i++)
                {
                    plugins.MakeWarning(this, nonLoaded[i]);
                }
            }

            window.LoadIcon();
            string connectString = "Connecting to " + IPAddress + ":" + Port + "..";
            if (Graphics.WarnIfNecessary(Chat))
            {
                MapBordersRenderer.UseLegacyMode(true);
                EnvRenderer.UseLegacyMode(true);
            }
            Gui.SetNewScreen(new LoadingMapScreen(this, connectString, ""));
            Server.Connect(IPAddress, Port);
        }
Пример #18
0
        public void Run()
        {
            Window = Factory.CreateWindow(640, 400, Program.AppName,
                                          GraphicsMode.Default, DisplayDevice.Default);
            Window.Visible = true;
            Drawer         = new GdiPlusDrawer2D();
            UpdateClientSize();

            Init();
            TryLoadTexturePack();
            platformDrawer.window = Window;
            platformDrawer.Init();

            Downloader = new AsyncDownloader(Drawer);
            Downloader.Init("");
            Downloader.Cookies   = new CookieContainer();
            Downloader.KeepAlive = true;

            fetcher = new ResourceFetcher();
            fetcher.CheckResourceExistence();
            checkTask = new UpdateCheckTask();
            checkTask.RunAsync(this);

            if (!fetcher.AllResourcesExist)
            {
                SetScreen(new ResourcesScreen(this));
            }
            else
            {
                SetScreen(new MainScreen(this));
            }

            while (true)
            {
                Window.ProcessEvents();
                if (!Window.Exists)
                {
                    break;
                }
                if (ShouldExit)
                {
                    if (Screen != null)
                    {
                        Screen.Dispose();
                        Screen = null;
                    }
                    break;
                }

                checkTask.Tick();
                Screen.Tick();
                if (Dirty)
                {
                    Display();
                }
                Thread.Sleep(10);
            }

            if (Options.Load())
            {
                LauncherSkin.SaveToOptions();
                Options.Save();
            }

            if (ShouldUpdate)
            {
                Updater.Applier.ApplyUpdate();
            }
            if (Window.Exists)
            {
                Window.Close();
            }
        }
Пример #19
0
        protected override void OnLoad(EventArgs e)
        {
                        #if !USE_DX
            Graphics = new OpenGLApi();
                        #else
            Graphics = new Direct3D9Api(this);
                        #endif
            Graphics.MakeGraphicsInfo();
            Players = new EntityList(this);

            Options.Load();
            AcceptedUrls.Load(); DeniedUrls.Load();
            ViewDistance     = Options.GetInt(OptionsKey.ViewDist, 16, 4096, 512);
            UserViewDistance = ViewDistance;
            CameraClipping   = Options.GetBool(OptionsKey.CameraClipping, true);
            InputHandler     = new InputHandler(this);
            Chat             = new ChatLog(this);
            ParticleManager  = new ParticleManager(this);
            HudScale         = Options.GetFloat(OptionsKey.HudScale, 0.25f, 5f, 1f);
            ChatScale        = Options.GetFloat(OptionsKey.ChatScale, 0.35f, 5f, 1f);
            defaultIb        = Graphics.MakeDefaultIb();
            MouseSensitivity = Options.GetInt(OptionsKey.Sensitivity, 1, 100, 30);
            UseClassicGui    = Options.GetBool(OptionsKey.UseClassicGui, false);
            BlockInfo        = new BlockInfo();
            BlockInfo.Init();
            ChatLines     = Options.GetInt(OptionsKey.ChatLines, 1, 30, 12);
            ClickableChat = Options.GetBool(OptionsKey.ClickableChat, true);
            ModelCache    = new ModelCache(this);
            ModelCache.InitCache();
            AsyncDownloader           = new AsyncDownloader(skinServer);
            Drawer2D                  = new GdiPlusDrawer2D(Graphics);
            Drawer2D.UseBitmappedChat = !Options.GetBool(OptionsKey.ArialChatFont, false);
            ViewBobbing               = Options.GetBool(OptionsKey.ViewBobbing, false);
            ShowBlockInHand           = Options.GetBool(OptionsKey.ShowBlockInHand, true);
            InvertMouse               = Options.GetBool(OptionsKey.InvertMouse, false);
            SimpleArmsAnim            = Options.GetBool(OptionsKey.SimpleArmsAnim, false);

            TerrainAtlas1D = new TerrainAtlas1D(Graphics);
            TerrainAtlas   = new TerrainAtlas2D(Graphics, Drawer2D);
            Animations     = new Animations(this);
            defTexturePack = Options.Get(OptionsKey.DefaultTexturePack) ?? "default.zip";
            TexturePackExtractor extractor = new TexturePackExtractor();
            extractor.Extract("default.zip", this);
            // in case the user's default texture pack doesn't have all required textures
            if (defTexturePack != "default.zip")
            {
                extractor.Extract(DefaultTexturePack, this);
            }
            Inventory = new Inventory(this);

            BlockInfo.SetDefaultBlockPermissions(Inventory.CanPlace, Inventory.CanDelete);
            Map                = new Map(this);
            LocalPlayer        = new LocalPlayer(this);
            Players[255]       = LocalPlayer;
            width              = Width;
            height             = Height;
            MapRenderer        = new MapRenderer(this);
            MapBordersRenderer = new MapBordersRenderer(this);
            EnvRenderer        = new StandardEnvRenderer(this);
            if (IPAddress == null)
            {
                Network = new Singleplayer.SinglePlayerServer(this);
            }
            else
            {
                Network = new NetworkProcessor(this);
            }
            Graphics.LostContextFunction = Network.Tick;

            firstPersonCam        = new FirstPersonCamera(this);
            thirdPersonCam        = new ThirdPersonCamera(this);
            forwardThirdPersonCam = new ForwardThirdPersonCamera(this);
            Camera          = firstPersonCam;
            FieldOfView     = Options.GetInt(OptionsKey.FieldOfView, 1, 150, 70);
            ZoomFieldOfView = FieldOfView;
            UpdateProjection();
            CommandManager = new CommandManager();
            CommandManager.Init(this);
            SelectionManager = new SelectionManager(this);
            WeatherRenderer  = new WeatherRenderer(this);
            WeatherRenderer.Init();
            BlockHandRenderer = new BlockHandRenderer(this);
            BlockHandRenderer.Init();

            FpsLimitMethod method = Options.GetEnum(OptionsKey.FpsLimit, FpsLimitMethod.LimitVSync);
            SetFpsLimitMethod(method);
            Graphics.DepthTest = true;
            Graphics.DepthTestFunc(CompareFunc.LessEqual);
            //Graphics.DepthWrite = true;
            Graphics.AlphaBlendFunc(BlendFunc.SourceAlpha, BlendFunc.InvSourceAlpha);
            Graphics.AlphaTestFunc(CompareFunc.Greater, 0.5f);
            fpsScreen = new FpsScreen(this);
            fpsScreen.Init();
            hudScreen = new HudScreen(this);
            hudScreen.Init();
            Culling = new FrustumCulling();
            EnvRenderer.Init();
            MapBordersRenderer.Init();
            Picking           = new PickingRenderer(this);
            AudioPlayer       = new AudioPlayer(this);
            LiquidsBreakable  = Options.GetBool(OptionsKey.LiquidsBreakable, false);
            AxisLinesRenderer = new AxisLinesRenderer(this);

            LoadIcon();
            string connectString = "Connecting to " + IPAddress + ":" + Port + "..";
            Graphics.WarnIfNecessary(Chat);
            SetNewScreen(new LoadingMapScreen(this, connectString, "Waiting for handshake"));
            Network.Connect(IPAddress, Port);
        }