예제 #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="nginz.ObjLoader"/> class.
 /// </summary>
 /// <param name="source">Source.</param>
 public ObjLoader(string source)
 {
     result = new ObjFile ();
     src = source;
     pos = -1;
     line = 1;
     linepos = 0;
     currentGroup = "default";
 }
예제 #2
0
        public Model(ObjFile objModel, int groupNum, ShaderProgram program)
        {
            var group = objModel.Groups[groupNum];
            var tempPos = new List<Vector3> ();
            var tempTex = new List<Vector2> ();
            foreach (ObjFace f in group.Faces) {
                foreach (ObjFaceVertex vert in f.Vertices) {
                    tempPos.Add (objModel.Vertices[vert.VertexIndex - 1]);
                    tempTex.Add (objModel.Textures[vert.TextureIndex - 1]);
                }
            }
            var v_pos = new GLBuffer<Vector3> (GLBufferSettings.StaticDraw3FloatArray, tempPos);
            var v_tex = new GLBuffer<Vector2> (GLBufferSettings.StaticDraw2FloatArray, tempTex);
            var m_ind = new GLBuffer<uint> (GLBufferSettings.StaticIndices, Array.ConvertAll<int, uint> (Enumerable.Range (0, tempPos.Count).ToArray (), x => (uint) x));
            Geometry = new Geometry (BeginMode.Quads)
                .AddBuffer ("v_pos", v_pos)
                .AddBuffer ("v_tex", v_tex);

            Position = Vector3.Zero;
            Scale = Vector3.One;
            Rotation = Vector3.Zero;
        }
예제 #3
0
 public KickerMeshTests()
 {
     _table = Engine.VPT.Table.Table.Load(VpxPath.Kicker);
     _obj   = LoadObjFixture(ObjPath.Kicker);
 }
예제 #4
0
 public TableMeshTests()
 {
     _table = Engine.VPT.Table.Table.Load(VpxPath.Table);
     _obj   = LoadObjFixture(ObjPath.Table);
 }
예제 #5
0
 public PrimitiveMeshTests()
 {
     _tc  = FileTableContainer.Load(VpxPath.Primitive);
     _obj = LoadObjFixture(ObjPath.Primitive);
 }
 public PrimitiveMeshTests(ITestOutputHelper output) : base(output)
 {
     _table = Engine.VPT.Table.Table.Load(VpxPath.Primitive);
     _obj   = LoadObjFixture(ObjPath.Primitive);
 }
        public static void ConvertObjFileToDMesh(ObjFile obj_file, DMesh dm, bool units_inches, string obj_file_name, Editor editor, TextureManager tex_manager)
        {
            dm.Init(editor);

            // Convert the verts
            foreach (var v in obj_file.Vertices)
            {
                // Flip Z for coordinate system translation
                                #if DMESH_EDITOR
                dm.AddVertexEditor(new Vector3(v.X, v.Y, -v.Z), false);
                                #else
                dm.AddVertex(v.X, v.Y, -v.Z);
                                #endif
            }

            if (units_inches)
            {
                for (int i = 0; i < dm.vertex.Count; i++)
                {
                    dm.vertex[i] *= 0.0254f;
                }
            }

            // Convert the textures
            for (var i = 0; i < obj_file.Materials.Count; i++)
            {
                var    material    = obj_file.Materials[i];
                string tex_name    = material.Diffuse.Texture;
                string tex_id_name = tex_name != null?Path.GetFileNameWithoutExtension(tex_name) : material.Name;

                string decal_tex_name = Path.Combine(editor.m_filepath_decal_textures, tex_id_name + ".png");

                if (tex_name != null)
                {
                    if (!CopyImportTextureToDecalFolder(obj_file_name, tex_name, editor.m_filepath_decal_textures))
                    {
                        Utility.DebugLog("No texture imported/updated: " + tex_name);
                    }
                    else
                    {
                        Utility.DebugLog("Imported/updated a texture: " + tex_name);
                    }
                }
                else if (!File.Exists(decal_tex_name))
                {
                    using (var bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb)) {
                        bmp.SetPixel(0, 0, material.Diffuse.Color);
                        bmp.Save(decal_tex_name, ImageFormat.Png);
                    }
                }

                if (tex_manager.FindTextureIDByName(tex_id_name) < 0)
                {
                    // Get the texture (if it exists)
                    if (File.Exists(decal_tex_name))
                    {
                        tex_manager.AddTexture(decal_tex_name);
                    }
                    else
                    {
                        // Try to steal it from the level directory instead
                        string level_tex_name = Path.Combine(editor.m_filepath_level_textures, tex_id_name + ".png");
                        if (File.Exists(level_tex_name))
                        {
                            // Copy it to the decal textures directory, then load it
                            if (!File.Exists(decal_tex_name))
                            {
                                File.Copy(level_tex_name, decal_tex_name);

                                tex_manager.AddTexture(decal_tex_name);
                            }
                        }
                        else
                        {
                            editor.AddOutputText("IMPORT WARNING: No PNG file could be found matching the name: " + tex_id_name);
                        }
                    }
                }

                dm.AddTexture(i, tex_id_name);
            }

            // Convert the faces
            var vrt_idx = new int[3];
            var uv      = new Vector2[3];
            var nrml    = new Vector3[3];
            var tris    = new List <ObjFile.FaceVert[]>();
            foreach (var f in obj_file.Faces)
            {
                // Triangulate face
                tris.Clear();
                var fv = f.FaceVerts;
                if (fv.Length == 3)
                {
                    tris.Add(fv);
                }
                else if (fv.Length == 4 &&
                         Vector3.Subtract(obj_file.Vertices[fv[0].VertIdx], obj_file.Vertices[fv[2].VertIdx]).LengthSquared >
                         Vector3.Subtract(obj_file.Vertices[fv[1].VertIdx], obj_file.Vertices[fv[3].VertIdx]).LengthSquared)
                {
                    tris.Add(new [] { fv[0], fv[1], fv[3] });
                    tris.Add(new [] { fv[1], fv[2], fv[3] });
                }
                else                     // assume convex...
                {
                    for (int i = 1; i < fv.Length - 1; i++)
                    {
                        tris.Add(new [] { fv[0], fv[i], fv[i + 1] });
                    }
                }

                foreach (var tri in tris)
                {
                    for (var i = 0; i < 3; i++)
                    {
                        // Flip Z/V and reverse vertex order for coordinate system translation
                        int fi = 2 - i;
                        vrt_idx[i] = tri[fi].VertIdx;
                        nrml[i]    = obj_file.Normals[tri[fi].NormIdx];
                        nrml[i].Z  = -nrml[i].Z;
                        uv[i]      = tri[fi].UVIdx >= 0 ? obj_file.UVs[tri[fi].UVIdx] : new Vector2();
                        uv[i].Y    = 1.0f - uv[i].Y;
                    }
                    dm.AddFace(vrt_idx, nrml, uv, f.MatIdx);
                }
            }
        }
 public RampMeshTests(ITestOutputHelper output) : base(output)
 {
     _table = Engine.VPT.Table.Table.Load(VpxPath.Ramp);
     _obj   = LoadObjFixture(ObjPath.Ramp);
 }
        public async Task <IActionResult> UploadPointCloudGeneric(PointCloud pointCloud)
        {
            if (ModelState.IsValid)
            {
                var CurrentDate       = DateTime.Now;
                var UploadDate        = CurrentDate.ToString("yyyyMMdd_hhmmss");
                var userfileName      = User.Identity.Name.ToString();
                var RootFolder        = _hostingEnvironment.WebRootPath;
                var UsersFileLocation = "UsersDirectory";
                //  var RootFfolderString = "wwwroot";
                var ObjFileExtension = ".obj";
                var UserDirectory    = $"{_hostingEnvironment.WebRootPath}/{UsersFileLocation}/{userfileName}/{UploadDate}";
                //var UserFilesDirectoryRelative = $"{RootFfolderString}/{UsersFileLocation}/{userfileName}/{UploadDate}";
                var UserFilesDirectoryRelative = $"{UsersFileLocation}/{userfileName}/{UploadDate}";
                //var ImageFileLocationPaths = new List<String>();
                //Check if user Directory exsists , if not creates new directory
                var exsits = Directory.Exists(UserDirectory);
                if (!exsits)
                {
                    Directory.CreateDirectory(UserDirectory);
                }
                var filePathName  = ContentDispositionHeaderValue.Parse(pointCloud.PointCloudFile.ContentDisposition).FileName.Trim('"');
                var fileExtention = Path.GetExtension(filePathName);
                if (!(fileExtention == ".xyz" || fileExtention == ".XYZ"))
                {
                    return(RedirectToAction("ErrorPage"));
                }
                var uploads      = Path.Combine(RootFolder, UsersFileLocation, userfileName, UploadDate);
                var fileName     = Guid.NewGuid().ToString("N").Substring(0, 10);
                var FileNameFull = fileName + fileExtention;
                var FileNameObj  = fileName + ObjFileExtension;
                var StaticPath   = Path.Combine(uploads, FileNameFull);
                var StaticPathNameNoExtension = Path.Combine(uploads, fileName);
                var RelativePaths             = $"{UserFilesDirectoryRelative}/{fileName}" + $"{ObjFileExtension}";
                //the image will be saved with a unique filename
                FileStream DestinationStream = new FileStream(StaticPath, FileMode.CreateNew);
                //ImageFileLocationPaths.Add(PathObjRelative);
                //the image will be saved with a unique filename
                // ImageFile.CopyToAsync(DestinationStream);
                pointCloud.PointCloudFile.CopyTo(DestinationStream);
                var ExcuationStatus = ModelBuilder(StaticPathNameNoExtension);
                var currentUser     = await _userManager.FindByNameAsync(User.Identity.Name);

                if (ExcuationStatus == 0)
                {
                    var ObjectFile = new ObjFile
                    {
                        FileName            = FileNameObj,
                        StaticFilePath      = StaticPathNameNoExtension + ObjFileExtension,
                        RelativeFilePath    = RelativePaths,
                        FK_ApplicatioUserId = currentUser.Id,
                        UploadedTime        = CurrentDate
                    };
                    repo.Add(ObjectFile);
                }
                else
                {
                    return(RedirectToAction("ErrorPage"));
                }
                return(RedirectToAction("UploadCompelete"));
            }
            else
            {
                return(View("Error"));
            }
        }
예제 #10
0
    // Use this for initialization
    void Start()
    {
        ObjFile file = new ObjFile();

        file.ReadObjFile(Application.dataPath + @"/NPP3.obj");
    }
 public HitTargetMeshTests()
 {
     _table = Engine.VPT.Table.Table.Load(VpxPath.HitTarget);
     _obj   = LoadObjFixture(ObjPath.HitTarget);
 }
예제 #12
0
 public TriggerMeshTests()
 {
     _tc  = FileTableContainer.Load(VpxPath.Trigger);
     _obj = LoadObjFixture(ObjPath.Trigger);
 }
예제 #13
0
 public RubberMeshTest()
 {
     _tc  = FileTableContainer.Load(VpxPath.Rubber);
     _obj = LoadObjFixture(ObjPath.Rubber);
 }
예제 #14
0
        static void Main(string[] args)
        {
            if (args.Length == 0 || args[0] == "-h")
            {
                printHelp();
                return;
            }
            List <string> fileList = new List <string>();
            FileInfo      dest     = null;
            string        format   = "";

            var settings = Settings.None;


            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];
                if (arg.StartsWith("-") || arg.Length == 1)
                {
                    var option = arg.Last();
                    // Handle as argument
                    switch (option)
                    {
                    case 'o':
                        if (i + 1 >= args.Length)
                        {
                            Console.Error.WriteLine("No value for {0}", arg);
                            printHelp();
                            return;
                        }

                        string path = args[++i];
                        int    idx  = path.LastIndexOf('.');
                        if (idx >= 0)
                        {
                            if (format == "")
                            {
                                format = path.Substring(idx + 1);
                            }
                            path = path.Substring(0, idx);
                        }
                        dest = new FileInfo(path);

                        break;

                    case 'h':
                        printHelp();
                        return;

                    case 'u':
                        settings |= Settings.Compatibility;
                        break;

                    case 'b':
                        settings |= Settings.Skin;
                        break;

                    case 's':
                        settings |= Settings.SliceAnimations;
                        break;

                    case 'm':
                        settings |= Settings.Morphs;
                        break;

                    case 'a':
                        settings |= Settings.Animations | Settings.Skin;
                        break;

                    case 'c':
                        settings |= Settings.Merge;
                        break;

                    case 'f':
                        if (i + 1 >= args.Length)
                        {
                            Console.Error.WriteLine("No value for {0}", arg);
                            printHelp();
                            return;
                        }
                        format = args[++i];
                        if (format != "dae" && format != "obj")
                        {
                            Console.Error.WriteLine("Invalid format: {0}", format);
                            printHelp();
                            return;
                        }

                        break;

                    default:
                        Console.Error.WriteLine("Unknown option {0}", arg);
                        printHelp();
                        return;
                    }
                }
                else
                {
                    // Handle as input file
                    var info = new FileInfo(arg);
                    if (info.Exists)
                    {
                        if (arg.EndsWith(".anz"))
                        {
                            fileList.Add(info.FullName);

                            if (dest == null)
                            {
                                dest = new FileInfo(info.FullName.Replace(".anz", ""));
                            }
                        }
                        else
                        {
                            Console.Error.WriteLine("File {0} is not an *.anz file.", arg);
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("Could not find file {0}", arg);
                    }
                }
            }
            if (settings == Settings.None)
            {
                settings = Settings.All;
            }

            //   settings = Settings.Animations | Settings.SliceAnimations | Settings.Compress;

            if (format == "")
            {
                format = "dae";
            }

            dest = new FileInfo(dest.FullName + "." + format);

            IConvertTarget target;

            if (format == "dae")
            {
                target = new ColladaFile();
            }
            else
            {
                target = new ObjFile();
            }

            target.Options = settings;

            int processed = 0;

            foreach (var file in fileList)
            {
                var anz = ANZFile.FromFile(file);
                if (!anz.HasAnimation || anz.Anims.Any(a => a.Objects == null || a.Objects.All(o => o.Name == null)))
                {
                    Console.WriteLine("{0}: mesh", file);

                    target.AddMesh(anz);
                    processed++;
                }
                else if (target is IMotionSupport)
                {
                    Console.WriteLine("{0}: anim", file);


                    ((IMotionSupport)target).AddMotion(anz);
                    processed++;
                }
                else
                {
                    Console.Error.WriteLine("{0} does not support animations. Skipping: {1}", format, file);
                }
            }

            if (processed > 0)
            {
                target.Save(dest.FullName);
            }
            else
            {
                Console.Error.WriteLine("Got nothing to do...");
            }
        }
예제 #15
0
 public RubberMeshTest()
 {
     _table = Engine.VPT.Table.Table.Load(VpxPath.Rubber);
     _obj   = LoadObjFixture(ObjPath.Rubber);
 }
예제 #16
0
        public Model Load(ObjFile obj_file)
        {
            var nv       = 0;
            var ni       = 0;
            var n        = obj_file.f.Count;
            var m        = obj_file.f[0].v.Length;
            var vertices = new VertexP3N3T2[n * m];
            var indices  = new List <uint>();

            for (var i = 0; i < n; i++)
            {
                var fi = obj_file.f[i];
                Debug.Assert(fi.v.Length == fi.vn.Length);
                Debug.Assert(fi.vn.Length == fi.vt.Length);
                for (var j = 0; j < fi.v.Length; j++)
                {
                    var vj = fi.v[j] - 1;
                    if (vj < 0)
                    {
                        vj += obj_file.v.Count + 1;
                    }
                    var vnj = fi.vn[j] - 1;
                    if (vnj < 0)
                    {
                        vnj += obj_file.vn.Count + 1;
                    }
                    var vtj = fi.vt[j] - 1;
                    if (vtj < 0)
                    {
                        vtj += obj_file.vt.Count + 1;
                    }
                    vertices[nv] = new VertexP3N3T2(obj_file.v[vj][0], obj_file.v[vj][1], obj_file.v[vj][2], obj_file.vn[vnj][0], obj_file.vn[vnj][1], obj_file.vn[vnj][2], obj_file.vt[vtj][0], 1 - obj_file.vt[vtj][1]);
                    nv++;
                }
                switch (fi.v.Length)
                {
                case 3:
                    indices.Add((uint)(ni + 0));
                    indices.Add((uint)(ni + 1));
                    indices.Add((uint)(ni + 2));
                    ni += fi.v.Length;
                    break;

                case 4:
                    indices.Add((uint)(ni + 0));
                    indices.Add((uint)(ni + 1));
                    indices.Add((uint)(ni + 2));
                    indices.Add((uint)(ni + 2));
                    indices.Add((uint)(ni + 3));
                    indices.Add((uint)(ni + 0));
                    ni += fi.v.Length;
                    break;

                default:
                    throw new NotImplementedException();
                }
            }

            var model = new Model();

            model.Mesh(new Mesh <VertexP3N3T2, uint>(vertices, indices.ToArray()));
            model.Mode = PrimitiveType.Triangles;
            return(model);
        }
예제 #17
0
        public ObjFile Import(string modelPath)
        {
            try
            {
                buffer = File.ReadAllBytes(modelPath);
            }
            catch
            {
                Console.WriteLine("Could not find model: " + modelPath);
                return(null);
            }

            int[][] sections = ParseFile();
            Dictionary <int, object[]> parsedSections = new Dictionary <int, object[]>();

            foreach (int[] section in sections)
            {
                switch (section[1])
                {
                case AnimationDataTag:
                    //Debug.Log("animation data");
                    parsedSections[section[2]] = ParseAnimationData(section[0] + 12, section[3], section[2]);
                    break;

                case AuthorTag:
                    //Debug.Log("author tag");
                    parsedSections[section[2]] = ParseAuthor(section[0] + 12, section[3], section[2]);
                    break;

                case MaterialGroupTag:
                    //Debug.Log("material group tag");
                    parsedSections[section[2]] = ParseMaterialGroup(section[0] + 12, section[3], section[2]);
                    break;

                case MaterialTag:
                    //Debug.Log("material tag");
                    parsedSections[section[2]] = ParseMaterial(section[0] + 12, section[3], section[2]);
                    break;

                case Object3DTag:
                    //Debug.Log("object3d tag");
                    parsedSections[section[2]] = ParseObject3D(section[0] + 12, section[3], section[2]);
                    break;

                case ModelDataTag:
                    //Debug.Log("model data tag");
                    parsedSections[section[2]] = ParseModelData(section[0] + 12, section[3], section[2]);
                    break;

                case GeometryTag:
                    //Debug.Log("geometry tag");
                    parsedSections[section[2]] = ParseGeometry(section[0] + 12, section[3], section[2]);
                    break;

                case TopologyTag:
                    //Debug.Log("topology tag");
                    parsedSections[section[2]] = ParseTopology(section[0] + 12, section[3], section[2]);
                    break;

                case TopologyIpTag:
                    //Debug.Log("topologyIP tag");
                    parsedSections[section[2]] = ParseTopologyIp(section[0] + 12, section[3], section[2]);
                    break;
                }

                if ((uint)section[1] == PassthroughTag)
                {
                    parsedSections[section[2]] = ParsePassthroughGp(section[0] + 12, section[3], section[2]);
                }
            }

            ObjFile obj = new ObjFile();

            foreach (int[] section in sections)
            {
                if (section[1] == ModelDataTag)
                {
                    object[] modelData = parsedSections[section[2]];
                    if ((int)modelData[3] == 6)
                    {
                        continue;
                    }
                    string         modelId  = "model-" + ((object[])modelData[2])[1];
                    object[]       geometry = parsedSections[(int)parsedSections[(int)modelData[4]][2]];
                    object[]       topology = parsedSections[(int)parsedSections[(int)modelData[4]][3]];
                    List <short[]> faces    = (List <short[]>)topology[4];
                    List <float[]> vertices = (List <float[]>)geometry[6];
                    List <float[]> uvs      = (List <float[]>)geometry[7];
                    List <float[]> normals  = (List <float[]>)geometry[8];
                    float[]        position = (float[])((object[])modelData[2])[5];

                    foreach (short[] face in faces)
                    {
                        ObjFace objFace = new ObjFace();
                        objFace.Vertices.Add(new ObjTriplet(face[0] + 1, face[0] + 1, face[0] + 1));
                        objFace.Vertices.Add(new ObjTriplet(face[1] + 1, face[1] + 1, face[1] + 1));
                        objFace.Vertices.Add(new ObjTriplet(face[2] + 1, face[2] + 1, face[2] + 1));
                        obj.Faces.Add(objFace);
                    }

                    foreach (float[] vertex in vertices)
                    {
                        obj.Vertices.Add(new ObjVertex(vertex[0] + position[0], vertex[1] + position[1],
                                                       vertex[2] + position[2]));
                    }

                    foreach (float[] uv in uvs)
                    {
                        obj.TextureVertices.Add(new ObjVector3(uv[0], -uv[1], 0));
                    }

                    foreach (float[] normal in normals)
                    {
                        obj.VertexNormals.Add(new ObjVector3(normal[0], normal[1], normal[2]));
                    }
                }
            }

            return(obj);
        }