private static MDLObject LoadMDLMesh(System.IO.BinaryReader br) { MDLMesh mesh = new MDLMesh(); mesh.nvertex = br.ReadInt32(); mesh.nfaces = br.ReadInt32(); mesh.vertices = new MDLVertice[mesh.nvertex]; for (int n = 0; n < mesh.nvertex; n++) { // read vertice MDLVertice vert = new MDLVertice(); vert.x = br.ReadSingle(); vert.y = br.ReadSingle();; vert.z = br.ReadSingle();; vert.mx = br.ReadSingle();; vert.my = br.ReadSingle();; vert.nx = br.ReadSingle();; vert.ny = br.ReadSingle();; vert.nz = br.ReadSingle();; mesh.vertices[n] = vert; } mesh.faces = new ushort[mesh.nfaces]; for (int n = 0; n < mesh.nfaces; n++) { mesh.faces[n] = br.ReadUInt16(); } MDLObject mdlo = MDLFile.NewMDLObject(); mdlo.mesh = mesh; mdlo.type = MDLType.mdl_mesh; return(mdlo); }
private static Mesh GenerateMesh(MDLFile mdl, string destPath) { var geometry = mdl.geometry; var verts = geometry.frames[0].verts; Mesh mesh = new Mesh(); var rotation = Quaternion.AngleAxis(-90, Vector3.up); Vector3[] vertices = new Vector3[verts.Length]; int[] triangles = new int[verts.Length]; for (int i = 0; i < verts.Length; i += 3) { vertices[i] = rotation * BSPFile.TransformVector(verts[i]); vertices[i + 1] = rotation * BSPFile.TransformVector(verts[i + 1]); vertices[i + 2] = rotation * BSPFile.TransformVector(verts[i + 2]); triangles[i] = i + 2; triangles[i + 1] = i + 1; triangles[i + 2] = i; } mesh.vertices = vertices; mesh.triangles = triangles; mesh.uv = geometry.uvs; mesh.RecalculateNormals(); var meshPath = destPath + "/" + mdl.name + "_mesh.asset"; AssetDatabase.CreateAsset(mesh, meshPath); return(AssetDatabase.LoadAssetAtPath <Mesh>(meshPath)); }
public Graph(MDLFile file) { //states var logicView = (from property in (from property in (from element in file.Elements.OfType <MdlReader.Object>() where element.Name == "\"Logical View\"" select element.Properties).First() where property.Name == "root_category" select property.Value).Cast <ElementVal>() select property.Value).Cast <MdlReader.Object>().First(); var stateMachine = (MdlReader.Object)(from property in logicView.Properties where property.Name == "statemachine" select property.Value).Cast <MdlReader.ElementVal>().First().Value; var states = (MdlReader.List)(from property in stateMachine.Properties where property.Name == "states" select property.Value).Cast <MdlReader.ElementVal>().First().Value; var transitions = (MdlReader.List)(from property in stateMachine.Properties where property.Name == "transitions" select property.Value).Cast <MdlReader.ElementVal>().First().Value; Nodes = new Dictionary <string, Node>(); //create node foreach (MdlReader.Object obj in states.Elements) { Node node = new Node(); node.Name = obj.Name; node.Quid = (from property in obj.Properties where property.Name == "quid" select property.Value).Cast <StringVal>().First().Value; node.Type = (from property in obj.Properties where property.Name == "type" select property.Value).Cast <StringVal>().First().Value; if (node.Type == "\"StartState\"") { Start = node; } else if (node.Type == "\"EndState\"") { End = node; } Nodes.Add(node.Quid, node); } //create edges foreach (MdlReader.Object obj in transitions.Elements) { string supplier = (from property in obj.Properties where property.Name == "supplier_quidu" select property.Value).Cast <StringVal>().First().Value; string client = (from property in obj.Properties where property.Name == "client_quidu" select property.Value).Cast <StringVal>().First().Value; Nodes[client].To.Add(supplier); Nodes[supplier].From.Add(client); // //add in degree // ++Nodes[client].Out; // //add out degree // ++Nodes[supplier].In; } }
private void ParseMdlFileButton_Click(object sender, EventArgs e) { MdlParser parser = new MdlParser(MdlFilePathTextBox.Text); MDLFile file = parser.Parse(); // Graph graph = new Graph(file); // var verticesPaths = graph.VerticesCover(); VerticesCover verticesCover = new VerticesCover(new Graph(file)); OutPutTextBox.Text = "满足所有点覆盖情况下的最少路径\r\n" + string.Join("\r\n", verticesCover.VerticesCoverPaths()); // var edgesPaths = graph.EdgesCover(); EdgesCover edgesCover = new EdgesCover(new Graph(file)); OutPutTextBox.Text += "\r\n满足所有边覆盖情况下的所有路径\r\n" + string.Join("\r\n", edgesCover.EdgesCoverPaths()); }
private fileType LoadFile(System.IO.FileInfo fi, string requestedName, out string varname, out Bitmap output) { fileType returnType = fileType.ImageMdl; varname = ""; output = null; if (fi.Name.EndsWith(".mdl")) { MDL.MDLFile test = new MDL.MDLFile(); bool valid = test.ReadFromFile(fi.FullName); if (valid) { currentBinaryMDL = test; returnType = fileType.ModelMdl; if (test.RootObject.Where(x => x.type == MDLType.mdl_image).Count() > 0) { output = test.RootObject.First(x => x.type == MDLType.mdl_image).image.myBitmap; returnType = fileType.ImageMdl; } } else { currentBinaryMDL = null; System.IO.FileStream fs; try { fs = fi.OpenRead(); using (System.IO.BinaryReader br = new System.IO.BinaryReader(fs)) { br.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); output = LoadTextBmpMDL(fi, out currentReferencedFiles, requestedName, out varname); returnType = fileType.TextMdl; } } catch (Exception ex) { } } } else { returnType = fileType.Image; currentBinaryMDL = null; output = (Bitmap)Bitmap.FromFile(fi.FullName); } return(returnType); }
private static MDL CreateMDL(DataStream ds, string destPath, string name) { MDLFile mdl = new MDLFile(ds, name); var mesh = GenerateMesh(mdl, destPath); var skins = GenerateSkins(mdl, destPath); GenerateAnimations(mdl, destPath); var asset = ScriptableObject.CreateInstance <MDL>(); asset.name = name; asset.mesh = mesh; asset.materials = skins; return(asset); }
private void GenerateStateDiagramButton_Click(object sender, EventArgs e) { MdlParser parser = new MdlParser(MdlFilePathTextBox.Text); MDLFile file = parser.Parse(); Graph graph = new Graph(file); SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "PlantUML file(*.wsd)|*.wsd"; if (dialog.ShowDialog() == DialogResult.OK) { File.WriteAllText(dialog.FileName, graph.ToPlantuml()); Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c plantuml " + dialog.FileName; process.Start(); process.WaitForExit(); PlantUML plantUML = new PlantUML(dialog.FileName.Replace(".wsd", ".png")); plantUML.Show(); } }
private List <Bitmap> GetReferencedImages(MDLFile currentBinaryMDL) { List <Bitmap> retunvalue = new List <Bitmap>(); List <string> possibleNS = currentBinaryMDL.header.NameSpaces.Where(x => x != "model" && x != "effect").ToList(); // lets loop over our possible NS foreach (var imageNameSpace in possibleNS) { IEnumerable <FileInfo> myFiles = listBox1.Items.OfType <FileInfo>(); foreach (var fileInfo in myFiles.Where(x => x.Name.ToLower() == imageNameSpace.ToLower() + ".mdl")) { // lets try to load an image out of this file. string fName = ""; // The namespace we got out of the file. Bitmap resultImage; // The image that we loaded from the file. fileType ft = LoadImage(fileInfo, imageNameSpace, out fName, out resultImage); if (resultImage != null) {// if we loaded an image lets add it to our list. retunvalue.Add(resultImage); } } } return(retunvalue); }
private static MDLAnimation[] GenerateAnimations(MDLFile mdl, string destPath) { var frames = mdl.geometry.frames; if (frames.Length == 1) { return(null); // no animations } var animationsPath = destPath + "/animations"; AssetUtils.CreateFolder(animationsPath); var animations = new List <MDLAnimation>(mdl.animations.Count); foreach (var e in mdl.animations) { var name = e.Key; var anim = e.Value; var rotation = Quaternion.AngleAxis(-90, Vector3.up); var animationFrames = new MDLAnimationFrame[anim.length]; for (int frameIndex = 0; frameIndex < anim.length; ++frameIndex) { var frame = frames[anim.start + frameIndex]; var verts = frame.verts; Vector3[] vertices = new Vector3[verts.Length]; int[] triangles = new int[verts.Length]; for (int vertexIndex = 0; vertexIndex < verts.Length; vertexIndex += 3) { vertices[vertexIndex] = rotation * BSPFile.TransformVector(verts[vertexIndex]); vertices[vertexIndex + 1] = rotation * BSPFile.TransformVector(verts[vertexIndex + 1]); vertices[vertexIndex + 2] = rotation * BSPFile.TransformVector(verts[vertexIndex + 2]); triangles[vertexIndex] = vertexIndex + 2; triangles[vertexIndex + 1] = vertexIndex + 1; triangles[vertexIndex + 2] = vertexIndex; } animationFrames[frameIndex] = new MDLAnimationFrame(frame.name, vertices, triangles); } var animation = ScriptableObject.CreateInstance <MDLAnimation>(); animation.name = name; animation.frames = animationFrames; animation.type = GetAnimationType(name); if (name == "frame") { name = mdl.name; } if (name == "v_axe") { name = "shot"; // dirty little hack } var animationPath = animationsPath + "/" + name + "_animation.asset"; AssetDatabase.CreateAsset(animation, animationPath); animations.Add(AssetDatabase.LoadAssetAtPath <MDLAnimation>(animationPath)); } AssetDatabase.SaveAssets(); return(animations.ToArray()); }
static Material[] GenerateSkins(MDLFile mdl, string destPath) { List <string> textures = new List <string>(); List <Material> materials = new List <Material>(); var skinsPath = destPath + "/skins"; AssetUtils.CreateFolder(skinsPath); int skinId = 0; foreach (var skin in mdl.skins) { var textureName = mdl.skins.Length > 1 ? string.Format("{0}_skin_{1}.png", mdl.name, skinId++) : string.Format("{0}_skin.png", mdl.name); var texturePath = skinsPath + "/" + textureName; if (!AssetUtils.AssetPathExists(texturePath)) { Texture2D tex = new Texture2D(skin.width, skin.height); Color32[] pixels = new Color32[skin.width * skin.height]; for (int i = 0, j = 0; i < pixels.Length; ++i) { pixels[i] = new Color32(skin.data[j++], skin.data[j++], skin.data[j++], skin.data[j++]); } for (int x = 0; x < skin.width; ++x) { for (int y = 0; y < skin.height / 2; ++y) { int from = y * skin.width + x; int to = (skin.height - y - 1) * skin.width + x; var temp = pixels[to]; pixels[to] = pixels[from]; pixels[from] = temp; } } tex.SetPixels32(pixels); File.WriteAllBytes(AssetUtils.GetAbsoluteAssetPath(texturePath), tex.EncodeToPNG()); } textures.Add(texturePath); } AssetDatabase.Refresh(); foreach (var texture in textures) { int index = texture.LastIndexOf('.'); string materialPath = texture.Substring(0, index) + ".mat"; if (!AssetUtils.AssetPathExists(materialPath)) { TextureImporter importer = TextureImporter.GetAtPath(texture) as TextureImporter; importer.textureType = TextureImporterType.Default; importer.wrapMode = TextureWrapMode.Repeat; importer.filterMode = FilterMode.Point; importer.maxTextureSize = 2048; importer.textureFormat = TextureImporterFormat.DXT1; importer.SaveAndReimport(); var material = new Material(Shader.Find("Standard")); material.mainTexture = AssetDatabase.LoadAssetAtPath <Texture2D>(texture); material.SetFloat("_Glossiness", 0.0f); AssetDatabase.CreateAsset(material, materialPath); } materials.Add(AssetDatabase.LoadAssetAtPath <Material>(materialPath)); } AssetDatabase.SaveAssets(); return(materials.ToArray()); }
public static Transform LoadModel(String ModelPath, Boolean WithAnims = false, Boolean withHitboxes = false, Boolean GenerateUV2 = false) { //Normalize path before do magic here //(Cuz some paths uses different separators or levels... so we normalize paths always) String TempPath = NormalizePath(ModelPath, ModelsSubFolder, ModelsExtension[0], false); //If model exist in cache, return it if (ModelCache.ContainsKey(TempPath)) { return(UnityEngine.Object.Instantiate(ModelCache[TempPath])); } //Else begin try load model Transform Model; String FileName = TempPath + ModelsExtension[0]; try { #region Studio Model //Try load model MDLFile MDLFile; using (Stream mdlStream = OpenFile(FileName)) { if (mdlStream == null) { throw new FileLoadException(FileName + " NOT FOUND!"); } MDLFile = new MDLFile(mdlStream, WithAnims, withHitboxes); } #endregion //Try load vertexes #region Vertexes (Vertices data) FileName = TempPath + ModelsExtension[1]; VVDFile VVDFile; using (Stream vvdStream = OpenFile(FileName)) { if (vvdStream != null) { VVDFile = new VVDFile(vvdStream, MDLFile); } else { Debug.LogWarning(FileName + " NOT FOUND!"); MDLFile.BuildMesh = false; VVDFile = null; } } #endregion #region Meshes VTXFile VTXFile = null; if (MDLFile.BuildMesh) { if (VVDFile != null) { //Here we try find all vtx pattern, from high to low for (Int32 TryVTXID = 0; TryVTXID < 4; TryVTXID++) { FileName = TempPath + ModelsExtension[2 + TryVTXID]; using (Stream vtxStream = OpenFile(FileName)) { if (vtxStream != null) { MDLFile.BuildMesh = true; VTXFile = new VTXFile(vtxStream, MDLFile, VVDFile); break; } } } //If at least one VTX was not found, notify about that if (VTXFile == null) { Debug.LogWarning(FileName + " NOT FOUND!"); MDLFile.BuildMesh = false; } } } #endregion //Try build model Model = MDLFile.BuildModel(GenerateUV2); //Reset all MDLFile = null; VVDFile = null; VTXFile = null; //Add model to cache (to load faster than rebuild models again, again and again...) ModelCache.Add(TempPath, Model); } catch (Exception ex) { Model = new GameObject(TempPath).transform; //notify about error Debug.LogError(String.Format("{0}: {1}", TempPath, ex)); ModelCache.Add(TempPath, Model); return(Model); } return(Model); }
/// <summary> /// The device has been created. Resources that are not lost on /// Reset() can be created here -- resources in Pool.Managed, /// Pool.Scratch, or Pool.SystemMemory. Image surfaces created via /// CreateImageSurface are never lost and can be created here. Vertex /// shaders and pixel shaders can also be created here as they are not /// lost on Reset(). /// </summary> protected override void InitializeDeviceObjects() { // Initialize the drawingFont's internal textures drawingFont.InitializeDeviceObjects(device); //ExtendedMaterial[] mtrl = null; mdlfile = new MDLFile(); string path = DXUtil.FindMediaFile(initialDirectory, meshFilename); try { //systemMemoryMesh = Mesh.FromFile(path, MeshFlags.SystemMemory, device, out adjacency, out mtrl); if (!mdlfile.ReadFromFile(initialDirectory + "\\" + meshFilename)) { throw new FileLoadException("not a valide MDL file.", meshFilename); } MDLObject obj = mdlfile.RootObject; rootmdl = obj; CBLOD.Items.Clear(); if (obj.type == MDLType.mdl_lod) { CBLOD.Enabled = true; for (int i = 0; i < obj.nchildren; i++) { CBLOD.Items.Add(obj.childrens[i].lodval); } obj = obj.childrens[0]; CBLOD.SelectedIndex = 0; } else { CBLOD.Enabled = false; } // while (obj.type != MDLType.mdl_mesh) // { // if (obj.childrens[0].type == MDLType.mdl_empty) // obj = obj.childrens[1]; // else // obj = obj.childrens[0]; // // } // process textures if (mdlfile.NumTextures > 0) { meshMaterials = new Material[mdlfile.NumTextures]; meshTextures = new Texture[mdlfile.NumTextures]; for (int i = 0; i < mdlfile.NumTextures; i++) { meshMaterials[i] = new Direct3D.Material(); meshMaterials[i].Ambient = Color.White; meshMaterials[i].Diffuse = Color.White; MDLFile mdlbmp = new MDLFile(); if (mdlbmp.ReadFromFile(initialDirectory + "\\" + mdlfile.Textures[i] + ".mdl")) { if (mdlbmp.RootObject.type == MDLType.mdl_image) { MDLImage mdlimg = mdlbmp.RootObject.image; MemoryStream memstream = new MemoryStream(mdlimg.bitmap); try { //meshTextures[i] = TextureLoader.FromStream(device,memstream,mdlimg.bitmap.Length,mdlimg.w,mdlimg.h,0,0,Format.R5G6B5,Pool.Managed,Filter.Linear,Filter.Linear,0); //meshTextures[i] = TextureLoader.FromStream(device,memstream,mdlimg.w,mdlimg.h,0,0,Format.R5G6B5,Pool.SystemMemory,Filter.Linear,Filter.Linear,1); Bitmap bitmap = new Bitmap(mdlimg.w, mdlimg.h, PixelFormat.Format16bppRgb565); Rectangle rect = new Rectangle(0, 0, mdlimg.w, mdlimg.h); BitmapData bmdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format16bppRgb565); IntPtr pixels = bmdata.Scan0; unsafe { byte *pBits = (byte *)pixels.ToPointer(); for (int p = 0; p < mdlimg.bitmap.Length; p++) { pBits[p] = mdlimg.bitmap[p]; } } bitmap.UnlockBits(bmdata); //bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); meshTextures[i] = Texture.FromBitmap(device, bitmap, Usage.AutoGenerateMipMap, Pool.Managed); } catch (Exception e) { string mess = e.Message; MessageBox.Show("error loading texture '" + mdlfile.Textures[i] + ".mdl'. " + e.Message); } } } } } ArrayList objs = FlattenChildren(obj); Meshes = new Mesh[objs.Count]; MeshesEnable = new bool[objs.Count]; MeshesTex = new int[objs.Count]; objectRadius = 0; tvObj.Nodes.Clear(); for (int oi = 0; oi < objs.Count; oi++) { obj = (MDLObject)objs[oi]; TreeNode tn = new TreeNode("part " + oi.ToString()); tn.Tag = oi; tn.Checked = true; tn.Nodes.Add("# vertices = " + obj.mesh.nvertex.ToString()); tn.Nodes.Add("# faces = " + (obj.mesh.nfaces / 3).ToString()); if (obj.textidx == -1) { tn.Nodes.Add("no texture"); } else { tn.Nodes.Add("texture = " + mdlfile.Textures[obj.textidx]); } tvObj.Nodes.Add(tn); // process mesh systemMemoryMesh = new Mesh(obj.mesh.nfaces / 3, obj.mesh.nvertex, MeshFlags.SystemMemory, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture1, device); //systemMemoryMesh = Mesh.Box(device,12,15,2); VertexBuffer pVB = systemMemoryMesh.VertexBuffer; int dwNumVertices = systemMemoryMesh.NumberVertices; CustomVertex.PositionNormalTextured [] dest = (CustomVertex.PositionNormalTextured [])pVB.Lock(0, typeof(CustomVertex.PositionNormalTextured), 0, dwNumVertices); for (int i = 0; i < dest.Length; i++) { dest[i].X = obj.mesh.vertices[i].x; dest[i].Y = obj.mesh.vertices[i].y; dest[i].Z = obj.mesh.vertices[i].z; dest[i].Nx = obj.mesh.vertices[i].nx; dest[i].Ny = obj.mesh.vertices[i].ny; dest[i].Nz = obj.mesh.vertices[i].nz; dest[i].Tu = obj.mesh.vertices[i].mx; dest[i].Tv = obj.mesh.vertices[i].my; } pVB.Unlock(); int dwNumFaces = systemMemoryMesh.NumberFaces * 3; ushort[] idxs = (ushort[])systemMemoryMesh.LockIndexBuffer(typeof(ushort), 0, dwNumFaces); for (int i = 0; i < dwNumFaces; i += 3) { idxs[i] = obj.mesh.faces[i]; idxs[i + 1] = obj.mesh.faces[i + 2]; idxs[i + 2] = obj.mesh.faces[i + 1]; } systemMemoryMesh.UnlockIndexBuffer(); //systemMemoryMesh.SetIndexBufferData(obj.mesh.faces,LockFlags.None); // Lock the vertex buffer, to generate a simple bounding sphere VertexBuffer vb = null; try { vb = systemMemoryMesh.VertexBuffer; GraphicsStream vbStream = vb.Lock(0, 0, 0); objectRadius = Math.Max(objectRadius, Geometry.ComputeBoundingSphere(vbStream, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out objectCenter)); } finally { // Make sure we unlock the buffer if we fail if (vb != null) { vb.Unlock(); } } // Make sure there are normals, which are required for the tesselation // enhancement if ((systemMemoryMesh.VertexFormat & VertexFormats.Normal) != VertexFormats.Normal) { Mesh tempMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value, systemMemoryMesh.VertexFormat | VertexFormats.Normal, device); tempMesh.ComputeNormals(); systemMemoryMesh.Dispose(); systemMemoryMesh = tempMesh; } Meshes[oi] = systemMemoryMesh; MeshesEnable[oi] = true; MeshesTex[oi] = obj.textidx; } // oi loop tvObj.ExpandAll(); objectCenter = new Vector3(0, 0, 0); } // try catch { // Hide the error so we display a blue screen return; } }