Ejemplo n.º 1
0
            public byte[] LoadTexture(string textureName, ReadAheadBinaryReader reader, int textureSize)
            {
                if (textureSize > 4e6)
                {
                    AcToolsLogging.Write($"{textureName}: {(double)textureSize / 1024 / 1024:F1} MB");
                }

                MemoryChunk.Bytes(textureSize).Execute(() => {
                    var bytes = reader.ReadBytes(textureSize);

                    // FromStream simply reads Stream to byte[] underneath, so we could just do it here in
                    // a more controlled manner

                    try {
                        lock (_device) {
                            if (OptionLoadView)
                            {
                                var view            = ShaderResourceView.FromMemory(_device, bytes); // new ShaderResourceView(_device, texture);
                                _ready[textureName] = new Tuple <Texture2D, ShaderResourceView>(null, view);
                            }
                            else
                            {
                                var texture         = Texture2D.FromMemory(_device, bytes);
                                var view            = new ShaderResourceView(_device, texture);
                                _ready[textureName] = new Tuple <Texture2D, ShaderResourceView>(texture, view);
                            }
                        }
                    } catch (SEHException e) {
                        AcToolsLogging.NonFatalErrorNotify("Can’t load texture", "Try again?", e);
                    }
                });

                return(null);
            }
Ejemplo n.º 2
0
 void LoadTextures()
 {
     foreach (var key in _kn5.Textures.Values.Select(x => x.Name.ToLower()).Where(key => !_textures.ContainsKey(key)))
     {
         try {
             _textures[key] = ShaderResourceView.FromMemory(CurrentDevice, DefaultTexture(key));
         } catch (System.Exception) { }
     }
 }
        /// <summary>
        ///
        /// </summary>
        protected void AttachMaterial()
        {
            this.phongMaterial = Material as PhongMaterial;
            if (phongMaterial != null)
            {
                this.effectMaterial = new EffectMaterialVariables(this.effect);

                /// --- has texture
                if (phongMaterial.DiffuseMap != null)
                {
                    this.texDiffuseMapView = ShaderResourceView.FromMemory(Device, phongMaterial.DiffuseMap.ToByteArray());
                    this.effectMaterial.texDiffuseMapVariable.SetResource(this.texDiffuseMapView);
                    this.effectMaterial.bHasDiffuseMapVariable.Set(true);
                }
                else
                {
                    this.effectMaterial.bHasDiffuseMapVariable.Set(false);
                }

                // --- has bumpmap
                if (phongMaterial.NormalMap != null)
                {
                    var geometry = this.Geometry as MeshGeometry3D;
                    if (geometry != null)
                    {
                        if (geometry.Tangents == null)
                        {
                            //System.Windows.MessageBox.Show(string.Format("No Tangent-Space found. NormalMap will be omitted."), "Warrning", MessageBoxButton.OK);
                            phongMaterial.NormalMap = null;
                        }
                        else
                        {
                            this.texNormalMapView = ShaderResourceView.FromMemory(Device, phongMaterial.NormalMap.ToByteArray());
                            this.effectMaterial.texNormalMapVariable.SetResource(this.texNormalMapView);
                            this.effectMaterial.bHasNormalMapVariable.Set(true);
                        }
                    }
                }
                else
                {
                    this.effectMaterial.bHasNormalMapVariable.Set(false);
                }

                // --- has displacement map
                if (phongMaterial.DisplacementMap != null)
                {
                    this.texDisplacementMapView = ShaderResourceView.FromMemory(Device, phongMaterial.DisplacementMap.ToByteArray());
                    this.effectMaterial.texDisplacementMapVariable.SetResource(this.texDisplacementMapView);
                    this.effectMaterial.bHasDisplacementMapVariable.Set(true);
                }
                else
                {
                    this.effectMaterial.bHasDisplacementMapVariable.Set(false);
                }
            }
        }
Ejemplo n.º 4
0
 private ShaderResourceView LoadSafe([CanBeNull] Device device, byte[] bytes)
 {
     if (device == null)
     {
         return(null);
     }
     try {
         return(ShaderResourceView.FromMemory(device, bytes));
     } catch (Exception e) {
         AcToolsLogging.Write($"Texture {Name} damaged: {e}");
         return(null);
     }
 }
Ejemplo n.º 5
0
        public static byte[] ToPng(DeviceContextHolder holder, byte[] bytes, bool ignoreAlpha, Size?downsize, out Format format)
        {
            Viewport[] viewports = null;

            try {
                using (var stream = new System.IO.MemoryStream())
                    using (var effect = new EffectPpBasic())
                        using (var output = TargetResourceTexture.Create(Format.R8G8B8A8_UNorm))
                            using (var resource = ShaderResourceView.FromMemory(holder.Device, bytes)) {
                                var texture = (Texture2D)resource.Resource;
                                var loaded  = texture.Description;
                                var width   = downsize?.Width ?? loaded.Width;
                                var height  = downsize?.Height ?? loaded.Height;

                                effect.Initialize(holder.Device);

                                format = loaded.Format;
                                output.Resize(holder, width, height, null);

                                holder.DeviceContext.ClearRenderTargetView(output.TargetView, Color.Transparent);
                                holder.DeviceContext.OutputMerger.SetTargets(output.TargetView);

                                viewports = holder.DeviceContext.Rasterizer.GetViewports();
                                holder.DeviceContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0f, 1f));

                                holder.DeviceContext.OutputMerger.BlendState = null;
                                holder.QuadBuffers.Prepare(holder.DeviceContext, effect.LayoutPT);

                                effect.FxInputMap.SetResource(resource);
                                holder.PrepareQuad(effect.LayoutPT);

                                if (ignoreAlpha)
                                {
                                    effect.TechCopyNoAlpha.DrawAllPasses(holder.DeviceContext, 6);
                                }
                                else
                                {
                                    effect.TechCopy.DrawAllPasses(holder.DeviceContext, 6);
                                }

                                Texture2D.ToStream(holder.DeviceContext, output.Texture, ImageFileFormat.Png, stream);
                                stream.Position = 0;
                                return(stream.GetBuffer());
                            }
            } finally {
                if (viewports != null)
                {
                    holder.DeviceContext.Rasterizer.SetViewports(viewports);
                }
            }
        }
Ejemplo n.º 6
0
        public override void Attach(IRenderHost host)
        {
            // --- attach
            this.renderTechnique = Techniques.RenderBillboard;
            this.effect          = EffectsManager.Instance.GetEffect(renderTechnique);
            this.renderHost      = host;

            // --- get variables
            this.vertexLayout    = EffectsManager.Instance.GetLayout(this.renderTechnique);
            this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name);

            // --- transformations
            this.effectTransforms = new EffectTransformVariables(this.effect);

            // --- shader variables
            this.vViewport = effect.GetVariableByName("vViewport").AsVector();

            // --- get geometry
            var geometry = this.Geometry as BillboardText3D;

            if (geometry == null)
            {
                return;
            }

            // --- material
            // this.AttachMaterial();
            billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource();

            var textureBytes = BillboardText3D.Texture.ToByteArray();

            billboardTextureView = ShaderResourceView.FromMemory(Device, textureBytes);
            billboardTextureVariable.SetResource(billboardTextureView);

            // -- set geometry if given
            vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer,
                                               DefaultVertex.SizeInBytes, CreateBillboardVertexArray());

            /// --- set rasterstate
            this.OnRasterStateChanged(this.DepthBias);

            /// --- flush
            this.Device.ImmediateContext.Flush();
        }
Ejemplo n.º 7
0
            public byte[] LoadTexture(string textureName, Stream stream, int textureSize)
            {
                AcToolsLogging.Write(textureName + ": " + textureSize / 1024 / 1024 + " MB");

                MemoryChunk.Bytes(textureSize).Execute(() => {
                    var bytes = new byte[textureSize];
                    AcToolsLogging.Write("Bytes are ready");

                    stream.Read(bytes, 0, textureSize);
                    AcToolsLogging.Write("Texture has been read");

                    // FromStream simply reads Stream to byte[] underneath, so we could just do it here in
                    // a more controlled manner
                    _ready[textureName] = ShaderResourceView.FromMemory(_device, bytes);
                    AcToolsLogging.Write("Texture has been loaded");
                });

                return(null);
            }
Ejemplo n.º 8
0
        public override void Attach(IRenderHost host)
        {
            // --- attach
            renderTechnique = host.RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.BillboardText];
            effect          = host.EffectsManager.GetEffect(renderTechnique);
            renderHost      = host;

            // --- get variables
            vertexLayout    = renderHost.EffectsManager.GetLayout(renderTechnique);
            effectTechnique = effect.GetTechniqueByName(renderTechnique.Name);

            // --- transformations
            effectTransforms = new EffectTransformVariables(effect);

            // --- shader variables
            vViewport = effect.GetVariableByName("vViewport").AsVector();

            // --- get geometry
            var geometry = Geometry as IBillboardText;

            if (geometry == null)
            {
                return;
            }
            // -- set geometry if given
            vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer,
                                               VertexSizeInBytes, CreateBillboardVertexArray());
            // --- material
            // this.AttachMaterial();
            billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource();

            var textureBytes = geometry.Texture.ToByteArray();

            billboardTextureView = ShaderResourceView.FromMemory(Device, textureBytes);

            /// --- set rasterstate
            OnRasterStateChanged();

            /// --- flush
            Device.ImmediateContext.Flush();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// ポインタから
        /// </summary>
        /// <param name="ptr"></param>
        public TextureBuffer(IntPtr ptr)
        {
            ksTexHeader header = (ksTexHeader)Marshal.PtrToStructure(ptr, typeof(ksTexHeader));
            int         offset = Marshal.SizeOf(header);

            ptr += offset;

            // データをバイト配列にコピー
            byte[] buffer = new byte[header.data_size];
            Marshal.Copy(ptr, buffer, 0, header.data_size);

            // バッファから初期化
            shaderResourceView_ = ShaderResourceView.FromMemory(GraphicsCore.D3D11Device, buffer);
            buffer_             = shaderResourceView_.Resource;

            // 情報取得
            var tex = (Texture2D)shaderResourceView_.Resource;

            width_  = tex.Description.Width;
            height_ = tex.Description.Height;
            format_ = tex.Description.Format;
            mips_   = tex.Description.MipLevels;
        }
Ejemplo n.º 10
0
 public void OnInitialize(DeviceContextHolder holder)
 {
     _effect        = holder.GetEffect <EffectPpDof>();
     _copyHelper    = holder.GetHelper <CopyHelper>();
     _bokehBaseView = ShaderResourceView.FromMemory(holder.Device, Resources.Bokeh);
 }
Ejemplo n.º 11
0
        void ReloadTexture(string filename, byte[] data)
        {
            var key = Path.GetFileName(filename).ToLower();

            if (!ContainsTexture(key) && data != null)
            {
                if (!key.EndsWith(".psd") && !key.EndsWith(".xcf") && !key.EndsWith(".jpg") && !key.EndsWith(".jpeg") &&
                    !key.EndsWith(".png") && !key.EndsWith(".tiff") && !key.EndsWith(".tga") && !key.EndsWith(".bmp"))
                {
                    return;
                }

                Toast("Updated: " + key);
                Logging.Write("reload texture using imagemagick: " + key);

                var nameOnly             = key.Substring(0, key.Length - 4);
                var possibleDestinations = _kn5.Textures.Where(entry => entry.Key.ToLower() == nameOnly ||
                                                               Path.GetFileNameWithoutExtension(entry.Key).ToLower() == nameOnly).ToList();
                if (!possibleDestinations.Any())
                {
                    Toast("Not appliable");
                    Logging.Warning("  texture isn't appliable");
                    return;
                }

                key = possibleDestinations[0].Key.ToLower();
                Logging.Write("  load in place of " + key);

                byte[] imageData;
                try {
                    imageData = MagickWrapper.LoadFromBytesAsSlimDxBuffer(data);
                } catch (Exception e) {
                    Toast("Can't read file");
                    Logging.Write("  can't read file: " + e);
                    return;
                }

                if (_textures.ContainsKey(key) && _textures[key] != null)
                {
                    if (_overrides.Contains(key))
                    {
                        _overrides.Remove(key);
                    }

                    _textures[key].Dispose();
                    _textures[key] = null;
                }

                Toast("Loaded: " + imageData.Length + " bytes");
                _textures[key] = ShaderResourceView.FromMemory(CurrentDevice, imageData);
                _overrides.Add(key);
                return;
            }

            Logging.Write("reload texture as usual: " + key);
            if (_textures.ContainsKey(key) && _textures[key] != null)
            {
                if (_overrides.Contains(key))
                {
                    _overrides.Remove(key);
                }

                _textures[key].Dispose();
                _textures[key] = null;
            }

            if (data != null)
            {
                _textures[key] = ShaderResourceView.FromMemory(CurrentDevice, data);
                _overrides.Add(key);
            }
            else
            {
                _textures[key] = ShaderResourceView.FromMemory(CurrentDevice, DefaultTexture(key));
            }
        }
Ejemplo n.º 12
0
        public void LoadSkin(int id, int attempt = 0)
        {
            if (Skins.Count == 0)
            {
                return;
            }

            try {
                var newSelectedSkin = (id + Skins.Count) % Skins.Count;

                if (newSelectedSkin != SelectedSkin && _watcher != null)
                {
                    _watcher.Update -= Watcher_Update;
                    _watcher.Dispose();
                    _watcher = null;
                }

                SelectedSkin = newSelectedSkin;
                var skinPath = Skins[SelectedSkin];

                Logging.Write("skin: " + skinPath);

                if (_overrides != null)
                {
                    foreach (var ov in _overrides)
                    {
                        _textures[ov].Dispose();
                        _textures[ov] = null;
                    }

                    _overrides.Clear();
                }
                else
                {
                    _overrides = new List <string>();
                }

                if (!Directory.Exists(skinPath))
                {
                    return;
                }

                foreach (var file in Directory.GetFiles(skinPath))
                {
                    if (File.GetAttributes(file).HasFlag(FileAttributes.Directory))
                    {
                        continue;
                    }

                    var key = Path.GetFileName(file).ToLower();
                    if (!ContainsTexture(key))
                    {
                        continue;
                    }

                    if (_textures.ContainsKey(key) && _textures[key] != null)
                    {
                        _textures[key].Dispose();
                    }

                    _textures[key] = ShaderResourceView.FromFile(CurrentDevice, file);
                    _overrides.Add(key);
                }

                foreach (var key in _textures.Keys.ToList().Where(key => _textures[key] == null))
                {
                    _textures[key] = ShaderResourceView.FromMemory(CurrentDevice, DefaultTexture(key));
                }

                if (_watcher != null)
                {
                    return;
                }
                _watcher         = new SkinDirectoryWatcher(skinPath);
                _watcher.Update += Watcher_Update;
            } catch (Exception) {
                if (attempt > 3)
                {
                    if (_form != null)
                    {
                        Toast(@"Can't load skin: " + id);
                        Logging.Warning(@"Can't load skin: " + id);
                        if (_watcher != null)
                        {
                            _watcher.Update -= Watcher_Update;
                            _watcher.Dispose();
                            _watcher = null;
                        }
                    }
                }
                else
                {
                    if (_attemptTimer == null)
                    {
                        _attemptTimer = new System.Timers.Timer(300)
                        {
                            AutoReset = false
                        };
                        _attemptTimer.Elapsed += (o, eventArgs) => {
                            LoadSkin(SelectedSkin);
                        };
                        _attemptTimer.Enabled = true;
                    }

                    _attemptTimer.Stop();
                    _attemptTimer.Start();
                }
            }
        }
Ejemplo n.º 13
0
        void LoadScene(string filename, int skinNumber, VisualMode mode)
        {
            _mode     = mode;
            _filename = filename;

            _kn5 = Kn5.FromFile(filename, mode == VisualMode.BODY_SHADOW || mode == VisualMode.TRACK_MAP);
            if (_kn5.IsWithoutTextures())
            {
                var mainFile = FileUtils.GetMainCarFilename(Path.GetDirectoryName(filename));
                if (mainFile != null)
                {
                    _kn5.LoadTexturesFrom(mainFile);
                }
            }

            _textures = new Dictionary <string, ShaderResourceView>(_kn5.Textures.Count);

            LoadMaterials();
            GetObjects();

            _wireframeBackgroundColor = new Color4(0x292826);

            switch (_mode)
            {
            case VisualMode.SIMPLE_PREVIEW_GT5: {
                _camera = new CameraOrbit(0.08f * MathF.PI)
                {
                    Alpha = 1.1f, Beta = -0.04f, Radius = 8.0f, Target = new Vector3(0, 0.78f, 0)
                };

                _dirLight = new DirectionalLight {
                    Ambient   = new Color4(0.65f, 0.66f, 0.64f),
                    Diffuse   = new Color4(1.84f, 1.87f, 1.88f),
                    Specular  = new Color4(0.95f, 0.96f, 1.13f),
                    Direction = new Vector3(-1.57735f, -2.57735f, 0.57735f)
                };

                _backgroundColor   = new Color4(0.0f, 0.0f, 0.0f, 0.0f);
                _reflectionCubemap = ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomReflection);
            }
            break;

            case VisualMode.SIMPLE_PREVIEW_GT6: {
                _camera = new CameraOrbit(0.011f * MathF.PI)
                {
                    Alpha = 0.0f, Beta = 0.0f, NearZ = 1.0f, Radius = 90.0f, Target = new Vector3(0, 0.78f, 0)
                };

                _dirLight = new DirectionalLight {
                    Ambient   = new Color4(0.65f, 0.66f, 0.64f),
                    Diffuse   = new Color4(1.84f, 1.87f, 1.88f),
                    Specular  = new Color4(0.95f, 0.96f, 1.13f),
                    Direction = new Vector3(-1.57735f, -2.57735f, 0.57735f)
                };

                _backgroundColor   = new Color4(0.0f, 0.0f, 0.0f, 0.0f);
                _reflectionCubemap = ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomReflection);
            }
            break;

            case VisualMode.LIVERY_VIEW: {
                _dirLight = new DirectionalLight {
                    Ambient   = new Color4(2.5f, 2.5f, 2.5f),
                    Diffuse   = new Color4(0.0f, 0.0f, 0.0f),
                    Specular  = new Color4(0.0f, 0.0f, 0.0f),
                    Direction = new Vector3(0.0f, -1.0f, 0.0f)
                };

                var pos = -_objectPos;
                pos.Y = CarSize.Y + 1.0f;

                _camera = new CameraOrtho()
                {
                    Position = pos,
                    FarZ     = CarSize.Y + 10.0f,
                    Target   = pos - Vector3.UnitY,
                    Width    = CarSize.X,
                    Height   = CarSize.Z
                };

                foreach (var obj in _objs)
                {
                    if (obj.Blen != null)
                    {
                        obj.Blen.Dispose();

                        var transDesc = new BlendStateDescription {
                            AlphaToCoverageEnable  = false,
                            IndependentBlendEnable = false
                        };

                        transDesc.RenderTargets[0].BlendEnable           = true;
                        transDesc.RenderTargets[0].SourceBlend           = BlendOption.Zero;
                        transDesc.RenderTargets[0].DestinationBlend      = BlendOption.Zero;
                        transDesc.RenderTargets[0].BlendOperation        = BlendOperation.Add;
                        transDesc.RenderTargets[0].SourceBlendAlpha      = BlendOption.Zero;
                        transDesc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                        transDesc.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
                        transDesc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                        obj.Blen = BlendState.FromDescription(CurrentDevice, transDesc);
                    }
                }

                _backgroundColor = new Color4(0.0f, 0.0f, 0.0f, 0.0f);
            }
            break;

            case VisualMode.SIMPLE_PREVIEW_SEAT_LEON_EUROCUP: {
                _camera = new CameraOrbit(0.011f * MathF.PI)
                {
                    Alpha = 0.0f, Beta = 0.0f, NearZ = 1.0f, Radius = 90.0f, Target = new Vector3(0, 0.78f, 0)
                };

                _dirLight = new DirectionalLight {
                    Ambient   = new Color4(0.65f, 0.66f, 0.64f),
                    Diffuse   = new Color4(1.89f, 1.89f, 1.84f),
                    Specular  = new Color4(2.95f, 2.96f, 2.13f),
                    Direction = new Vector3(-1.57735f, -0.57735f, 0.57735f)
                };

                _backgroundColor   = new Color4(0.68f, 0.68f, 0.68f);
                _reflectionCubemap = ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomReflection);
            }
            break;

            case VisualMode.DARK_ROOM: {
                _camera = new CameraOrbit(0.15f * MathF.PI)
                {
                    Alpha = 1.1f, Beta = 0.021f, Radius = 5.4f, Target = new Vector3(0, 0.78f, 0)
                };

                _dirLight = new DirectionalLight {
                    Ambient   = new Color4(1.45f, 1.46f, 1.44f),
                    Diffuse   = new Color4(2.24f, 2.23f, 2.20f),
                    Specular  = new Color4(0.0f, 0.0f, 0.0f),
                    Direction = new Vector3(-1.57735f, -2.57735f, 0.57735f)
                };

                _backgroundColor   = new Color4(0.0f, 0.0f, 0.0f);
                _reflectionCubemap = ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomReflection);

                var size    = CarSize;
                var maxSize = System.Math.Max(size.X, size.Z) * 0.8f;
                var pos     = _objectPos;
                pos.Y = 0;
                CreateTexturedPlace(Matrix.Scaling(maxSize, 1.0f, maxSize) * Matrix.Translation(pos),
                                    ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomFloor));
                LoadShadows();
            }
            break;

            case VisualMode.BRIGHT_ROOM: {
                _camera = new CameraOrbit(0.15f * MathF.PI)
                {
                    Alpha = 1.1f, Beta = 0.021f, Radius = 5.4f, Target = new Vector3(0, 0.78f, 0)
                };

                _dirLight = new DirectionalLight {
                    Ambient   = new Color4(2.36f, 2.36f, 2.36f),
                    Diffuse   = new Color4(1.08f, 1.08f, 1.08f),
                    Specular  = new Color4(0.0f, 0.0f, 0.0f),
                    Direction = new Vector3(1.57735f, -2.57735f, 0.57735f)
                };

                _backgroundColor   = new Color4(0.9f, 0.92f, 0.97f);
                _reflectionCubemap = ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomReflection);

                var size    = CarSize;
                var maxSize = System.Math.Max(size.X, size.Z) * 0.8f;
                var pos     = _objectPos;
                pos.Y = 0;
                CreateTexturedPlace(Matrix.Scaling(maxSize, 1.0f, maxSize) * Matrix.Translation(pos),
                                    ShaderResourceView.FromMemory(CurrentDevice, Properties.Resources.TextureDarkRoomFloor)).Visible = false;
                LoadShadows();
            }
            break;

            case VisualMode.BODY_SHADOW: {
                LoadShadowsSize();
            }
                return;

            case VisualMode.TRACK_MAP:
                return;
            }

            LoadSkins();
            if (skinNumber >= 0 && skinNumber < Skins.Count)
            {
                LoadSkin(skinNumber);
            }

            LoadTextures();
        }
Ejemplo n.º 14
0
 protected override AResource doLoad(TextureResource res, byte[] data)
 {
     res.texture = ShaderResourceView.FromMemory(renderer.device, data);
     return(res);
 }