public XTemplate Clone(ITemplate original) { try { var template = new XTemplate() { Width = original.Width, Height = original.Height, Name = original.Name, Grid = original.Grid, Table = original.Table, Frame = original.Frame }; var json = Serializer.Serialize(template); var copy = Serializer.Deserialize <XTemplate>(json); return(copy); } catch (Exception ex) { if (Log != null) { Log.LogError("{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace); } } return(null); }
private void AddSourceTables(XTemplate xTemplate) { Progress?.Report("Adding source tables"); ISet <string> tableNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (XField xField in xTemplate.XProject.XFields) { if (xField.FieldType.IsTableBased()) { tableNames.Add(xField.SourceTableName); } else if (xField.FieldType == MetaFieldType.Grid) { DataTable gridColumns = Metadata.GetGridColumns(xField.FieldId); foreach (DataRow gridColumn in gridColumns.Rows) { if (gridColumn.Field <MetaFieldType>(ColumnNames.FIELD_TYPE_ID).IsTableBased()) { tableNames.Add(gridColumn.Field <string>(ColumnNames.SOURCE_TABLE_NAME)); } } } } foreach (string tableName in tableNames.OrderBy(tableName => tableName, StringComparer.OrdinalIgnoreCase)) { if (string.IsNullOrEmpty(tableName)) { continue; } Progress?.Report($"Adding source table: {tableName}"); DataTable table = Metadata.GetCodeTableData(tableName); table.TableName = tableName; xTemplate.Add(XTable.Create(ElementNames.SourceTable, table)); } }
private DataView GetDataView() { DataView view = new DataView() { ID = "DataView1" }; XTemplate tpl = new XTemplate() { ID = "XTemplate1" }; tpl.Html = "<tpl for=\".\">" + "<div class=\"item\">" + "<tpl if=\"!Ext.isIE6\">" + "<img src=\"../../Shared/images/touch-icons/{thumb}\" />" + "</tpl>" + "<tpl if=\"Ext.isIE6\">" + "<div style=\"position:relative;width:74px;height:74px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"../../Shared/images/touch-icons/{thumb}\")></div>" + "</tpl>" + "<h3>{name}</h3>" + "</div>" + "</tpl>"; view.Tpl = tpl; view.Plugins.Add(new DataViewAnimated()); view.ItemSelector = "div.item"; view.Store.Add(this.GetStore()); return(view); }
/// <summary> /// /// </summary> /// <param name="surl1"></param> /// <param name="surl2"></param> protected void ApplyImage(string surl1, string surl2) { try { var tpl = new XTemplate { ID = "Template1" }; tpl.Html = @"<div class=""details""> <tpl for="".""> <center> <img src=""{url1}"" onload=""resizeimg(this);"" alt=""车辆图片(双击图片进行放大)"" onDblClick='OpenPicPage(this.src)'; /> <img src=""{url2}"" onload=""resizeimg(this);"" alt=""车辆图片(双击图片进行放大)"" onDblClick=""OpenPicPage(this.src)"";/> </center> </tpl> </div>" ; tpl.Overwrite(this.ImagePanel, new { url1 = surl1, url2 = surl2 }); tpl.Render(); } catch (Exception ex) { ILog.WriteErrorLog(ex); logManager.InsertLogError("TgsPassCarAmply.aspx-ApplyImage", ex.Message + ";" + ex.StackTrace, "ApplyImage has an exception"); } }
protected override string Render() { dynamic xt = new XTemplate(Layout.IntranetControllerView); xt.UserName = this.Context.Engine.GetSession().User.Description; xt.TemplateName = this.Model.ViewMapper.TridionTemplate.Title; xt.TemplateTypeName = this.Model.ViewMapper.TridionTemplate is ComponentTemplate ? "component template" : "page template"; xt.ErrorMessage = this.Model.ViewMapper.Success ? "Oops, view not found!" : "Oops, invalid template name!"; xt.ControllerTypeName = this.Model.GetType().Name; xt.ViewFullTypeName = this.Model.ViewMapper.ViewFullTypeName; xt.ProjectNamespace = this.Model.ViewMapper.ProjectRootNamespace; xt.TemplateNameRegexPattern = this.Model.ViewMapper.TemplateNameRegexPattern; xt.Parse(!this.Model.ViewMapper.Success ? "root.invalidTemplateName" : "root.viewNotFound"); if (!string.IsNullOrEmpty(this.Model.ProjectDocumentationUrl)) { xt.ProjectDocumentationUrl = this.Model.ProjectDocumentationUrl; xt.Parse("root.projectDocumentation"); } return(xt.ToString()); }
public XTemplate Create() { Progress?.Report($"Creating template: {DisplayName}"); XTemplate xTemplate = CreateCore(); AddSourceTables(xTemplate); AddGridTables(xTemplate); xTemplate.OnCreated(); return(xTemplate); }
protected dynamic NewXTemplate(string template) { var xt = new XTemplate(template); // By default XTemplate replaces an unassigned variable with an empty string. // If you want to keep this behaviour, then remove the statement below. xt.ReserveUnassignedVariableTags = true; return(xt); }
protected override XTemplate CreateCore() { XTemplate xTemplate = new XTemplate(TemplateLevel.View) { Name = View.Name }; XProject xProject = new XProject(); xTemplate.Add(xProject); AddView(View, xProject); return(xTemplate); }
protected override string Render() { // Instantiates a new XTemplate object with a parameter which is the // content of the embedded file XTemplateExample1View.html. The content // of this file is exposed by the resources file Layout through the property // Layout.XTemplateExample1View XTemplate xt = new XTemplate(Layout.XTemplateExample1View); // Assigns User.Description to variable {UserName}. // Assigns DateTime.Now.ToString("D") to variable {CurrentDate}. xt.Assign("UserName", this.Model.Session.User.Description); xt.Assign("CurrentDate", DateTime.Now.ToString("D")); // Parses the "administrator" block, if the current user is Administrator. if (this.Model.Session.User.IsSystemAdministrator) { // Assigns value "God" to variable {Role}. xt.Assign("Role", "Root"); // Block "administrator" is a child block of the "root" block. // The "root" block is the most outer block, which is a special // block. You don't have to explicitly specify the "root" block // in the markup. // The given block name for the .Parse() method has to be a fully // qualified block name. In this case "root.administrator". xt.Parse("root.administrator"); } /* ******************************* * Calling the .ToString() method without parameter returns the parsed "root" block * and is equal to the following two statements: * * xt.Parse("root"); * xt.ToString("root"); * * Or the following statement: * * xt.ToString("root"); * ******************************* */ return(xt.ToString()); }
private void AddGridTables(XTemplate xTemplate) { Progress?.Report("Adding grid tables"); foreach (XField xField in xTemplate.XProject.XFields) { if (xField.FieldType != MetaFieldType.Grid) { continue; } Progress?.Report($"Adding grid table: {xField.Name}"); DataTable table = Metadata.GetGridColumns(xField.FieldId); table.TableName = xField.Name; xTemplate.Add(XTable.Create(ElementNames.GridTable, table)); } }
protected override XTemplate CreateCore() { XTemplate xTemplate = new XTemplate(TemplateLevel.Project) { Name = Project.Name, Description = Project.Description }; XProject xProject = XProject.Create(Project); xTemplate.Add(xProject); foreach (View view in Project.Views) { AddView(view, xProject); } return(xTemplate); }
/// <summary> /// /// </summary> /// <param name="surl1"></param> /// <param name="surl2"></param> protected void ApplyImage(string surl1, string surl2) { try { var tpl = new XTemplate { ID = "Template1" }; if (surl1 != string.Empty || surl2 != string.Empty) { tpl.Html = @"<div class=""details""> <tpl for="".""> <center> <img src=""{url1}"" onload=""resizeimg(this);"" alt=""车辆图片(双击图片进行放大)"" onclick=""$.openPhotoGalleryXiangqing(this);"" class=""photo""; /> <img src=""{url2}"" onload=""resizeimg(this);"" alt=""车辆图片(双击图片进行放大)"" onclick=""$.openPhotoGalleryXiangqing(this);"" class=""photo""; /> </center> </tpl> </div>" ; tpl.Overwrite(this.ImagePanel, new { url1 = surl1, url2 = surl2 }); } else { tpl.Html = @"<div class=""details""> <tpl for="".""> <center> <img src=""{url1}"" onload=""resizeimg(this);"" /> <img src=""{url2}"" onload=""resizeimg(this);"" /> </center> </tpl> </div>" ; tpl.Overwrite(this.ImagePanel, new { url1 = surl1, url2 = surl2 }); } tpl.Render(); } catch (Exception ex) { ILog.WriteErrorLog(ex); logManager.InsertLogError("AlarmMonitor.aspx-ApplyImage", ex.Message + ";" + ex.StackTrace, "ApplyImage has an exception"); } }
protected override XTemplate CreateCore() { XTemplate xTemplate = new XTemplate(TemplateLevel.Page) { Name = Page.Name }; XProject xProject = new XProject(); xTemplate.Add(xProject); XView xView = new XView { CheckCode = Page.GetView().CheckCode }; xProject.Add(xView); AddPage(Page, xView); return(xTemplate); }
/// <summary> /// 将报警信息显示至textpanel /// </summary> /// <param name="text"></param> protected void ApplyText(string text) { try { var tpl = new XTemplate { ID = "Template1" }; tpl.Html = @"<div class=""details""> <tpl for="".""> <center>{content} </center> </tpl> </div>"; tpl.Overwrite(this.TextPanel, new { content = text }); tpl.Render(); } catch (Exception ex) { ILog.WriteErrorLog(ex); logManager.InsertLogError("FlowMonitor.aspx-ApplyText", ex.Message, "ApplyText has an exception"); } }
/// <summary>Загружает проект кодогенерации</summary> public GenerationProject Load() { XDocument document = XDocument.Load(_fileName); if (document.Root == null) { throw new ApplicationException(); } // ReSharper disable PossibleNullReferenceException return(new GenerationProject( document.Root.Element("GenerationTasks").Elements() .Select(XGenerationTask => new GenerationTask( XGenerationTask.Element("Globals").Elements() .ToDictionary(XGlobalVariable => XGlobalVariable.Name.LocalName, XGlobalVariable => XGlobalVariable.Value), XGenerationTask.Element("Actions").Elements() .Select(XAction => new GenerationActionCalling(XAction.Name.LocalName, (string)XAction.Attribute("file"))) .ToList(), LoadItems(XGenerationTask.Element("SourceItems")))) .ToList(), document.Root.Element("GenerationActions").Elements() .Select(XAction => new GenerationAction(XAction.Name.LocalName, XAction.Elements("InjectionTemplate") .Select(XTemplate => new InjectionTemplate((string)XTemplate.Attribute("anchor"), XTemplate.Nodes().OfType <XText>().First().Value.TrimEnd().Trim('\n').TrimIndents(), XTemplate.Elements("Template").ToDictionary( XInternalTemplate => XInternalTemplate.Attribute("name").Value, XInternalTemplate => XInternalTemplate.Value.TrimEnd().Trim('\n').TrimIndents()), (string)XTemplate.Attribute("filter"))) .ToList())) .ToList() )); // ReSharper restore PossibleNullReferenceException }
private void BuildTemplate() { this.template = new XTemplate(); this.template.Html = @" <div id=""preview-tpl""> <div class=""post-data""> <span class=""post-date"">{pubDate:date(""M j, Y, g:i a"")}</span> <h3 class=""post-title"">{title}</h3> <h4 class=""post-author"">Autor: {author:defaultValue(""Desconhecido"")}</h4> </div> <div class=""post-body"">{content:this.getBody}</div> </div>"; this.template.Functions.Add(new JFunction { Name = "getBody", Handler = "return Ext.util.Format.stripScripts(v || all.description);", Args = new string[] { "v", "all" } }); this.Controls.Add(this.template); this.LazyItems.Add(this.template); }
/// <summary> /// 将类对象转化成代码文本 /// </summary> /// <param name="proto_class">类结构</param> /// <param name="template_str">模板文本</param> /// <returns></returns> public static string parse(Proto_Class proto_class, string template_str, bool showHead) { var template = new XTemplate(template_str); template.setCondition("HEAD", showHead); template.setValue("#CLASS_TYPE#", proto_class.Class_Type); template.setValue("#CLASS_NAME#", proto_class.Class_Name); template.setValue("#CLASS_COMMENT#", proto_class.Class_Comment); template.setCondition("DESERIALIZE_CLASS", proto_class.Class_Type == "class"); template.setCondition("SERIALIZE_CLASS", proto_class.Class_Type == "class"); if (template.beginLoop("#VARIABLES#")) { foreach (var item in proto_class.Class_Variables) { template.setCondition("SINGLE", !item.IsArray); template.setCondition("ARRAY", item.IsArray); template.setValue("#VAR_TYPE#", item.Var_Type); template.setValue("#VAR_NAME#", item.Var_Name); template.setValue("#VAR_COMMENT#", item.Var_Comment); template.nextLoop(); } template.endLoop(); } if (template.beginLoop("#DESERIALIZE_PROCESS#")) { foreach (var item in proto_class.Class_Variables) { template.setCondition("SINGLE", !item.IsArray); template.setCondition("ARRAY", item.IsArray); template.setValue("#VAR_TYPE#", item.Var_Type); template.setValue("#VAR_NAME#", item.Var_Name); template.setValue("#VAR_COMMENT#", item.Var_Comment); template.nextLoop(); } template.endLoop(); } if (template.beginLoop("#DESERIALIZE_RETURN#")) { foreach (var item in proto_class.Class_Variables) { template.setValue("#VAR_TYPE#", item.Var_Type); template.setValue("#VAR_NAME#", item.Var_Name); template.setValue("#VAR_COMMENT#", item.Var_Comment); template.nextLoop(); } template.endLoop(); } if (template.beginLoop("#SERIALIZE_PROCESS#")) { foreach (var item in proto_class.Class_Variables) { template.setCondition("SINGLE", !item.IsArray); template.setCondition("ARRAY", item.IsArray); template.setValue("#VAR_TYPE#", item.Var_Type); template.setValue("#VAR_NAME#", item.Var_Name); template.setValue("#VAR_COMMENT#", item.Var_Comment); template.nextLoop(); } template.endLoop(); } return(template.getContent()); }
/// <summary> /// 将类对象转化成代码文本 /// </summary> /// <param name="proto_class">类结构</param> /// <param name="template_str">模板文本</param> /// <returns></returns> public static string Parse(ClassInfo proto_class, string template_str, bool showHead) { var template = new XTemplate(template_str); template.setCondition("HEAD", showHead); template.setValue("#CLASS_TYPE#", "class"); template.setValue("#CLASS_NAME#", proto_class.name); template.setValue("#CLASS_COMMENT#", "Auto Created " + proto_class.name); // 设置Key { PropertyInfo keyProperty = null; foreach (var item in proto_class.propertys) { if (item.key) { keyProperty = item; } } if (keyProperty == null) { keyProperty = proto_class.propertys[0]; } template.setValue("#KEY_TYPE#", keyProperty.type); template.setValue("#KEY_NAME#", keyProperty.name); } template.setCondition("DESERIALIZE_CLASS", true); template.setCondition("SERIALIZE_CLASS", true); if (template.beginLoop("#VARIABLES#")) { foreach (var item in proto_class.propertys) { template.setCondition("SINGLE", !item.IsArray); template.setCondition("ARRAY", item.IsArray); template.setValue("#VAR_TYPE#", item.Type); template.setValue("#VAR_NAME#", item.name); template.setValue("#VAR_COMMENT#", item.desc); template.nextLoop(); } template.endLoop(); } if (template.beginLoop("#DESERIALIZE_PROCESS#")) { foreach (var item in proto_class.propertys) { template.setCondition("SINGLE", !item.IsArray); template.setCondition("ARRAY", item.IsArray); template.setValue("#VAR_TYPE#", item.Type); template.setValue("#VAR_NAME#", item.name); template.setValue("#VAR_COMMENT#", item.desc); template.nextLoop(); } template.endLoop(); } if (template.beginLoop("#DESERIALIZE_RETURN#")) { foreach (var item in proto_class.propertys) { template.setValue("#VAR_TYPE#", item.Type); template.setValue("#VAR_NAME#", item.name); template.setValue("#VAR_COMMENT#", item.desc); template.nextLoop(); } template.endLoop(); } if (template.beginLoop("#SERIALIZE_PROCESS#")) { foreach (var item in proto_class.propertys) { template.setCondition("SINGLE", !item.IsArray); template.setCondition("ARRAY", item.IsArray); template.setValue("#VAR_TYPE#", item.Type); template.setValue("#VAR_NAME#", item.name); template.setValue("#VAR_COMMENT#", item.desc); template.nextLoop(); } template.endLoop(); } return(template.getContent()); }
public Directive(string name, IDictionary<string, string> parameters, XTemplate.Templating.Block block) { this._Name = name; this._Parameters = parameters; this._Block = block; }
protected TemplateInstantiator(XTemplate xTemplate, IMetadataProvider metadata) { XTemplate = xTemplate; Metadata = metadata; }
public PageTemplateInstantiator(XTemplate xTemplate, View view) : base(xTemplate, view.GetMetadata()) { View = view; }
public ViewTemplateInstantiator(XTemplate xTemplate, Project project) : base(xTemplate, project.Metadata) { Project = project; }
public static XFile ImportOBJ(string filename, Matrix transform, bool flipV = true, bool removeTextureExtension = true) { XFile result = new XFile(new XHeader(3, 3, XHeader.HeaderFormat.Binary, 32)); bool hasColor = false; bool hasMRGB = false; result.Templates.Add(XReader.NativeTemplates["XSkinMeshHeader"]); result.Templates.Add(XReader.NativeTemplates["VertexDuplicationIndices"]); result.Templates.Add(XReader.NativeTemplates["SkinWeights"]); XTemplate vectorTemplate = XReader.NativeTemplates["Vector"]; XObject FrameObject = new XObject(new XToken(XToken.TokenID.NAME) { NameData = "Frame" }, "Root"); XObject FrameTransformMatrix = new XObject(new XToken(XToken.TokenID.NAME) { NameData = "FrameTransformMatrix" }); FrameTransformMatrix.Members.Add(new XObjectMember("frameMatrix", new XToken(XToken.TokenID.NAME) { NameData = "Matrix4x4" }, new XObjectStructure(XReader.NativeTemplates["Matrix4x4"], new XObjectMember("matrix", new XToken(XToken.TokenID.FLOAT), 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)))); FrameObject.Children.Add(new XChildObject(FrameTransformMatrix, false)); // Read the obj file as one whole mesh XObject MeshObject = XReader.NativeTemplates["Mesh"].Instantiate(); FrameObject.Children.Add(new XChildObject(MeshObject, false)); XObject MeshNormalsObject = XReader.NativeTemplates["MeshNormals"].Instantiate(); MeshObject.Children.Add(new XChildObject(MeshNormalsObject, false)); XObject MeshTextureCoordsObject = XReader.NativeTemplates["MeshTextureCoords"].Instantiate(); MeshObject.Children.Add(new XChildObject(MeshTextureCoordsObject, false)); XObject MeshMaterialListObject = XReader.NativeTemplates["MeshMaterialList"].Instantiate(); XObject MeshVertexColorsObject = XReader.NativeTemplates["MeshVertexColors"].Instantiate(); // Store the positions and UVs so we can weld the pairs together later List <Vector3> positions = new List <Vector3>(); List <Vector2> uvs = new List <Vector2>(); List <Vector4> colors = new List <Vector4>(); Dictionary <int, int> positionColors = new Dictionary <int, int>(); // Maps verteices by index to colors. List <List <Tuple <int, int> > > faces = new List <List <Tuple <int, int> > >(); // list of faces (list of <Pos index, UV index>). Not pretty, but it works. List <string> materialNames = new List <string>(); // Store the names of materials so we can look up indexes to them. int currentMaterial = 0; using (System.IO.StreamReader reader = new System.IO.StreamReader(filename)) { while (!reader.EndOfStream) { string line = reader.ReadLine().Trim(); if (String.IsNullOrEmpty(line)) { continue; } if (line.StartsWith("#")) { if (line.StartsWith("#MRGB")) { if (!hasMRGB) { MeshObject.Children.Add(new XChildObject(MeshVertexColorsObject, false)); hasMRGB = true; } // Read ZBrush Polypaint-style vertex colors line = line.Substring(6); // Trim off leading '#MRGB ' for (int i = 0; i < line.Length / 8; i++) { float mask = Int32.Parse(line.Substring(i * 8, 2), System.Globalization.NumberStyles.AllowHexSpecifier) / 255.0f; float red = Int32.Parse(line.Substring(i * 8 + 2, 2), System.Globalization.NumberStyles.AllowHexSpecifier) / 255.0f; float green = Int32.Parse(line.Substring(i * 8 + 4, 2), System.Globalization.NumberStyles.AllowHexSpecifier) / 255.0f; float blue = Int32.Parse(line.Substring(i * 8 + 6, 2), System.Globalization.NumberStyles.AllowHexSpecifier) / 255.0f; colors.Add(new Vector4(red, green, blue, mask)); // Treat 'mask' like alpha } } else { continue; } } string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (parts[0] == "v") { Vector4 v = Vector3.Transform(new Vector3(Single.Parse(parts[1]), Single.Parse(parts[2]), Single.Parse(parts[3])), transform); //MeshObject["vertices"].Values.Add(Vector(new Vector3(v.X, v.Y, v.Z))); positions.Add(new Vector3(v.X, v.Y, v.Z)); } else if (parts[0] == "vn") { Vector4 v = Vector4.Transform(new Vector4(Single.Parse(parts[1]), Single.Parse(parts[2]), Single.Parse(parts[3]), 0.0f), transform); MeshNormalsObject["normals"].Values.Add(Vector(new Vector3(v.X, v.Y, v.Z))); } else if (parts[0] == "vt") { Vector2 coords = new Vector2(Single.Parse(parts[1]), Single.Parse(parts[2])); if (flipV) { coords.Y = 1.0f - coords.Y; } //MeshTextureCoordsObject["textureCoords"].Values.Add(TexCoord(coords)); uvs.Add(coords); } else if (parts[0] == "vc") { if (!hasColor) { MeshObject.Children.Add(new XChildObject(MeshVertexColorsObject, false)); hasColor = true; } Vector4 color = new Vector4(Single.Parse(parts[1]), Single.Parse(parts[2]), Single.Parse(parts[3]), Single.Parse(parts[4])); colors.Add(color); } else if (parts[0] == "f") { // Handle each vertex in the polygon List <int> normIndices = new List <int>(); List <Tuple <int, int> > face = new List <Tuple <int, int> >(); for (int i = 1; i < parts.Length; i++) { string[] components = parts[i].Split('/'); int pindex = Int32.Parse(components[0]) - 1; int uvindex = -1; if (components.Length > 1 && components[1].Length > 0) { uvindex = Int32.Parse(components[1]) - 1; } else { Console.WriteLine("[WARNING]: No UVs! Please add some."); } if (components.Length > 2 && components[2].Length > 0) { normIndices.Add(Int32.Parse(components[2]) - 1); } else { Console.WriteLine("[WARNING]: No normals! Please add some."); } if (components.Length > 3 && components[3].Length > 0) { // Set / overwrite color for position pindex. int colorIndex = Int32.Parse(components[3]) - 1; if (!positionColors.ContainsKey(pindex)) { positionColors.Add(pindex, colorIndex); } else { positionColors[pindex] = colorIndex; } } face.Add(new Tuple <int, int>(pindex, uvindex)); } if (normIndices.Count > 0) { MeshNormalsObject["faceNormals"].Values.Add(Face(normIndices)); } // Texture coordinates are directly linked to vertices faces.Add(face); MeshMaterialListObject["faceIndexes"].Values.Add(currentMaterial); } else if (parts[0] == "usemtl") { string matName = parts[1]; if (materialNames.Contains(matName)) { currentMaterial = materialNames.IndexOf(matName); } else { Console.WriteLine(" [WARNING]: OBJ Material '" + matName + "' not found."); } } else if (parts[0] == "mtllib") { string mtlFilename = line.Substring("mtllib ".Length); mtlFilename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), mtlFilename); // Parse material library! if (!System.IO.File.Exists(mtlFilename)) { Console.WriteLine("[WARNING]: OBJ references material library '" + mtlFilename + "' which does not exist."); } else { using (System.IO.StreamReader mtlReader = new System.IO.StreamReader(mtlFilename)) { XObject MaterialObject = null; while (!mtlReader.EndOfStream) { string mtlLine = mtlReader.ReadLine().Trim(); if (String.IsNullOrEmpty(mtlLine)) { continue; } string[] mtlParts = mtlLine.Split(' '); if (mtlParts[0] == "newmtl") { if (MaterialObject != null) { MeshMaterialListObject.Children.Add(new XChildObject(MaterialObject, false)); if (MaterialObject.Children.Count == 0) { Console.WriteLine("[WARNING]: Material at index " + (MeshMaterialListObject.Children.Count - 1) + " doesn't have a texture filename!"); } } MaterialObject = XReader.NativeTemplates["Material"].Instantiate(); MaterialObject["faceColor"].Values.Add(ColorRGBA(1.0, 1.0, 1.0, 1.0)); MaterialObject["specularColor"].Values.Add(ColorRGB(1.0, 1.0, 1.0)); MaterialObject["power"].Values.Add(0.0); MaterialObject["emissiveColor"].Values.Add(ColorRGB(0.0, 0.0, 0.0)); materialNames.Add(mtlLine.Substring(7)); } else if (mtlParts[0] == "Kd") { MaterialObject["faceColor"].Values[0] = (ColorRGBA(Double.Parse(mtlParts[1]), Double.Parse(mtlParts[2]), Double.Parse(mtlParts[3]), 1.0)); } else if (mtlParts[0] == "Ks") { MaterialObject["specularColor"].Values[0] = (ColorRGB(Double.Parse(mtlParts[1]), Double.Parse(mtlParts[2]), Double.Parse(mtlParts[3]))); } else if (mtlParts[0] == "Ke") { MaterialObject["emissiveColor"].Values[0] = (ColorRGB(Double.Parse(mtlParts[1]), Double.Parse(mtlParts[2]), Double.Parse(mtlParts[3]))); } else if (mtlParts[0] == "Ns") { MaterialObject["power"].Values[0] = (Double.Parse(mtlParts[1])); } else if (mtlParts[0] == "Tr") { (MaterialObject["faceColor"].Values[0] as XObjectStructure)["alpha"].Values[0] = 1.0 - Double.Parse(mtlParts[1]); } else if (mtlParts[0] == "d") { (MaterialObject["faceColor"].Values[0] as XObjectStructure)["alpha"].Values[0] = Double.Parse(mtlParts[1]); } else if (mtlParts[0] == "map_Kd") { XObject texFilename = XReader.NativeTemplates["TextureFilename"].Instantiate(); string texname = mtlLine.Substring(7); if (removeTextureExtension) { texname = System.IO.Path.GetFileNameWithoutExtension(texname); } texFilename["filename"].Values.Add(texname); MaterialObject.Children.Add(new XChildObject(texFilename, false)); } } if (MaterialObject != null) { MeshMaterialListObject.Children.Add(new XChildObject(MaterialObject, false)); } } } } else { System.Diagnostics.Debug.WriteLine(" [INFO]: Ignored OBJ line '" + line + "'."); } } } // Fix up relative indices List <List <Tuple <int, int> > > oldFaces = faces; faces = new List <List <Tuple <int, int> > >(); foreach (List <Tuple <int, int> > face in oldFaces) { List <Tuple <int, int> > newFace = new List <Tuple <int, int> >(); foreach (Tuple <int, int> vert in face) { int vIndex = vert.Item1; if (vIndex < 0) { vIndex = positions.Count + vIndex + 1; } int uvIndex = vert.Item2; if (uvIndex < 0) { uvIndex = uvs.Count + uvIndex + 1; } newFace.Add(new Tuple <int, int>(vIndex, uvIndex)); } faces.Add(newFace); } // Weld all the used combinations of <position, uv>. List <List <int> > newFaces = null; List <Tuple <Vector3, Vector4> > inputs = new List <Tuple <Vector3, Vector4> >(); for (int i = 0; i < positions.Count; i++) { if (hasColor) { // Make sure that position index has been assigned a color by a face set. (*/*/*/*) if (!positionColors.ContainsKey(i)) { throw new Exception("ImportOBJ: Vertex color was not specified for position index " + i + "!"); } } Vector4 color = Vector4.Zero; if (hasColor) { color = colors[positionColors[i]]; } else if (hasMRGB) { color = colors[i]; } inputs.Add(new Tuple <Vector3, Vector4>(positions[i], color)); } List <Tuple <Vector3, Vector4, Vector2> > newPositionUVs = WeldTextureCoordinates(inputs, uvs, faces, out newFaces); int vertex = 0; foreach (Tuple <Vector3, Vector4, Vector2> vdata in newPositionUVs) { MeshObject["vertices"].Values.Add(Vector(vdata.Item1)); MeshTextureCoordsObject["textureCoords"].Values.Add(TexCoord(vdata.Item3)); if (hasColor || hasMRGB) { MeshVertexColorsObject["vertexColors"].Values.Add(IndexedColor(vertex, vdata.Item2)); } vertex++; } foreach (List <int> face in newFaces) { MeshObject["faces"].Values.Add(Face(face)); } MeshObject.Children.Add(new XChildObject(MeshMaterialListObject, false)); // Fix all the counts. MeshObject["nVertices"].Values.Add(MeshObject["vertices"].Values.Count); MeshObject["nFaces"].Values.Add(MeshObject["faces"].Values.Count); MeshNormalsObject["nNormals"].Values.Add(MeshNormalsObject["normals"].Values.Count); MeshNormalsObject["nFaceNormals"].Values.Add(MeshNormalsObject["faceNormals"].Values.Count); MeshTextureCoordsObject["nTextureCoords"].Values.Add(MeshTextureCoordsObject["textureCoords"].Values.Count); MeshVertexColorsObject["nVertexColors"].Values.Add(MeshVertexColorsObject["vertexColors"].Values.Count); MeshMaterialListObject["nMaterials"].Values.Add(MeshMaterialListObject.Children.Count); // Because MeshMaterialList is a restricted template, all children are guaranteed to be Material objects. MeshMaterialListObject["nFaceIndexes"].Values.Add(MeshMaterialListObject["faceIndexes"].Values.Count); result.Objects.Add(FrameObject); return(result); }
internal TemplateException(XTemplate.Templating.Block block, string message) : base(message + block.ToFullString()) { this.Block = block; }