Пример #1
0
        public DarkKn5ObjectRenderer(CarDescription car, string showroomKn5 = null) : base(car, showroomKn5)
        {
            // UseMsaa = true;
            VisibleUi           = false;
            UseSprite           = false;
            AllowSkinnedObjects = true;

            if (showroomKn5 != null)
            {
                _showroom         = true;
                CubemapReflection = true;
            }

            //BackgroundColor = Color.FromArgb(10, 15, 25);
            //BackgroundColor = Color.FromArgb(220, 140, 100);

            BackgroundColor      = Color.FromArgb(220, 220, 220);
            BackgroundBrightness = showroomKn5 == null ? 1f : 2f;
            EnableShadows        = EffectDarkMaterial.EnableShadows;

#if DEBUG
            //FlatMirror = true;
            //FlatMirrorBlurred = true;
            //ReflectionPower = 1.0f;
            //EnablePcssShadows = true;
            //UseSsao = true;
#endif
        }
            internal CarSlot([NotNull] ForwardKn5ObjectRenderer renderer, [CanBeNull] CarDescription car, int?id)
            {
                Id = id ?? ++_id;

                _renderer  = renderer;
                _car       = car;
                CarWrapper = new RenderableList();
            }
Пример #3
0
        private static DarkKn5ObjectRenderer CreateRenderer([NotNull] string acRoot, [NotNull] DarkPreviewsOptions options,
                                                            [CanBeNull] CarDescription initialCar, [CanBeNull] string initialSkinId)
        {
            var renderer = new DarkKn5ObjectRenderer(initialCar, GetShowroomKn5(acRoot, options.Showroom))
            {
                LoadCarLights      = true,
                LoadShowroomLights = true
            };

            SetRendererOptions(acRoot, renderer, options);
            renderer.SelectSkin(initialSkinId);
            renderer.Initialize();
            SetRendererCarOptions(renderer, options);
            return(renderer);
        }
Пример #4
0
        public static async Task UpdateKn5(this Kn5 kn5, BaseRenderer renderer = null, CarSkinObject skin = null)
        {
            if (kn5.MaterialLoader != DefaultKn5MaterialLoader.Instance || kn5.NodeLoader != DefaultKn5NodeLoader.Instance)
            {
                throw new Exception("Can’t save KN5 loaded unusually");
            }

            var backup = kn5.OriginalFilename + ".backup";

            try {
                if (!File.Exists(backup))
                {
                    FileUtils.HardLinkOrCopy(kn5.OriginalFilename, backup);
                }
            } catch (Exception e) {
                Logging.Warning(e);
            }

            await Task.Run(() => {
                using (var f = FileUtils.RecycleOriginal(kn5.OriginalFilename)) {
                    try {
                        if (kn5.TextureLoader == DefaultKn5TextureLoader.Instance)
                        {
                            kn5.Save(f.Filename);
                        }
                        else
                        {
                            Logging.Debug("Extra special mode for saving KN5s without textures loaded");
                            kn5.Save(f.Filename, new ExistingKn5Textures(kn5.OriginalFilename));
                        }
                    } catch {
                        FileUtils.TryToDelete(f.Filename);
                        throw;
                    }
                }
            });

            if (renderer != null)
            {
                var car  = skin == null ? null : CarsManager.Instance.GetById(skin.CarId);
                var slot = (renderer as ToolsKn5ObjectRenderer)?.MainSlot;
                if (car != null && slot != null)
                {
                    slot.SetCar(CarDescription.FromKn5(kn5, car.Location, car.AcdData));
                    slot.SelectSkin(skin.Id);
                }
            }
        }
Пример #5
0
        private static async Task <IReadOnlyList <UpdatePreviewError> > Run([NotNull] CarObject car, [CanBeNull] string skinId,
                                                                            [CanBeNull] IReadOnlyList <ToUpdatePreview> toUpdate, [CanBeNull] string presetFilename)
        {
            var carKn5 = FileUtils.GetMainCarFilename(car.Location, car.AcdData);

            if (!File.Exists(carKn5))
            {
                ModernDialog.ShowMessage("Model not found");
                return(null);
            }

            await PrepareAsync();

            Kn5 kn5;

            using (var waiting = new WaitingDialog()) {
                waiting.Report("Loading model…");
                kn5 = await Task.Run(() => Kn5.FromFile(carKn5));
            }

            using (var renderer = new DarkKn5ObjectRenderer(CarDescription.FromKn5(kn5, car.Location, car.AcdData))
            {
                AutoRotate = false,
                AutoAdjustTarget = false,
                AsyncTexturesLoading = true,
                AsyncOverridesLoading = true,
                AutoloadCarLights = false,
                AutoloadShowroomLights = false
            }) {
                var wrapper = new CmPreviewsFormWrapper(car, renderer, skinId, presetFilename);

                if (toUpdate != null)
                {
                    wrapper.SetToUpdate(toUpdate);
                }

                wrapper.Form.Icon = AppIconService.GetAppIcon();
                wrapper.Run();

                return(wrapper.GetErrors());
            }
        }
Пример #6
0
        public static async Task UpdateKn5(this IKn5 kn5, BaseRenderer renderer = null, CarSkinObject skin = null)
        {
            if (!kn5.IsEditable)
            {
                throw new Exception("Can’t save KN5 loaded unusually");
            }

            var backup = kn5.OriginalFilename + ".backup";

            try {
                if (!File.Exists(backup))
                {
                    FileUtils.HardLinkOrCopy(kn5.OriginalFilename, backup);
                }
            } catch (Exception e) {
                Logging.Warning(e);
            }

            await Task.Run(() => {
                using (var f = FileUtils.RecycleOriginal(kn5.OriginalFilename)) {
                    try {
                        kn5.Save(f.Filename);
                    } catch {
                        FileUtils.TryToDelete(f.Filename);
                        throw;
                    }
                }
            });

            if (renderer != null)
            {
                var car  = skin == null ? null : CarsManager.Instance.GetById(skin.CarId);
                var slot = (renderer as ToolsKn5ObjectRenderer)?.MainSlot;
                if (car != null && slot != null)
                {
                    slot.SetCar(CarDescription.FromKn5(kn5, car.Location, car.AcdData));
                    slot.SelectSkin(skin.Id);
                }
            }
        }
Пример #7
0
        protected override void InitializeInner()
        {
            base.InitializeInner();
            DeviceContextHolder.Set <IMaterialsFactory>(new MaterialsProviderDeferred());

            Scene.Add(SkyObject.Create(500f));

            foreach (var showroom in _kn5.Skip(1))
            {
                Scene.Add(new Kn5RenderableFile(showroom, Matrix.Identity));
            }

            if (_kn5.Length > 1)
            {
                _car = new DeferredRenderableCar(CarDescription.FromKn5(_kn5[0]), Matrix.Identity, shadowsHeight: 0.001f, lights: Lights)
                {
                    IsReflectable = false
                };
                Scene.Add(_car);
            }

            Scene.UpdateBoundingBox();

            Camera = new CameraOrbit(32)
            {
                Alpha  = 0.9f,
                Beta   = 0.1f,
                Radius = _car?.BoundingBox?.GetSize().Length() * 1.2f ?? 4.8f,
                Target = (_car?.BoundingBox?.GetCenter() ?? Vector3.Zero) - new Vector3(0f, 0.05f, 0f)
            };

            _resetCamera = (CameraOrbit)Camera.Clone();

            Sun = new DirectionalLight {
                Color     = FixLight(new Vector3(1.2f, 1.0f, 0.9f)) * 5f,
                Direction = Vector3.Normalize(new Vector3(-1.2f, -3.4f, -2.2f))
            };

            _effect = DeviceContextHolder.GetEffect <EffectDeferredGObject>();
        }
Пример #8
0
 public DeferredRenderableCar(CarDescription car, Matrix matrix, string selectSkin = null, bool scanForSkins = true,
                              float shadowsHeight = 0, List <ILight> lights = null)
     : base(car, matrix, selectSkin ?? DefaultSkin, scanForSkins, shadowsHeight)
 {
     _lights = lights;
 }
Пример #9
0
        public async Task SetCarAsync(CarDescription car, string skinId   = Kn5RenderableCar.DefaultSkin,
                                      CancellationToken cancellationToken = default(CancellationToken))
        {
            ClearBeforeChangingCar();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            try {
                _loadingCar = car;

                if (_carWrapper == null)
                {
                    _car = car;
                    return;
                }

                if (car == null)
                {
                    ClearExisting();
                    CarNode         = null;
                    _carBoundingBox = null;
                    _car            = null;
                    Scene.UpdateBoundingBox();
                    return;
                }

                Kn5RenderableCar loaded = null;

                var previous = _previousCars.FirstOrDefault(x => x.Id == car.MainKn5File);
                if (previous != null)
                {
                    _previousCars.Remove(previous);

                    ClearExisting();
                    _carWrapper.AddRange(previous.Objects);
                    _car   = car;
                    loaded = previous.Objects.OfType <Kn5RenderableCar>().First();
                    CopyValues(loaded, CarNode);
                    CarNode         = loaded;
                    _carBoundingBox = null;

                    if (_selectSkinLater)
                    {
                        CarNode.SelectSkin(DeviceContextHolder, _selectSkin);
                        _selectSkinLater = false;
                    }
                    else
                    {
                        CarNode.SelectSkin(DeviceContextHolder, skinId);
                    }
                    Scene.UpdateBoundingBox();
                    return;
                }

                await car.LoadAsync();

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                await Task.Run(() => {
                    loaded = new Kn5RenderableCar(car, Matrix.Identity, _selectSkinLater ? _selectSkin : skinId,
                                                  asyncTexturesLoading: AsyncTexturesLoading, asyncOverrideTexturesLoading: AsyncOverridesLoading,
                                                  allowSkinnedObjects: AllowSkinnedObjects);
                    _selectSkinLater = false;
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    CopyValues(loaded, CarNode);
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    loaded.Draw(DeviceContextHolder, null, SpecialRenderMode.InitializeOnly);
                });

                if (cancellationToken.IsCancellationRequested || _loadingCar != car)
                {
                    loaded?.Dispose();
                    return;
                }

                ClearExisting();

                _carWrapper.Add(loaded);
                ExtendCar(loaded, _carWrapper);

                _car            = car;
                _selectSkin     = null;
                CarNode         = loaded;
                _carBoundingBox = null;

                IsDirty = true;
                Scene.UpdateBoundingBox();
            } catch (Exception e) {
                MessageBox.Show(e.ToString());
                throw;
            } finally {
                if (ReferenceEquals(_loadingCar, car))
                {
                    _loadingCar = null;
                }
            }
        }
Пример #10
0
        public void SetCar(CarDescription car, string skinId = Kn5RenderableCar.DefaultSkin)
        {
            ClearBeforeChangingCar();

            try {
                _loadingCar = car;

                if (_carWrapper == null)
                {
                    _car = car;
                    return;
                }

                if (car == null)
                {
                    ClearExisting();
                    CarNode         = null;
                    _carBoundingBox = null;
                    _car            = null;
                    Scene.UpdateBoundingBox();
                    return;
                }

                Kn5RenderableCar loaded;

                var previous = _previousCars.FirstOrDefault(x => x.Id == car.MainKn5File);
                if (previous != null)
                {
                    _previousCars.Remove(previous);

                    ClearExisting();
                    _carWrapper.AddRange(previous.Objects);
                    _car   = car;
                    loaded = previous.Objects.OfType <Kn5RenderableCar>().First();
                    CopyValues(loaded, CarNode);
                    CarNode         = loaded;
                    _carBoundingBox = null;

                    if (_selectSkinLater)
                    {
                        CarNode.SelectSkin(DeviceContextHolder, _selectSkin);
                        _selectSkinLater = false;
                    }
                    else
                    {
                        CarNode.SelectSkin(DeviceContextHolder, skinId);
                    }
                    Scene.UpdateBoundingBox();
                    return;
                }

                loaded = new Kn5RenderableCar(car, Matrix.Identity, _selectSkinLater ? _selectSkin : skinId,
                                              asyncTexturesLoading: AsyncTexturesLoading, asyncOverrideTexturesLoading: AsyncOverridesLoading,
                                              allowSkinnedObjects: AllowSkinnedObjects);
                _selectSkinLater = false;
                CopyValues(loaded, CarNode);

                ClearExisting();

                _carWrapper.Add(loaded);
                ExtendCar(loaded, _carWrapper);

                _car            = car;
                _selectSkin     = null;
                CarNode         = loaded;
                _carBoundingBox = null;

                IsDirty = true;
                Scene.UpdateBoundingBox();
            } catch (Exception e) {
                MessageBox.Show(e.ToString());
                throw;
            } finally {
                if (ReferenceEquals(_loadingCar, car))
                {
                    _loadingCar = null;
                }
            }
        }
Пример #11
0
 public ForwardKn5ObjectRenderer(CarDescription car, string showroomKn5Filename = null)
 {
     _car = car;
     _showroomKn5Filename = showroomKn5Filename;
 }
Пример #12
0
        private static DarkKn5ObjectRenderer CreateRenderer(string acRoot, DarkPreviewsOptions options, CarDescription initialCar, string initialSkinId)
        {
            var showroom = options.Showroom;

            if (showroom != null && !File.Exists(showroom))
            {
                var kn5 = Path.Combine(FileUtils.GetShowroomDirectory(acRoot, showroom), $"{showroom}.kn5");
                showroom = File.Exists(kn5) ? kn5 : null;
            }

            var renderer = new DarkKn5ObjectRenderer(initialCar, showroom)
            {
                AutoloadCarLights      = true,
                AutoloadShowroomLights = true
            };

            SetRendererOptions(renderer, options);

            renderer.SelectSkin(initialSkinId);
            renderer.Initialize();
            SetRendererCarOptions(renderer, options);

            return(renderer);
        }
Пример #13
0
        private static async Task ShowCarInShowroomAsync(string carId)
        {
            if (_showingCarInShowroom)
            {
                return;
            }
            _showingCarInShowroom = true;

            try {
                var temporaryDirectory = FilesStorage.Instance.GetTemporaryDirectory("Workshop", "Showroom", carId);
                var temporaryFilename  = Path.Combine(temporaryDirectory, "data.zip");

                byte[] modelData  = null;
                string mainSkidId = null;
                var    carData    = new VirtualDataWrapper();

                using (var waiting = WaitingDialog.Create("Loading showroom…")) {
                    await WorkshopHolder.Client.DownloadFileAsync($"/cars/{carId}/download-showroom", temporaryFilename, false,
                                                                  waiting, waiting.CancellationToken);

                    waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Loading…"));

                    await Task.Run(() => {
                        using (var stream = File.OpenRead(temporaryFilename))
                            using (var archive = new ZipArchive(stream)) {
                                foreach (var entry in archive.Entries)
                                {
                                    if (entry.Length == 0)
                                    {
                                        continue;
                                    }
                                    if (entry.FullName == @"model.kn5")
                                    {
                                        modelData = entry.Open().ReadAsBytesAndDispose();
                                    }
                                    else if (entry.FullName.StartsWith(@"data"))
                                    {
                                        carData.Data[Path.GetFileName(entry.FullName)] = entry.Open().ReadAsStringAndDispose();
                                    }
                                    else
                                    {
                                        if (mainSkidId == null && entry.FullName.StartsWith(@"skins"))
                                        {
                                            mainSkidId = Path.GetFileName(Path.GetDirectoryName(entry.FullName));
                                        }
                                        var newFilename = Path.Combine(temporaryDirectory, entry.FullName);
                                        FileUtils.EnsureFileDirectoryExists(newFilename);
                                        entry.ExtractToFile(newFilename, true);
                                    }
                                    waiting.CancellationToken.ThrowIfCancellationRequested();
                                }
                            }
                    });

                    waiting.CancellationToken.ThrowIfCancellationRequested();
                }

                if (modelData == null)
                {
                    throw new Exception("Model is missing");
                }

                if (mainSkidId == null)
                {
                    throw new Exception("Skins are missing");
                }

                var description = CarDescription.FromKn5(Kn5.FromBytes(modelData), temporaryDirectory, carData);
                var renderer    = new DarkKn5ObjectRenderer(description)
                {
                    FlatMirror = true,
                    FlatMirrorReflectiveness = 0.3f,
                    FlatMirrorReflectedLight = true,
                    BackgroundColor          = Color.White,
                    BackgroundBrightness     = 0.05f,
                    LightBrightness          = 2f,
                    AmbientBrightness        = 2f,
                    AmbientUp                   = Color.FromArgb(0xEEEEEE),
                    AmbientDown                 = Color.FromArgb(0x333333),
                    UseDof                      = true,
                    UseAccumulationDof          = true,
                    AccumulationDofIterations   = 40,
                    AccumulationDofApertureSize = 0f,
                    UseSslr                     = true,
                    VisibleUi                   = false,
                    UseSprite                   = false,
                    AnyGround                   = false,
                    ToneMapping                 = ToneMappingFn.Uncharted2,
                    ToneExposure                = 1.2f,
                    ToneGamma                   = 1f,
                    ToneWhitePoint              = 2.2f,
                };
                renderer.SelectSkin(mainSkidId);
                await FormWrapperBase.PrepareAsync();

                var wrapper = new LiteShowroomFormWrapper(renderer);
                wrapper.Form.Icon = AppIconService.GetAppIcon();
                CustomShowroomWrapper.SetProperties(wrapper, renderer);
                wrapper.Run();
            } catch (Exception e) when(!e.IsCancelled())
            {
                Logging.Warning(e);
                NonfatalError.Notify("Failed to load showroom", e);
            } finally {
                _showingCarInShowroom = false;
            }
        }
Пример #14
0
 public ToolsKn5ObjectRenderer(CarDescription car, string showroomKn5Filename = null) : base(car, showroomKn5Filename)
 {
 }
Пример #15
0
        private static async Task StartAsyncInner(string kn5, string skinId = null, string presetFilename = null)
        {
            if (_starting)
            {
                return;
            }
            _starting = true;

            await FormWrapperBase.PrepareAsync();

            ForwardKn5ObjectRenderer renderer = null;

            Logging.Write("Custom Showroom: Magick.NET IsSupported=" + ImageUtils.IsMagickSupported);

            try {
                var carDirectory = Path.GetDirectoryName(kn5);
                if (Path.GetFileName(Path.GetDirectoryName(carDirectory)) == @"..")
                {
                    carDirectory = Path.GetDirectoryName(Path.GetDirectoryName(carDirectory));
                }

                var carObject   = CarsManager.Instance.GetById(Path.GetFileName(carDirectory) ?? "");
                var toolboxMode = IsSameDirectories(carObject?.Location, carDirectory);

                LiteShowroomFormWrapper formWrapper;
                using (var waiting = new WaitingDialog()) {
                    waiting.Report(ControlsStrings.CustomShowroom_Loading);

                    var description = new CarDescription(kn5, carDirectory, carObject?.AcdData);
                    if (toolboxMode)
                    {
                        ExtraModelProvider.Initialize();
                        var toolsRenderer = await Task.Run(() => SettingsHolder.CustomShowroom.UseOldLiteShowroom?
                                                           new ToolsKn5ObjectRenderer(description) {
                            UseMsaa      = SettingsHolder.CustomShowroom.LiteUseMsaa,
                            UseFxaa      = SettingsHolder.CustomShowroom.LiteUseFxaa,
                            UseBloom     = SettingsHolder.CustomShowroom.LiteUseBloom,
                            SoundFactory = new AcCarSoundFactory()
                        } :
                                                           new DarkKn5ObjectRenderer(description)
                        {
                            SoundFactory = new AcCarSoundFactory()
                        });

                        formWrapper = new LiteShowroomFormWrapperWithTools(toolsRenderer, carObject, skinId, presetFilename);
                        renderer    = toolsRenderer;
                    }
                    else
                    {
                        Logging.Warning($"Can’t find CarObject for “{carDirectory}”");
                        Logging.Warning($"Found location: “{carObject?.Location ?? @"NULL"}”");

                        renderer = await Task.Run(() => SettingsHolder.CustomShowroom.UseOldLiteShowroom?
                                                  new ForwardKn5ObjectRenderer(description) {
                            UseMsaa  = SettingsHolder.CustomShowroom.LiteUseMsaa,
                            UseFxaa  = SettingsHolder.CustomShowroom.LiteUseFxaa,
                            UseBloom = SettingsHolder.CustomShowroom.LiteUseBloom
                        } :
                                                  new DarkKn5ObjectRenderer(description)
                        {
                            FlatMirror = true,
                            VisibleUi  = true,
                            UseSprite  = true
                        });

                        formWrapper = new LiteShowroomFormWrapper(renderer);
                        if (skinId != null)
                        {
                            renderer.SelectSkin(skinId);
                        }
                    }

                    SetProperties(formWrapper, renderer);
                    formWrapper.Form.Icon = AppIconService.GetAppIcon();
                }

                formWrapper.Run(() => _starting = false);
            } catch (Exception e) {
                NonfatalError.Notify(ControlsStrings.CustomShowroom_CannotStart, e);
            } finally {
                try {
                    renderer?.Dispose();
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t close Custom Showroom", e);
                } finally {
                    _starting = false;
                }
            }
        }
Пример #16
0
        private static async Task StartAsyncInner([CanBeNull] CarObject carObject, string kn5, IEnumerable <CustomShowroomLodDefinition> lodDefinitions = null,
                                                  string skinId = null, string presetFilename = null, bool forceToolboxMode = false)
        {
            if (_starting)
            {
                return;
            }
            _starting = true;

            await FormWrapperBase.PrepareAsync();

            ForwardKn5ObjectRenderer renderer = null;

            Logging.Write("Custom Showroom: Magick.NET IsSupported=" + ImageUtils.IsMagickSupported);

            if (!_interopSet)
            {
                _interopSet = true;
                Task.Delay(TimeSpan.FromSeconds(1d)).ContinueWithInMainThread(r => {
                    DpiAwareWindow.NewWindowCreated += (sender, args) => ElementHost.EnableModelessKeyboardInterop((DpiAwareWindow)sender);
                    foreach (Window window in Application.Current.Windows)
                    {
                        ElementHost.EnableModelessKeyboardInterop(window);
                    }
                }).Ignore();
            }

            try {
                var kn5Directory = Path.GetDirectoryName(kn5);
                var toolboxMode  = forceToolboxMode || lodDefinitions != null || IsSameDirectories(carObject?.Location, kn5Directory);

                LiteShowroomFormWrapper formWrapper;
                using (var waiting = new WaitingDialog()) {
                    waiting.Report(ControlsStrings.CustomShowroom_Loading);

                    var description = new CarDescription(kn5, carObject?.Location ?? kn5Directory, carObject?.AcdData);
                    if (toolboxMode)
                    {
                        ExtraModelProvider.Initialize();
                        var toolsRenderer = await Task.Run(() => SettingsHolder.CustomShowroom.UseOldLiteShowroom?
                                                           new ToolsKn5ObjectRenderer(description) {
                            UseMsaa      = SettingsHolder.CustomShowroom.LiteUseMsaa,
                            UseFxaa      = SettingsHolder.CustomShowroom.LiteUseFxaa,
                            UseBloom     = SettingsHolder.CustomShowroom.LiteUseBloom,
                            SoundFactory = new AcCarSoundFactory()
                        } :
                                                           new DarkKn5ObjectRenderer(description)
                        {
                            SoundFactory = new AcCarSoundFactory()
                        });

                        formWrapper = new LiteShowroomFormWrapperWithTools(toolsRenderer, carObject, skinId, presetFilename, lodDefinitions);
                        renderer    = toolsRenderer;
                    }
                    else
                    {
                        Logging.Warning($"Can’t find CarObject for “{kn5Directory}”");
                        Logging.Warning($"Found location: “{carObject?.Location ?? @"NULL"}”");

                        renderer = await Task.Run(() => SettingsHolder.CustomShowroom.UseOldLiteShowroom?
                                                  new ForwardKn5ObjectRenderer(description) {
                            UseMsaa  = SettingsHolder.CustomShowroom.LiteUseMsaa,
                            UseFxaa  = SettingsHolder.CustomShowroom.LiteUseFxaa,
                            UseBloom = SettingsHolder.CustomShowroom.LiteUseBloom
                        } :
                                                  new DarkKn5ObjectRenderer(description)
                        {
                            FlatMirror = true,
                            VisibleUi  = true,
                            UseSprite  = true
                        });

                        formWrapper = new LiteShowroomFormWrapper(renderer);
                        if (skinId != null)
                        {
                            renderer.SelectSkin(skinId);
                        }
                    }

                    SetProperties(formWrapper, renderer);
                    formWrapper.Form.Icon = AppIconService.GetAppIcon();
                }

                formWrapper.Run(() => _starting = false);
            } catch (Exception e) {
                NonfatalError.Notify(ControlsStrings.CustomShowroom_CannotStart, e);
            } finally {
                try {
                    renderer?.Dispose();
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t close Custom Showroom", e);
                } finally {
                    _starting = false;
                }
            }
        }
Пример #17
0
        private async Task EnableRenderer()
        {
            if (!_loaded)
            {
                await DisableRenderer();

                return;
            }

            try {
                _carId = ValuesStorage.Storage.GetObject <JObject>("__QuickDrive_Main")?.GetStringValueOnly("CarId") ?? @"abarth500";

                var car = CarsManager.Instance.GetById(_carId);
                if (_imageEx != null || car == null)
                {
                    return;
                }

                Progress.IsActive = true;
                var panoramaBg = new Uri("pack://application:,,,/Content Manager;component/Assets/Img/ShowroomPanoramaExample.jpg", UriKind.Absolute);
                var renderer   = new DarkKn5ObjectRenderer(CarDescription.FromDirectory(car.Location, car.AcdData))
                {
                    WpfMode              = true,
                    UseMsaa              = false,
                    VisibleUi            = false,
                    TryToGuessCarLights  = false,
                    LoadCarLights        = false,
                    AnyGround            = true,
                    BackgroundColor      = System.Drawing.Color.FromArgb(0x444444),
                    BackgroundBrightness = 1f,
                    LightBrightness      = 0f,
                    AmbientDown          = System.Drawing.Color.FromArgb(0x444444),
                    AmbientUp            = System.Drawing.Color.FromArgb(0xffffff),
                    AmbientBrightness    = 4f,
                    Light                       = Vector3.Normalize(new Vector3(-0.1f, 10, -0.1f)),
                    ShadowMapSize               = 512,
                    EnableShadows               = false,
                    AutoRotate                  = false,
                    AutoAdjustTarget            = false,
                    UseDof                      = true,
                    UseAccumulationDof          = true,
                    AccumulationDofApertureSize = 0f,
                    AccumulationDofIterations   = 20,
                    AccumulationDofBokeh        = false,
                    UseFxaa                     = false,
                    UseSslr                     = true,
                    UseAo                       = false,
                    UseDither                   = true,
                    MaterialsReflectiveness     = 1.5f,
                    UseCustomReflectionCubemap  = true,
                    CustomReflectionCubemap     = Application.GetResourceStream(panoramaBg)?.Stream.ReadAsBytesAndDispose(),
                    CubemapAmbientWhite         = false,
                    CubemapAmbient              = 0.6f,
                };

                var data = car.AcdData;
                if (data != null)
                {
                    var carBasic = data.GetIniFile("car.ini")["BASIC"];
                    _carLength = carBasic.GetVector3F("INERTIA").ToVector3().Z;

                    var suspensions      = data.GetIniFile("suspensions.ini");
                    var suspensionsBasic = suspensions["BASIC"];
                    var go     = carBasic.GetVector3F("GRAPHICS_OFFSET").ToVector3();
                    var center = suspensionsBasic.GetFloat("WHEELBASE", 2.5f) * suspensionsBasic.GetFloat("CG_LOCATION", 0.5f);
                    _carOffset = new Vector3(go.X, go.Y - suspensions["REAR"].GetFloat("BASEY", 0.25f), go.Z + center);
                    _lookAt    = new Vector3(go.X, go.Y - suspensions["FRONT"].GetFloat("BASEY", 0.25f), go.Z + center);
                }

                await Task.Run(() => renderer.Initialize());

                renderer.SetCameraHigher = false;
                SetRendererSize(renderer);

                if (renderer.CarNode != null)
                {
                    // renderer.SelectSkin(car.SelectedSkin?.Id);
                    renderer.CarNode.BrakeLightsEnabled = true;
                    renderer.CarNode.CockpitLrActive    = true;
                    renderer.CarNode.CurrentLod         = renderer.CarNode.LodsCount > 1 ? 1 : 0;
                }

                await Task.Run(() => renderer.Draw());

                _renderer = renderer;

                _imageEx     = new D3DImageEx();
                Scene.Source = _imageEx;

                _setCount   = 0;
                _lastTarget = IntPtr.Zero;

                CompositionTargetEx.Rendering += OnRendering;
                UpdateCamera();
            } catch (Exception e) {
                NonfatalError.Notify("Can’t display chase camera preview", e);
            } finally {
                Progress.IsActive = false;
            }
        }