public TextureReference DefineTexture(string path) { //make sure its not already in there int index = TextureReferences.FindIndex((x) => x.Path.ToUpper() == path.ToUpper()); if (index != -1) return TextureReferences[index]; var pathFull = PathManager.FullyQualify(path); TextureReference tr = new TextureReference(); //try loading it as tga tr.Name = Path.GetFileNameWithoutExtension(path); tr.Path = path; tr.PopulateBMP(); tr.SetFormat(TextureFormat.Format4_I8); TextureReferences.Add(tr); LayoutMemory(); return tr; }
private static void LoadWalls(XmlDocument document) { XmlNodeList entities = document.GetElementsByTagName("wall"); foreach (XmlElement element in entities) { string name = element.GetAttribute("name"); string shortName = element.GetAttribute("shortname"); float scale = float.Parse(element.GetAttribute("scale")); bool unique = VerifyShortName(shortName); if (!unique) { Debug.LogWarning("Shortname " + shortName + " already exists, aborting"); continue; } string type = element.GetAttribute("type"); bool houseWall = type == "house" || type == "arch"; bool arch = type == "arch"; bool archBuildable = type == "lowfence"; Model bottomModel = null; Model normalModel = null; TextureReference icon = null; Color color = Color.white; List <string[]> categories = new List <string[]>(); Materials materials = null; foreach (XmlElement child in element) { switch (child.LocalName) { case "model": Model model = new Model(child, LayerMasks.WallLayer); if (model.Tag == "bottom") { bottomModel = model; } else { normalModel = model; } break; case "category": categories.Add(child.InnerText.Split('/')); break; case "color": float r = float.Parse(child.GetAttribute("r"), CultureInfo.InvariantCulture); float g = float.Parse(child.GetAttribute("g"), CultureInfo.InvariantCulture); float b = float.Parse(child.GetAttribute("b"), CultureInfo.InvariantCulture); color = new Color(r, g, b); break; case "materials": materials = new Materials(child); break; case "icon": icon = TextureReference.GetTextureReference(child.GetAttribute("location")); break; } } if (bottomModel == null) { bottomModel = normalModel; } WallData data = ScriptableObject.CreateInstance <WallData>(); data.Initialize(bottomModel, normalModel, name, shortName, color, scale, houseWall, arch, archBuildable, materials, icon); Database.Walls[shortName] = data; foreach (string[] category in categories) { IconUnityListElement iconListElement = (IconUnityListElement)GuiManager.Instance.WallsTree.Add(data, category); iconListElement.TextureReference = icon; } } }
private static void LoadGrounds(XmlDocument document) { XmlNodeList entities = document.GetElementsByTagName("ground"); foreach (XmlElement element in entities) { string name = element.GetAttribute("name"); string shortName = element.GetAttribute("shortname"); Debug.Log("Loading ground " + name); bool unique = VerifyShortName(shortName); if (!unique) { Debug.LogWarning("Shortname " + shortName + " already exists, aborting"); continue; } TextureReference tex2d = null; TextureReference tex3d = null; List <string[]> categories = new List <string[]>(); bool diagonal = false; foreach (XmlElement child in element) { switch (child.LocalName) { case "tex": string target = child.GetAttribute("target"); if (target == "editmode") { tex2d = TextureReference.GetTextureReference(child); } else if (target == "previewmode") { tex3d = TextureReference.GetTextureReference(child); } else { tex2d = TextureReference.GetTextureReference(child); tex3d = tex2d; } break; case "category": categories.Add(child.InnerText.Split('/')); break; case "diagonal": diagonal = true; break; } } if (tex2d == null || tex3d == null) { Debug.LogWarning("No textures loaded, aborting"); } GroundData data = ScriptableObject.CreateInstance <GroundData>(); data.Initialize(name, shortName, tex2d, tex3d, diagonal); Database.Grounds[shortName] = data; foreach (string[] category in categories) { IconUnityListElement iconListElement = (IconUnityListElement)GuiManager.Instance.GroundsTree.Add(data, category); iconListElement.TextureReference = tex2d; } Debug.Log("Ground data " + name + " loaded and ready to use!"); } }
public Tile(TextureReference img) { imgref = img; Behavior = 0; }
public Tile(TextureReference img, TileBehavior behavior) { imgref = img; Behavior = behavior; }
/// <summary> /// Tries to read import statements for external .FX files /// </summary> /// <param name="xmlEffect">xml effect node</param> /// <param name="material">Material instance to store data in</param> void ReadEffectImport(XmlNode xmlMaterial, XmlNode xmlEffect, ref Material material) { // for now the simplest solution: Simply search for a file path containing ".fx" Match match = Regex.Match(xmlEffect.InnerXml, "\"([^\"]+\\.fx)\""); if (!match.Success) { return; } string filename = match.Groups[1].Value.Replace("%20", " "); if (!Path.IsPathRooted(filename)) { filename = Path.GetDirectoryName(model.SourceFilename) + "\\" + filename; } CustomShader shader = new CustomShader(); shader.Filename = filename; // Set parameters as given in <instance_effect> XmlNode xmlInstanceEffect = xmlMaterial.SelectSingleNode("instance_effect"); if (xmlInstanceEffect == null) { return; } foreach (XmlNode setparam in xmlInstanceEffect.SelectNodes("setparam")) { // Name referencing a shader parameter string name = setparam.GetAttributeString("ref"); // value can be color, vector, single or texture Object value = null; XmlNode valueNode = setparam.FirstChild; switch (valueNode.Name) { case "float": value = XmlUtil.ParseFloats(valueNode.InnerText)[0]; break; case "float3": value = XmlUtil.ParseVector3(valueNode.InnerText); break; case "float4": value = XmlUtil.ParseVector4(valueNode.InnerText); break; case "float4x4": value = XmlUtil.ParseMatrix(valueNode.InnerText); break; case "surface": TextureReference texture = new TextureReference(); texture.TextureChannel = "CHANNEL1"; string imageId = valueNode.SelectSingleNode("init_from").InnerText; // texture/surface -> image XmlNode root = xmlEffect.OwnerDocument.DocumentElement; XmlNode imageInitFrom = root.SelectSingleNode("library_images/image[@id='" + imageId + "']/init_from"); if (imageInitFrom == null) { throw new Exception("Image not found: " + imageId, null); } texture.Filename = imageInitFrom.InnerText.Trim(); texture.Filename = texture.Filename.Replace("file://", ""); if (!Path.IsPathRooted(texture.Filename)) { texture.Filename = Path.GetDirectoryName(model.SourceFilename) + "\\" + texture.Filename; } value = texture; break; } if (value != null) { shader.Parameters.Add(name, value); } } material.Properties.Add(shader); }
public ShaderReference(TextureReference reference) : this(ReferenceType.Texture, reference) { }
private void btnImportTextureLevel_Click(object sender, EventArgs e) { // Extract the TextureReference structure to get the selected texture TextureReference textureData = (TextureReference)treeTextures.SelectedNode.Tag; TplTexture tex = tpl[textureData.TextureIdx]; // Request image filename if (ofdTextureImportPath.ShowDialog() != DialogResult.OK) { return; } // Load image Bitmap bmp; try { bmp = new Bitmap(ofdTextureImportPath.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error loading image.", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (textureData.TextureLevel == -1) // Replacing whole texture { // Ask the user to select the format to import GxTextureFormatPickerDialog formatPickerDlg = new GxTextureFormatPickerDialog( TplTexture.SupportedTextureFormats, tex.Format); if (formatPickerDlg.ShowDialog() != DialogResult.OK) { return; } GxTextureFormat newFmt = formatPickerDlg.SelectedFormat; // Redefine the entire texture from the bitmap tex.DefineTextureFromBitmap(newFmt, GetSelectedMipmap(), GetNumMipmaps(), bmp); TextureHasChanged(textureData.TextureIdx); UpdateTextureTree(); treeTextures.SelectedNode = treeTextures.Nodes.Cast <TreeNode>() .Where(tn => ((TextureReference)tn.Tag).TextureIdx == textureData.TextureIdx).First(); } else // Replacing single level { if (bmp.Width != tex.WidthOfLevel(textureData.TextureLevel) || bmp.Height != tex.HeightOfLevel(textureData.TextureLevel)) { MessageBox.Show("The selected image has an invalid size to replace this level.\n" + "If you wish to replace the entire texture, select the node coresponding to the texture.", "Invalid image size", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } // Replace just the selected level from the bitmap tex.DefineLevelDataFromBitmap(textureData.TextureLevel, GetSelectedMipmap(), bmp); TextureHasChanged(textureData.TextureIdx); } }
/// <summary> /// Reads either a xmlColor or a texture from a XML node. /// Thus it searches for <xmlcolor> or <texture>. /// </summary> /// <param name="xmlEffect">XML effect node</param> /// <param name="xmlChildNode">XML child node of <effect></param> /// <returns>Color, Texture or null if neither is found</returns> Object ReadColorOrTexture(XmlNode xmlEffect, XmlNode xmlChildNode) { if (xmlChildNode == null) { return(null); } XmlNode xmlColor = xmlChildNode.SelectSingleNode("color"); if (xmlColor != null) { float[] values = XmlUtil.ParseFloats(xmlColor.InnerText); if (values.Length < 3 || values.Length > 4) { throw new Exception("Unsupported Color format encountered"); } if (values.Length == 4) { return(new Color(values[0], values[1], values[2], values[3])); } else { return(new Color(values[0], values[1], values[2])); } } else { XmlNode xmlTexture = xmlChildNode.SelectSingleNode("texture"); if (xmlTexture == null) { return(null); } TextureReference texture = new TextureReference(); texture.TextureChannel = xmlTexture.Attributes["texcoord"].Value; // texture -> sampler string samplerId = xmlTexture.Attributes["texture"].Value; string imageId; XmlNode xmlSamplerSource = xmlEffect.SelectSingleNode(".//newparam[@sid='" + samplerId + "']/sampler2D/source"); if (xmlSamplerSource != null) { // sampler -> surface string surfaceId = xmlSamplerSource.InnerText.Trim(); XmlNode surfaceRef = xmlEffect.SelectSingleNode(".//newparam[@sid='" + surfaceId + "']/surface/init_from"); if (surfaceRef == null) { throw new Exception("No image reference for texture found"); } imageId = surfaceRef.InnerText.Trim(); } else { imageId = samplerId; } // texture/surface -> image XmlNode root = xmlEffect.OwnerDocument.DocumentElement; XmlNode imageInitFrom = root.SelectSingleNode("library_images/image[@id='" + imageId + "']/init_from"); if (imageInitFrom == null) { throw new Exception("Image not found: " + imageId); } texture.Filename = imageInitFrom.InnerText.Trim(); texture.Filename = texture.Filename.Replace("file://", ""); if (texture.Filename.Contains(".exr")) { // exr-images (32 bit per channel) are not supported right now // silently ignore // TODO: Implement Warning Log messages return(null); } return(texture); } }
private void Update(EvaluationContext context) { var resourceManager = ResourceManager.Instance(); var device = resourceManager.Device; Size2 size = Resolution.GetValue(context); if (size.Width == 0 || size.Height == 0) { size = context.RequestedResolution; } if (size.Width <= 0 || size.Height <= 0 || size.Width > MaximumTexture2DSize || size.Height > MaximumTexture2DSize) { Log.Warning("Invalid texture size: " + size); return; } _sampleCount = Multisampling.GetValue(context).Clamp(1, 32); bool generateMips = GenerateMips.GetValue(context); var withDepthBuffer = WithDepthBuffer.GetValue(context); UpdateTextures(device, size, TextureFormat.GetValue(context), withDepthBuffer ? Format.R32_Typeless : Format.Unknown, generateMips); var deviceContext = device.ImmediateContext; // Save settings in context var prevRequestedResolution = context.RequestedResolution; var prevViewports = deviceContext.Rasterizer.GetViewports <RawViewportF>(); var prevTargets = deviceContext.OutputMerger.GetRenderTargets(2, out var prevDepthStencilView); var prevObjectToWorld = context.ObjectToWorld; var prevWorldToCamera = context.WorldToCamera; var prevCameraToClipSpace = context.CameraToClipSpace; deviceContext.Rasterizer.SetViewport(new SharpDX.Viewport(0, 0, size.Width, size.Height, 0.0f, 1.0f)); deviceContext.OutputMerger.SetTargets(_multiSampledDepthBufferDsv, _multiSampledColorBufferRtv); // Clear var clear = Clear.GetValue(context); var c = ClearColor.GetValue(context); if (clear || !_wasClearedOnce) { try { deviceContext.ClearRenderTargetView(_multiSampledColorBufferRtv, new Color(c.X, c.Y, c.Z, c.W)); if (_multiSampledDepthBufferDsv != null) { deviceContext.ClearDepthStencilView(_multiSampledDepthBufferDsv, DepthStencilClearFlags.Depth, 1.0f, 0); } _wasClearedOnce = true; } catch { Log.Error($"{Parent.Symbol.Name}: Error clearing actual render target.", SymbolChildId); } } // Set default values for new sub tree context.RequestedResolution = size; context.SetDefaultCamera(); if (TextureReference.IsConnected) { var reference = TextureReference.GetValue(context); reference.ColorTexture = ColorTexture; reference.DepthTexture = DepthTexture; } // Render Command.GetValue(context); // Restore context context.ObjectToWorld = prevObjectToWorld; context.WorldToCamera = prevWorldToCamera; context.CameraToClipSpace = prevCameraToClipSpace; context.RequestedResolution = prevRequestedResolution; deviceContext.Rasterizer.SetViewports(prevViewports); deviceContext.OutputMerger.SetTargets(prevDepthStencilView, prevTargets); if (_sampleCount > 1) { try { device.ImmediateContext.ResolveSubresource(_multiSampledColorBuffer, 0, _resolvedColorBuffer, 0, _resolvedColorBuffer.Description.Format); if (withDepthBuffer) { ResolveDepthBuffer(); } } catch (Exception e) { Log.Error("resolving render target buffer failed:" + e.Message); } } if (generateMips) { deviceContext.GenerateMips(DownSamplingRequired ? _resolvedColorBufferSrv : _multiSampledColorBufferSrv); } // Clean up ref counts for RTVs for (int i = 0; i < prevTargets.Length; i++) { prevTargets[i]?.Dispose(); } prevDepthStencilView?.Dispose(); ColorBuffer.Value = ColorTexture; ColorBuffer.DirtyFlag.Clear(); DepthBuffer.Value = DepthTexture; DepthBuffer.DirtyFlag.Clear(); }
public PropertyField() { texture = new TextureReference(); }
public string EvaluateTextureName(Texture texture, TextureReference reference) { var baseName = EvaluateTextureName(texture); return(GetTextureOutputName(baseName, reference)); }
public void Initialize(string name, string shortName, TextureReference tex2d, TextureReference tex3d, bool diagonal) { Name = name; ShortName = shortName; Tex2d = tex2d; Tex3d = tex3d; Diagonal = diagonal; }
public void Initialize(Model bottomModel, Model normalModel, string name, string shortName, Color color, float scale, bool houseWall, bool arch, bool archBuildable, Materials materials, TextureReference icon) { BottomModel = bottomModel; NormalModel = normalModel; Name = name; ShortName = shortName; Color = color; Scale = scale; HouseWall = houseWall; Arch = arch; ArchBuildable = archBuildable; Icon = icon; if (materials != null) { Materials = materials; } else { Materials = new Materials(); } }