Ejemplo n.º 1
0
        fPolylineGameObject make_path <T>(LinearToolpath3 <T> path, fMaterial material, float width, Vector3d origin) where T : IToolpathVertex
        {
            Vector3d prev = Vector3d.Zero;

            tempPolyLine.Clear();
            foreach (T vtx in path)
            {
                Vector3d v = origin + vtx.Position;
                v = MeshTransforms.ConvertZUpToYUp(v);
                v = MeshTransforms.FlipLeftRightCoordSystems(v);

                // [RMS] because of the sharp turns we make, unity polyline will get twisted up unless we put
                // in some duplicate vertices =\
                if (tempPolyLine.Count > 0)
                {
                    tempPolyLine.Add((Vector3f)Vector3d.Lerp(prev, v, 0.001));
                    tempPolyLine.Add((Vector3f)Vector3d.Lerp(prev, v, 0.998));
                    tempPolyLine.Add((Vector3f)Vector3d.Lerp(prev, v, 0.999));
                }
                tempPolyLine.Add((Vector3f)v);
                prev = v;
            }

            fPolylineGameObject go = PolylinePool.Allocate();

            go.SetMaterial(material, true);
            go.SetLineWidth(width);
            go.SetVertices(tempPolyLine.ToArray(), false, true);
            return(go);
        }
Ejemplo n.º 2
0
        public static void ExportSocket()
        {
            if (OG.Model.HasSocket() == false)
            {
                return;
            }

            string filename = null;

            if (ShowExportDialogInEditor || FPlatform.InUnityEditor() == false)
            {
                filename = FPlatform.GetSaveFileName("Export Socket",
                                                     Path.Combine(ExportSocketPath, "socket.obj"), new string[] { "*.obj" }, "Mesh Files (*.OBJ)");
            }
            else
            {
                filename = Path.Combine(ExportSocketPath, "socket.obj");
            }
            if (filename == null)
            {
                return;
            }

            DMesh3           SocketMesh = new DMesh3(OG.Socket.Socket.Mesh);
            AxisAlignedBox3d bounds     = SocketMesh.CachedBounds;

            MeshTransforms.Translate(SocketMesh, -bounds.Min.y * Vector3d.AxisZ);
            MeshTransforms.FlipLeftRightCoordSystems(SocketMesh);   // convert from unity coordinate system

            WriteOptions opt = WriteOptions.Defaults;

            opt.bWriteGroups = true;
            StandardMeshWriter.WriteMesh(filename, SocketMesh, opt);
        }
Ejemplo n.º 3
0
    // Use this for initialization
    void Start()
    {
        meshGO = GameObject.Find("sample_mesh");
        Mesh unityMesh = meshGO.GetComponent <MeshFilter>().mesh;

        startMesh = g3UnityUtils.UnityMeshToDMesh(unityMesh);
        double height = startMesh.CachedBounds.Height;

        // find path to sample file
        if (LoadSampleMesh)
        {
            string curPath  = Application.dataPath;
            string filePath = Path.Combine(curPath, Path.Combine("..\\sample_files", SampleFileName));

            // load sample file, convert to unity coordinate system, translate and scale to origin
            startMesh = StandardMeshReader.ReadMesh(filePath);
            if (startMesh == null)
            {
                startMesh = new Sphere3Generator_NormalizedCube().Generate().MakeDMesh();
            }

            if (FlipLeftRight)
            {
                MeshTransforms.FlipLeftRightCoordSystems(startMesh);
            }
            MeshTransforms.Scale(startMesh, height / startMesh.CachedBounds.Height);
            MeshTransforms.Translate(startMesh, -startMesh.CachedBounds.Center);
            MeshNormals.QuickCompute(startMesh);
            g3UnityUtils.SetGOMesh(meshGO, startMesh);
        }
    }
Ejemplo n.º 4
0
        // parse file and create a set of MeshSO objects
        public bool ReadFile(string sPath)
        {
            sSourcePath = sPath;
            SomeMeshesTooLargeForUnityWarning = false;

            // read the input file

            DMesh3Builder build = new DMesh3Builder();

            StandardMeshReader reader = new StandardMeshReader()
            {
                MeshBuilder = build
            };

            reader.warningEvent += on_warning;

            ReadOptions options = new ReadOptions();

            options.ReadMaterials = true;
            LastReadResult        = reader.Read(sPath, options);
            if (LastReadResult.code != IOCode.Ok)
            {
                return(false);
            }

            // create the material set

            List <SOMaterial> vSOMaterials = new List <SOMaterial>();

            for (int k = 0; k < build.Materials.Count; ++k)
            {
                SOMaterial m = build_material(sPath, build.Materials[k]);
                vSOMaterials.Add(m);
            }

            // convert the read meshes into unity meshes

            SceneObjects = new List <ImportedObject>();
            for (int k = 0; k < build.Meshes.Count; ++k)
            {
                DMesh3 mesh = build.Meshes[k];

                int        matID      = build.MaterialAssignment[k];
                SOMaterial soMaterial =
                    (matID < 0 || matID >= vSOMaterials.Count) ? null : vSOMaterials[matID];

                if (SwapLeftRight)
                {
                    MeshTransforms.FlipLeftRightCoordSystems(mesh);
                }

                SceneObjects.Add(new ImportedObject()
                {
                    mesh = mesh, material = soMaterial
                });
            }

            return(SceneObjects.Count > 0);
        }
Ejemplo n.º 5
0
        void compute_slice_polylines()
        {
            // fMaterial mat1 = MaterialUtil.CreateFlatMaterialF(Colorf.Black);
            // fMaterial mat2 = MaterialUtil.CreateFlatMaterialF(Colorf.BlueMetal);

            // [TODO] do we need to hold data_lock here? seems like no since main thread is blocked,
            //  then it would never be the case that we are setting SliceSet = null

            // create geometry
            int slice_i = 0;

            //SlicePolylines = new List<fPolylineGameObject>();

            foreach (PlanarSlice slice in SliceSet.Slices)
            {
                //DebugUtil.Log(2, "Slice has {0} solids", slice.Solids.Count);
                Colorf slice_color = (slice_i % 2 == 0) ? Colorf.Black : Colorf.BlueMetal;
                // fMaterial slice_mat = (slice_i % 2 == 0) ? mat1 : mat2;
                slice_i++;
                foreach (GeneralPolygon2d poly in slice.Solids)
                {
                    List <Vector3f> polyLine = new List <Vector3f>();
                    for (int pi = 0; pi <= poly.Outer.VertexCount; ++pi)
                    {
                        int      i  = pi % poly.Outer.VertexCount;
                        Vector2d v2 = poly.Outer[i];
                        Vector2d n2 = poly.Outer.GetTangent(i).Perp;

                        Vector3d v3 = new Vector3d(v2.x, v2.y, slice.Z);
                        v3 = MeshTransforms.ConvertZUpToYUp(v3);
                        v3 = MeshTransforms.FlipLeftRightCoordSystems(v3);
                        Vector3d n3 = MeshTransforms.ConvertZUpToYUp(new Vector3d(n2.x, n2.y, 0));
                        n3 = MeshTransforms.FlipLeftRightCoordSystems(n3);
                        n3.Normalize();
                        v3 += 0.1f * n3;

                        polyLine.Add((Vector3f)v3);
                    }

                    // Do something with polyline....
                    Console.WriteLine(polyLine);

                    ////DebugUtil.Log(2, "Polyline has {0} vertiecs", polyLine.Count);
                    //fPolylineGameObject go = GameObjectFactory.CreatePolylineGO(
                    //    "slice_outer", polyLine, slice_color, 0.1f, LineWidthType.World);
                    //go.SetMaterial(slice_mat, true);
                    //CC.ActiveScene.RootGameObject.AddChild(go, false);
                    //SlicePolylines.Add(go);
                }
            }
        }
Ejemplo n.º 6
0
    // Use this for initialization
    void Start()
    {
        // find path to sample file
        string curPath  = Application.dataPath;
        string filePath = Path.Combine(curPath, Path.Combine("..\\sample_files", "bunny_solid.obj"));

        // load sample file, convert to unity coordinate system, translate and scale to origin
        startMesh = StandardMeshReader.ReadMesh(filePath);
        if (startMesh == null)
        {
            startMesh = new Sphere3Generator_NormalizedCube().Generate().MakeDMesh();
        }
        MeshTransforms.FlipLeftRightCoordSystems(startMesh);
        MeshTransforms.Translate(startMesh, -startMesh.CachedBounds.Center);
        MeshTransforms.Scale(startMesh, 8.0 / startMesh.CachedBounds.MaxDim);

        // load wireframe shader
        Material wireframeShader = g3UnityUtils.SafeLoadMaterial("wireframe_shader/Wireframe");

        // create initial mesh
        meshGO = g3UnityUtils.CreateMeshGO("start_mesh", startMesh, wireframeShader);
    }
Ejemplo n.º 7
0
        virtual protected DMesh3 make_bunny()
        {
            if (cached_bunny == null)
            {
                // [RMS] yiiiiiikes
                MemoryStream stream = FResources.LoadBinary("meshes/unit_height_bunny");
                if (stream != null)
                {
                    cached_bunny = StandardMeshReader.ReadMesh(stream, "obj");
                    MeshTransforms.ConvertZUpToYUp(cached_bunny);
                    MeshTransforms.FlipLeftRightCoordSystems(cached_bunny);
                }
                else
                {
                    cached_bunny = make_shape_sphere();
                    MeshTransforms.Scale(cached_bunny, 1 / ShapeHeight);
                }
            }
            DMesh3 mesh = new DMesh3(cached_bunny);

            MeshTransforms.Scale(mesh, ShapeHeight);
            return(mesh);
        }
Ejemplo n.º 8
0
        public IOWriteResult RunBackgroundWrite()
        {
            // transform meshes
            gParallel.ForEach(Interval1i.Range(ExportMeshes.Length), (i) => {
                if (MeshFrames[i].Origin != Vector3f.Zero || MeshFrames[i].Rotation != Quaternionf.Identity)
                {
                    MeshTransforms.FromFrame(ExportMeshes[i], MeshFrames[i]);
                }

                MeshTransforms.FlipLeftRightCoordSystems(ExportMeshes[i]);

                if (ExportYUp == false)
                {
                    MeshTransforms.ConvertYUpToZUp(ExportMeshes[i]);
                }
            });


            List <WriteMesh> writeMeshes = new List <WriteMesh>();

            for (int i = 0; i < ExportMeshes.Length; ++i)
            {
                writeMeshes.Add(new WriteMesh(ExportMeshes[i]));
            }


            WriteOptions options = WriteOptions.Defaults;

            options.bWriteBinary = true;
            options.ProgressFunc = BackgroundProgressFunc;

            StandardMeshWriter writer = new StandardMeshWriter();
            IOWriteResult      result = writer.Write(WritePath, writeMeshes, options);

            return(result);
        }
Ejemplo n.º 9
0
            public void Compute()
            {
                int N = meshToScene.Length;

                slicer = new MeshPlanarSlicerPro()
                {
                    LayerHeightMM = CC.Settings.LayerHeightMM,
                    // [RMS] 1.5 here is a hack. If we don't leave a bit of space then often the filament gets squeezed right at
                    //   inside/outside transitions, which is bad. Need a better way to handle.
                    OpenPathDefaultWidthMM = CC.Settings.NozzleDiameterMM * 1.5,
                    SetMinZValue           = 0,
                    SliceFactoryF          = PlanarSlicePro.FactoryF
                };
                if (CC.Settings.OpenMode == PrintSettings.OpenMeshMode.Clipped)
                {
                    slicer.DefaultOpenPathMode = PrintMeshOptions.OpenPathsModes.Clipped;
                }
                else if (CC.Settings.OpenMode == PrintSettings.OpenMeshMode.Embedded)
                {
                    slicer.DefaultOpenPathMode = PrintMeshOptions.OpenPathsModes.Embedded;
                }
                else if (CC.Settings.OpenMode == PrintSettings.OpenMeshMode.Ignored)
                {
                    slicer.DefaultOpenPathMode = PrintMeshOptions.OpenPathsModes.Ignored;
                }

                if (CC.Settings.StartLayers > 0)
                {
                    int    start_layers       = CC.Settings.StartLayers;
                    double std_layer_height   = CC.Settings.LayerHeightMM;
                    double start_layer_height = CC.Settings.StartLayerHeightMM;
                    slicer.LayerHeightF = (layer_i) => {
                        return((layer_i < start_layers) ? start_layer_height : std_layer_height);
                    };
                }

                try {
                    assembly = new PrintMeshAssembly();
                    for (int k = 0; k < N; ++k)
                    {
                        DMesh3            mesh     = meshCopies[k];
                        Frame3f           mapF     = meshToScene[k];
                        PrintMeshSettings settings = meshSettings[k];

                        PrintMeshOptions options = new PrintMeshOptions();
                        options.IsSupport    = (settings.ObjectType == PrintMeshSettings.ObjectTypes.Support);
                        options.IsCavity     = (settings.ObjectType == PrintMeshSettings.ObjectTypes.Cavity);
                        options.IsCropRegion = (settings.ObjectType == PrintMeshSettings.ObjectTypes.CropRegion);
                        options.IsOpen       = false;
                        if (settings.OuterShellOnly)
                        {
                            options.IsOpen = true;
                        }
                        options.OpenPathMode = PrintMeshSettings.Convert(settings.OpenMeshMode);
                        options.Extended     = new ExtendedPrintMeshOptions()
                        {
                            ClearanceXY = settings.Clearance,
                            OffsetXY    = settings.OffsetXY
                        };

                        Vector3f scale = localScale[k];
                        MeshTransforms.Scale(mesh, scale.x, scale.y, scale.z);
                        MeshTransforms.FromFrame(mesh, mapF);
                        MeshTransforms.FlipLeftRightCoordSystems(mesh);
                        MeshTransforms.ConvertYUpToZUp(mesh);

                        MeshAssembly decomposer = new MeshAssembly(mesh);
                        decomposer.HasNoVoids = settings.NoVoids;
                        decomposer.Decompose();

                        assembly.AddMeshes(decomposer.ClosedSolids, options);

                        PrintMeshOptions openOptions = options.Clone();
                        assembly.AddMeshes(decomposer.OpenMeshes, openOptions);
                    }

                    if (slicer.Add(assembly) == false)
                    {
                        throw new Exception("error adding PrintMeshAssembly to Slicer!!");
                    }

                    // set clip box
                    Box2d clip_box = new Box2d(Vector2d.Zero,
                                               new Vector2d(CC.Settings.BedSizeXMM / 2, CC.Settings.BedSizeYMM / 2));
                    slicer.ValidRegions = new List <GeneralPolygon2d>()
                    {
                        new GeneralPolygon2d(new Polygon2d(clip_box.ComputeVertices()))
                    };

                    result  = slicer.Compute();
                    Success = true;
                } catch (Exception e) {
                    DebugUtil.Log("GeometrySlicer.Compute: exception: " + e.Message);
                    Success = false;
                }

                Finished = true;
            }
Ejemplo n.º 10
0
        public void ComputeOnBackgroundThread()
        {
            Deviation = null;

            DebugUtil.Log(SO.GetToolpathStats());

            ToolpathSet      paths  = SO.GetToolpaths();
            PlanarSliceStack slices = SO.GetSlices();
            var settings            = SO.GetSettings();

            // AAHHH
            double   bed_width  = settings.Machine.BedSizeXMM;
            double   bed_height = settings.Machine.BedSizeYMM;
            Vector3d origin     = new Vector3d(-bed_width / 2, -bed_height / 2, 0);

            if (settings is gs.info.MakerbotSettings)
            {
                origin = Vector3d.Zero;
            }

            List <DeviationPt>   points       = new List <DeviationPt>();
            SpinLock             pointsLock   = new SpinLock();
            Action <DeviationPt> appendPointF = (pt) => {
                bool entered = false;
                pointsLock.Enter(ref entered);
                points.Add(pt);
                pointsLock.Exit();
            };

            double tolerance = settings.Machine.NozzleDiamMM * 0.5 + DeviationToleranceMM;

            gParallel.ForEach(Interval1i.Range(slices.Count), (slicei) => {
                PlanarSlice slice = slices[slicei];

                //Interval1d zrange = (slicei < slices.Count - 1) ?
                //    new Interval1d(slice.Z, slices[slicei + 1].Z - 0.5*settings.LayerHeightMM) :
                //    new Interval1d(slice.Z, slice.Z + 0.5*settings.LayerHeightMM);
                double dz         = 0.5 * settings.LayerHeightMM;
                Interval1d zrange = new Interval1d(slice.Z - dz, slice.Z + dz);

                double cellSize = 2.0f;

                ToolpathsLayerGrid grid = new ToolpathsLayerGrid();
                grid.Build(paths, zrange, cellSize);

                foreach (GeneralPolygon2d poly in slice.Solids)
                {
                    measure_poly(poly.Outer, slice.Z, grid, tolerance, appendPointF);
                    foreach (var hole in poly.Holes)
                    {
                        measure_poly(poly.Outer, slice.Z, grid, tolerance, appendPointF);
                    }
                }
            });

            int N = points.Count;

            for (int k = 0; k < N; ++k)
            {
                DeviationPt pt = points[k];
                Vector3d    v  = origin + pt.pos;
                v         = MeshTransforms.ConvertZUpToYUp(v);
                pt.pos    = MeshTransforms.FlipLeftRightCoordSystems(v);
                points[k] = pt;
            }

            Deviation = new DeviationData();
            Deviation.DeviationPoints = points;
            OnGeometryUpdateRequired?.Invoke(this);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// If go has a MeshFilter, extract it and append to SimpleMesh.
        /// Returns false if no filter.
        /// </summary>
        bool AppendGOMesh(GameObject go, SimpleMesh m, int[] vertexMap, FScene scene, int gid)
        {
            MeshFilter filter = go.GetComponent <MeshFilter>();

            if (filter == null || filter.mesh == null)
            {
                return(false);
            }

            Mesh curMesh = filter.sharedMesh;

            Vector3[] vertices = curMesh.vertices;
            Vector3[] normals  = (WriteNormals) ? curMesh.normals : null;
            Color[]   colors   = (WriteVertexColors) ? curMesh.colors : null;
            Vector2[] uvs      = (WriteUVs) ? curMesh.uv : null;

            if (vertexMap.Length < curMesh.vertexCount)
            {
                vertexMap = new int[curMesh.vertexCount * 2];
            }

            for (int i = 0; i < curMesh.vertexCount; ++i)
            {
                NewVertexInfo vi = new NewVertexInfo();
                vi.bHaveN = WriteNormals; vi.bHaveC = WriteVertexColors; vi.bHaveUV = WriteUVs;

                Vector3f v = vertices[i];
                // local to world
                v = filter.gameObject.transform.TransformPoint(v);
                // world back to scene
                v    = scene.ToSceneP(v);
                vi.v = MeshTransforms.FlipLeftRightCoordSystems(vi.v);

                if (WriteNormals)
                {
                    Vector3 n = normals[i];
                    n    = filter.gameObject.transform.TransformDirection(n); // to world
                    n    = scene.ToSceneN(n);                                 // to scene
                    vi.n = MeshTransforms.FlipLeftRightCoordSystems(vi.n);
                }
                if (WriteVertexColors)
                {
                    vi.c = colors[i];
                }
                if (WriteUVs)
                {
                    vi.uv = uvs[i];
                }

                vertexMap[i] = m.AppendVertex(vi);
            }

            int[] triangles  = curMesh.triangles;
            int   nTriangles = triangles.Length / 3;

            for (int i = 0; i < nTriangles; ++i)
            {
                int a = vertexMap[triangles[3 * i]];
                int b = vertexMap[triangles[3 * i + 1]];
                int c = vertexMap[triangles[3 * i + 2]];
                m.AppendTriangle(a, c, b, gid);  // TRI ORIENTATION IS REVERSED HERE!!
            }

            return(true);
        }
Ejemplo n.º 12
0
 public void apply(DMeshSO meshSO)
 {
     meshSO.EditAndUpdateMesh((mesh) => {
         MeshTransforms.FlipLeftRightCoordSystems(mesh);
     }, GeometryEditTypes.ArbitraryEdit);    // reverses orientation, too!
 }
Ejemplo n.º 13
0
    // Use this for initialization
    public override void Awake()
    {
        // if we need to auto-configure Rift vs Vive vs (?) VR, we need
        // to do this before any other F3 setup, because MainCamera will change
        // and we are caching that in a lot of places...
        if (AutoConfigVR)
        {
            VRCameraRig = gs.VRPlatform.AutoConfigureVR();
        }

        // restore any settings
        SceneGraphConfig.RestorePreferences();

        // set up some defaults
        // this will move the ground plane down, but the bunnies will be floating...
        //SceneGraphConfig.InitialSceneTranslate = -4.0f * Vector3f.AxisY;
        SceneGraphConfig.DefaultSceneCurveVisualDegrees = 0.5f;
        SceneGraphConfig.DefaultPivotVisualDegrees      = 2.3f;
        SceneGraphConfig.DefaultAxisGizmoVisualDegrees  = 25.0f;
        PolyCurveSO.DefaultHitWidthMultiplier           = 2.5f;

        SceneOptions options = new SceneOptions();

        options.UseSystemMouseCursor  = false;
        options.Use2DCockpit          = false;
        options.EnableTransforms      = true;
        options.EnableCockpit         = true;
        options.EnableDefaultLighting = false;
        options.CockpitInitializer    = new SetupOrthoVRCockpit();

        options.MouseCameraControls = new MayaCameraHotkeys()
        {
            MousePanSpeed = 5.0f, MouseZoomSpeed = 5.0f
        };
        options.SpatialCameraRig = VRCameraRig;

        // very verbose
        options.LogLevel = 2;

        // hacks for stuff
#if F3_ENABLE_TEXT_MESH_PRO
        SceneGraphConfig.TextLabelZOffset = -0.01f;
#else
        SceneGraphConfig.TextLabelZOffset = -0.3f;
#endif


        context    = new FContext();
        OG.Context = context;
        OrthogenUI.ActiveContext = context;
        context.Start(options);


        // Set up standard scene lighting if enabled
        if (options.EnableDefaultLighting)
        {
            GameObject lighting = GameObject.Find("SceneLighting");
            if (lighting == null)
            {
                lighting = new GameObject("SceneLighting");
            }
            SceneLightingSetup setup = lighting.AddComponent <SceneLightingSetup>();
            setup.Context              = context;
            setup.ShadowLightCount     = 0;
            setup.AdjustShadowDistance = false;
            setup.LightDistance        = 1000.0f; // related to total scene scale...
        }

        // override sun so that it doesn't stick to one of the scene lights
        RenderSettings.sun = GameObject.Find("SunLight").GetComponent <Light>();

        //GameObjectFactory.CurveRendererSource = new VectrosityCurveRendererFactory();

        // set up ground plane geometry (optional)
        GameObject boundsObject = GameObject.Find("Bounds");
        if (boundsObject != null)
        {
            context.Scene.AddWorldBoundsObject(boundsObject);
        }


        /*
         * ORTHOGEN-SPECIFIC SETUP STARTS HERE
         */

        // set up scene and tools like Orthogen wants them
        OGActions.InitializeVRUsageContext();
        OrthogenMaterials.InitializeMaterials();
        OrthogenMaterials.ScanMaterial = new UnitySOMaterial(MaterialUtil.SafeLoadMaterial("scan_material"));
        //OrthogenMaterials.RectifiedLegMaterial = OrthogenMaterials.ScanMaterial;
        OGActions.InitializeF3Scene(context);
        OGActions.InitializeF3Tools(context);
        OGActions.InitializeF3VRTools(context);
        OGActions.PostConfigureTools_Demo();
        OGActions.ConfigurePlatformInput_VR();


        /*
         * optional things specific to demo app
         */

        // ground plane stays below socket as it is updated
        DemoActions.AddRepositionGroundPlaneOnSocketEdit();


        /*
         * import sample mesh
         */
        bool do_scan_demo = true;

        // load sample mesh
        string assetPath   = Application.dataPath;
        string samplesPath = Path.Combine(assetPath, "..", "sample_files");
        //string sampleFile = Path.Combine(samplesPath, "sample_socket_off.obj");
        string sampleFile = Path.Combine(samplesPath, "sample_socket_1.obj");
        if (do_scan_demo)
        {
            sampleFile = Path.Combine(samplesPath, "scan_1_remesh.obj");
        }
        if (File.Exists(sampleFile) == false)
        {
            sampleFile = Path.Combine(samplesPath, "sample_socket_1.obj");
        }
        DMesh3 mesh = StandardMeshReader.ReadMesh(sampleFile);
        // read sample file from Resources instead
        //MemoryStream sampleFileStream = FResources.LoadBinary("sample_socket_1");
        //DMesh3 mesh = StandardMeshReader.ReadMesh(sampleFileStream, "obj");
        if (mesh.HasVertexColors == false)
        {
            mesh.EnableVertexColors(Colorf.Silver);
        }

        // transform to our coordinate system
        double scale = Units.MetersTo(Units.Linear.Millimeters); // this mesh is in meters, so scale to mm
        MeshTransforms.FlipLeftRightCoordSystems(mesh);          // convert to unity coordinate system
        MeshTransforms.Scale(mesh, scale);

        if (do_scan_demo)
        {
            OGActions.SetSizeMode(OGActions.SizeModes.RealSize);
        }
        else
        {
            OGActions.SetSizeMode(OGActions.SizeModes.DemoSize);
        }

        // initialize the datamodel
        OGActions.BeginSocketDesignFromScan(Context, mesh);

        // set up my UI tests/etc
        configure_unity_ui();

        // [RMS] do this next frame because SteamVR needs a chance to set up and position the cockpit
        OGActions.RecenterVRView(true);

        add_vr_head(context);

        // dgraph tests
        //DGTest.test(Debug.Log);
    }
Ejemplo n.º 14
0
        public async Task ImportInteractive(string sFilename, Action <string> onCompletedF)
        {
            SourceFilePath = sFilename;

            DMesh3Builder      builder = new DMesh3Builder();
            StandardMeshReader reader  = new StandardMeshReader()
            {
                MeshBuilder = builder
            };

            await Task.Run(() => {
                IOReadResult result = reader.Read(SourceFilePath, ReadOptions.Defaults);
                if (result.code != IOCode.Ok)
                {
                    ErrorMessage = "MeshImporter.Import: failed with message " + result.message;
                    return;
                }
            });

            if (builder.Meshes.Count == 0)
            {
                ErrorMessage = "MeshImporter.Import: no meshes in file!";
                return;
            }

            await Task.Run(() => {
                // apply unity xforms
                foreach (DMesh3 mesh in builder.Meshes)
                {
                    MeshTransforms.ConvertZUpToYUp(mesh);
                    MeshTransforms.FlipLeftRightCoordSystems(mesh);
                }

                TriCount = 0;
                Bounds   = AxisAlignedBox3d.Empty;
                foreach (var m in builder.Meshes)
                {
                    TriCount += m.TriangleCount;
                    Bounds.Contain(m.CachedBounds);
                }
            });

            bool   bSmall    = (Bounds.MaxDim < HeightMinThreshold);
            bool   bTall     = (Bounds.Height > CC.Settings.BedSizeYMM);
            double maxXZ     = Math.Max(Bounds.Width, Bounds.Depth);
            double bedMin    = Math.Min(CC.Settings.BedSizeXMM, CC.Settings.BedSizeZMM);
            bool   bLarge    = (Bounds.Width > 2 * CC.Settings.BedSizeXMM) || (maxXZ > 2 * bedMin);
            bool   bTriCount = (TriCount > TriCountThreshold);

            switch (CCPreferences.ImportAssistantMode)
            {
            case CCPreferences.ImportAssistantModes.PhysicalSizeOnly:
                bTriCount = false; break;

            case CCPreferences.ImportAssistantModes.MeshSizeOnly:
                bLarge = bSmall = bTall = false; break;

            case CCPreferences.ImportAssistantModes.Disabled:
                bLarge = bSmall = bTall = bTriCount = false; break;
            }

            if (bTriCount || bSmall || bLarge)
            {
                ImportMeshDialog.Show(CotangentUI.MainUICanvas,
                                      bSmall, bTall, bLarge, Bounds.Height,
                                      bTriCount, TriCount,
                                      async(scale, tricount) => { await process_and_complete_import(SourceFilePath, builder, scale, tricount, onCompletedF); },
                                      async() => { await complete_import(SourceFilePath, builder, onCompletedF); }
                                      );
            }
            else
            {
                await complete_import(SourceFilePath, builder, onCompletedF);
            }
        }
Ejemplo n.º 15
0
        public bool ImportAutoUpdate(PrintMeshSO so)
        {
            SourceFilePath = so.SourceFilePath;
            if (!File.Exists(SourceFilePath))
            {
                ErrorMessage = "MeshImporter.ImportAutoUpdate: file does not exist";
                return(false);
            }

            DMesh3Builder      builder = new DMesh3Builder();
            StandardMeshReader reader  = new StandardMeshReader()
            {
                MeshBuilder = builder
            };

            long timestamp = File.GetLastWriteTime(SourceFilePath).Ticks;

            IOReadResult result = reader.Read(SourceFilePath, ReadOptions.Defaults);

            if (result.code != IOCode.Ok)
            {
                ErrorMessage = "MeshImporter.ImportAutoUpdate: failed with message " + result.message;
                return(false);
            }
            if (builder.Meshes.Count == 0)
            {
                ErrorMessage = "MeshImporter.ImportAutoUpdate: no meshes in file!";
                return(false);
            }
            if (builder.Meshes.Count != 1)
            {
                ErrorMessage = "MeshImporter.ImportAutoUpdate: can only auto-update from file with single mesh!";
                return(false);
            }
            DMesh3 mesh = builder.Meshes[0];

            // unity xforms
            MeshTransforms.ConvertZUpToYUp(mesh);
            MeshTransforms.FlipLeftRightCoordSystems(mesh);

            // wait for any active tools to finish
            // [TODO] do we need to do this?
            while (CC.ActiveContext.ToolManager.HasActiveTool())
            {
                Thread.Sleep(1000);
            }

            if (CC.ActiveScene.SceneObjects.Contains(so) == false)
            {
                ErrorMessage = "MeshImporter.ImportAutoUpdate: SO no longer exists";
                return(false);
            }

            // change event??

            so.LastReadFileTimestamp = timestamp;
            ThreadMailbox.PostToMainThread(() => {
                so.ReplaceMesh(mesh, true);
            });
            return(true);
        }
Ejemplo n.º 16
0
        public virtual ExportStatus Export(FScene scene, string filename)
        {
            int[]            vertexMap = new int[2048]; // temp
            List <WriteMesh> vMeshes   = new List <WriteMesh>();

            if (WriteFaceGroups)
            {
                throw new Exception("SceneMeshExporter.Export: writing face groups has not yet been implemented!");
            }

            // extract all the mesh data we want to export
            foreach (SceneObject so in scene.SceneObjects)
            {
                if (so.IsTemporary || so.IsSurface == false || SceneUtil.IsVisible(so) == false)
                {
                    continue;
                }
                if (SOFilterF != null && SOFilterF(so) == false)
                {
                    continue;
                }

                // if this SO has an internal mesh we can just copy, use it
                if (so is DMeshSO)
                {
                    DMeshSO meshSO = so as DMeshSO;

                    // todo: flags

                    // make a copy of mesh
                    DMesh3 m = GetMeshForDMeshSO(meshSO);

                    // transform to scene coords and swap left/right
                    foreach (int vid in m.VertexIndices())
                    {
                        Vector3f v = (Vector3f)m.GetVertex(vid);
                        v = SceneTransforms.ObjectToSceneP(meshSO, v);
                        v = MeshTransforms.FlipLeftRightCoordSystems(v);
                        m.SetVertex(vid, v);
                    }
                    m.ReverseOrientation();

                    vMeshes.Add(new WriteMesh(m, so.Name));
                }


                // Look for lower-level fGameObject items to export. By default
                // this is anything with a MeshFilter, override CollectGOChildren
                // or use GOFilterF to add restrictions
                List <fGameObject> vExports = CollectGOChildren(so);
                if (vExports.Count > 0)
                {
                    SimpleMesh m = new SimpleMesh();
                    m.Initialize(WriteNormals, WriteVertexColors, WriteUVs, WriteFaceGroups);
                    int groupCounter = 1;

                    foreach (fGameObject childgo in vExports)
                    {
                        if (GOFilterF != null && GOFilterF(so, childgo) == false)
                        {
                            continue;
                        }

                        if (AppendGOMesh(childgo, m, vertexMap, scene, groupCounter))
                        {
                            groupCounter++;
                        }
                    }

                    vMeshes.Add(new WriteMesh(m, so.Name));
                }
            }


            // ok, we are independent of Scene now and can write in bg thread
            if (WriteInBackgroundThreads)
            {
                ExportStatus status = new ExportStatus()
                {
                    Exporter = this, IsComputing = true
                };
                WriteOptions useOptions = Options;
                useOptions.ProgressFunc = (cur, max) => {
                    status.Progress    = cur;
                    status.MaxProgress = max;
                };
                BackgroundWriteThread t = new BackgroundWriteThread()
                {
                    Meshes      = vMeshes, options = useOptions, Filename = filename,
                    CompletionF = (result) => {
                        LastWriteStatus         = result.code;
                        LastErrorMessage        = result.message;
                        status.LastErrorMessage = result.message;
                        status.Ok          = (result.code == IOCode.Ok);
                        status.IsComputing = false;
                        if (BackgroundWriteCompleteF != null)
                        {
                            BackgroundWriteCompleteF(this, status);
                        }
                    }
                };
                t.Start();
                return(status);
            }
            else
            {
                IOWriteResult result = StandardMeshWriter.WriteFile(filename, vMeshes, Options);
                LastWriteStatus  = result.code;
                LastErrorMessage = result.message;
                return(new ExportStatus()
                {
                    Exporter = this, IsComputing = false,
                    Ok = (result.code == IOCode.Ok),
                    LastErrorMessage = result.message
                });
            }
        }
Ejemplo n.º 17
0
    // Use this for initialization
    public override void Awake()
    {
        // if we need to auto-configure Rift vs Vive vs (?) VR, we need
        // to do this before any other F3 setup, because MainCamera will change
        // and we are caching that in a lot of places...
        if (AutoConfigVR)
        {
            VRCameraRig = gs.VRPlatform.AutoConfigureVR();
        }

        // restore any settings
        SceneGraphConfig.RestorePreferences();

        // set up some defaults
        // this will move the ground plane down, but the bunnies will be floating...
        //SceneGraphConfig.InitialSceneTranslate = -4.0f * Vector3f.AxisY;
        SceneGraphConfig.DefaultSceneCurveVisualDegrees = 0.35f;
        SceneGraphConfig.DefaultPivotVisualDegrees      = 2.3f;
        SceneGraphConfig.DefaultAxisGizmoVisualDegrees  = 25.0f;

        // make curves easier to click
        PolyCurveSO.DefaultHitWidthMultiplier = 2.0f;

        SceneOptions options = new SceneOptions();

        options.UseSystemMouseCursor = true;
        options.EnableTransforms     = true;
        options.EnableCockpit        = true;
        options.CockpitInitializer   = new SetupOrthoGenCockpit();

        options.MouseCameraControls = new MayaCameraHotkeys()
        {
            MousePanSpeed = 5.0f, MouseZoomSpeed = 5.0f
        };
        options.SpatialCameraRig = VRCameraRig;

        options.Use2DCockpit             = true;
        options.ConstantSize2DCockpit    = true;
        FPlatform.EditorPixelScaleFactor = 1.0f;

        // very verbose
        options.LogLevel = 2;

        context    = new FContext();
        OG.Context = context;
        OrthogenUI.ActiveContext = context;
        context.Start(options);

        DebugUtil.Log("started context");

        // Set up standard scene lighting if enabled
        if (options.EnableDefaultLighting)
        {
            GameObject lighting = GameObject.Find("SceneLighting");
            if (lighting == null)
            {
                lighting = new GameObject("SceneLighting");
            }
            SceneLightingSetup setup = lighting.AddComponent <SceneLightingSetup>();
            setup.Context       = context;
            setup.LightDistance = 30.0f; // related to total scene scale...
        }


        //GameObjectFactory.CurveRendererSource = new VectrosityCurveRendererFactory();

        // set up ground plane geometry (optional)
        GameObject boundsObject = GameObject.Find("Bounds");

        if (boundsObject != null)
        {
            context.Scene.AddWorldBoundsObject(boundsObject);
        }


        /*
         * ORTHOGEN-SPECIFIC SETUP STARTS HERE
         */

        // set up scene and tools like Orthogen wants them
        OGActions.InitializeUsageContext(OGActions.UsageContext.OrthoVRApp);
        //OGActions.InitializeUsageContext(OGActions.UsageContext.NiaOrthogenApp);
        OrthogenMaterials.InitializeMaterials();
        OGActions.InitializeF3Scene(context);
        OGActions.InitializeF3Tools(context);
        OGActions.PostConfigureTools_Demo();
        OGActions.ConfigurePlatformInput_Mouse();

        /*
         * optional things specific to demo app
         */

        // ground plane stays below socket as it is updated
        DemoActions.AddRepositionGroundPlaneOnSocketEdit();


        /*
         * import sample mesh
         */

        // load sample mesh
        string assetPath   = Application.dataPath;
        string samplesPath = Path.Combine(assetPath, "..", "sample_files");
        //string sampleFile = Path.Combine(samplesPath, "sample_socket_off.obj");
        //string sampleFile = Path.Combine(samplesPath, "sample_socket_1.obj");
        //string sampleFile = Path.Combine(samplesPath, "scan_1_raw.obj");
        string sampleFile = Path.Combine(samplesPath, "scan_1_remesh.obj");
        DMesh3 mesh       = StandardMeshReader.ReadMesh(sampleFile);

        if (mesh.HasVertexColors == false)
        {
            mesh.EnableVertexColors(Colorf.Silver);
        }
        // read sample file from Resources instead
        //MemoryStream sampleFileStream = FResources.LoadBinary("sample_socket_1");
        //DMesh3 mesh = StandardMeshReader.ReadMesh(sampleFileStream, "obj");
        double scale = Units.MetersTo(Units.Linear.Millimeters); // this mesh is in meters, so scale to mm

        MeshTransforms.FlipLeftRightCoordSystems(mesh);          // convert to unity coordinate system
        MeshTransforms.Scale(mesh, scale);

        // initialize the datamodel
        OGActions.BeginSocketDesignFromScan(Context, mesh);

        // set up my UI tests/etc
        configure_unity_ui();

        // dgraph tests
        //DGTest.test(Debug.Log);
    }