Exemplo n.º 1
0
 /*
  * Load Stl
  */
 private void LoadSTLModel_Click(object sender, EventArgs e)
 {
     if (openFileDialog1.ShowDialog() == DialogResult.OK)
     {
         UVDLPApp.Instance().m_obj = new Object3d();
         if (UVDLPApp.Instance().m_obj.LoadSTL(openFileDialog1.FileName) == false)
         {
             MessageBox.Show("Error loading file " + openFileDialog1.FileName);
         }
         else
         {
             ShowObjectInfo();
             chkWireframe.Checked = false;
             UVDLPApp.Instance().Engine3D.RemoveAllObjects();
             UVDLPApp.Instance().Engine3D.AddObject(UVDLPApp.Instance().m_obj);
             UVDLPApp.Instance().m_slicefile = null;
             glControl1.Invalidate();
             vScrollBar1.Maximum = 1;
             vScrollBar1.Value   = 0;
         }
     }
 }
Exemplo n.º 2
0
 public bool Load(String filename)
 {
     try
     {
         XmlHelper xh        = new XmlHelper();
         bool      fileExist = xh.Start(filename, "ApplicationConfig");
         XmlNode   ac        = xh.m_toplevel;
         m_LastModelFilename      = xh.GetString(ac, "LastModelName", "");
         m_cursliceprofilename    = UVDLPApp.Instance().m_PathProfiles + UVDLPApp.m_pathsep + xh.GetString(ac, "SliceProfileName", "default.slicing");
         m_curmachineeprofilename = UVDLPApp.Instance().m_PathMachines + UVDLPApp.m_pathsep + xh.GetString(ac, "MachineProfileName", "NullMachine.machine");
         m_autoconnect            = xh.GetBool(ac, "AutoConnect", false);
         m_loadlastmodel          = xh.GetBool(ac, "LoadLastModel", true);
         m_slic3rloc                 = xh.GetString(ac, "Slic3rLocation", "");
         m_slic3rparameters          = xh.GetString(ac, "Slic3rParams", "");
         m_foregroundcolor           = xh.GetColor(ac, "ForegroundColor", Color.White);
         m_backgroundcolor           = xh.GetColor(ac, "BackgroundColor", Color.Black);
         m_previewslicesbuilddisplay = xh.GetBool(ac, "PreviewSlices", false);
         m_viewslice3d               = xh.GetBool(ac, "Preview3dSlice", false);
         m_viewslice3dheight         = xh.GetBool(ac, "Preview3dSliceHeight", false);
         m_driverdebuglog            = xh.GetBool(ac, "DriverLogging", false);
         m_ignore_response           = xh.GetBool(ac, "IgnoreGCRsp", false);
         m_showBoundingBox           = xh.GetBool(ac, "ShowBoundingBox", true);
         m_showShaded                = xh.GetBool(ac, "ShowShaded", false);
         m_showOutline               = xh.GetBool(ac, "ShowOutline", false);
         m_licensekey                = xh.GetString(ac, "LicenseKey", "00000000000000000000");
         m_serveraddress             = xh.GetString(ac, "ServerAddress", "www.buildyourownsla.com");
         m_contactform               = xh.GetString(ac, "ContactForm", "cwupdate.php");
         if (!fileExist)
         {
             xh.Save(FILE_VERSION);
         }
         return(true);
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogRecord(ex.Message);
         return(false);
     }
 }
Exemplo n.º 3
0
 private void cmdConnect1_Click(object sender, EventArgs e)
 {
     try
     {
         if (!UVDLPApp.Instance().m_deviceinterface.Connected) //
         {
             //maybe get the com port if it's different?
             //UVDLPApp.Instance().m_printerinfo.m_driverconfig.m_connection.comname = com;
             UVDLPApp.Instance().m_deviceinterface.Configure(UVDLPApp.Instance().m_printerinfo.m_driverconfig.m_connection);
             String com = UVDLPApp.Instance().m_printerinfo.m_driverconfig.m_connection.comname;
             DebugLogger.Instance().LogRecord("Connecting to Printer on " + com + " using " + UVDLPApp.Instance().m_printerinfo.m_driverconfig.m_drivertype.ToString());
             if (!UVDLPApp.Instance().m_deviceinterface.Connect())
             {
                 DebugLogger.Instance().LogRecord("Cannot connect printer driver on " + com);
             }
         }
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogRecord(ex.Message);
     }
 }
 public bool SendProjCommand(string displayname, string commandname)
 {
     try
     {
         // get the projector command for 'on'
         // ACER_ON
         ProjectorCommand pcmd = UVDLPApp.Instance().m_proj_cmd_lst.FindByName(commandname);
         if (pcmd != null)
         {
             DeviceDriver dd = DisplayManager.Instance().FindDisplaySerialPortDriverByName(displayname);
             if (dd != null)
             {
                 if (dd.Connected)
                 {
                     byte[] data = pcmd.GetBytes();
                     dd.Write(data, data.Length);
                     return(true);
                 }
                 else
                 {
                     DebugLogger.Instance().LogError("Projector Driver not connected");
                 }
             }
             else
             {
                 DebugLogger.Instance().LogError("Projector Driver not found");
             }
         }
         else
         {
             DebugLogger.Instance().LogError("Projector command not found");
         }
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogError(ex);
     }
     return(false);
 }
Exemplo n.º 5
0
        private void SetButtonStatuses()
        {
            if (UVDLPApp.Instance().m_deviceinterface.Connected)
            {
                buttConnect.Enabled    = false;
                buttDisconnect.Enabled = true;

                if (UVDLPApp.Instance().m_buildmgr.IsPrinting)
                {
                    if (UVDLPApp.Instance().m_buildmgr.IsPaused())
                    {
                        buttPlay.Enabled  = true;
                        buttStop.Enabled  = true;
                        buttPause.Enabled = false;
                    }
                    else
                    {
                        buttPlay.Enabled  = false;
                        buttStop.Enabled  = true;
                        buttPause.Enabled = true;
                    }
                }
                else
                {
                    buttPlay.Enabled  = true;
                    buttStop.Enabled  = false;
                    buttPause.Enabled = false;
                }
            }
            else
            {
                buttConnect.Enabled    = true;
                buttDisconnect.Enabled = false;
                buttPlay.Enabled       = false;
                buttStop.Enabled       = false;
                buttPause.Enabled      = false;
            }
            Refresh();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Loads a model, adds it to the 3d engine to be shown, and raises an app event
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool LoadModel(String filename)
        {
            try
            {
                ModelLoader     ml   = new ModelLoader();
                List <Object3d> objs = ml.Load(filename);
                if (objs != null)
                {
                    foreach (Object3d obj in objs)
                    {
                        obj.CenterOnPlatform();
                        m_engine3d.AddObject(obj);
                        m_undoer.SaveAddition(obj);
                        SelectedObject = obj;
                        //test code to create a preview, this should definitely go somewhere else

                        /*PreviewGenerator pg = new PreviewGenerator();
                         * Bitmap preview = pg.GeneratePreview(512, 512, obj);
                         * if(preview !=null)
                         *  preview.Save(UVDLPApp.Instance().m_apppath + "\\testpreview.png");*/
                    }
                    UVDLPApp.Instance().m_engine3d.UpdateLists();
                    m_slicefile = null; // the slice file is not longer current
                    RaiseAppEvent(eAppEvent.eModelAdded, "Model Loaded " + filename);
                }
                else
                {
                    RaiseAppEvent(eAppEvent.eModelNotLoaded, "Model " + filename + " Failed to load");
                }

                return(objs != null);
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogRecord(ex.Message);
                return(false);
            }
        }
Exemplo n.º 7
0
        private void SliceEv(Slicer.eSliceEvent ev, int layer, int totallayers, SliceFile sf)
        {
            try
            {
                if (InvokeRequired)
                {
                    BeginInvoke(new MethodInvoker(delegate() { SliceEv(ev, layer, totallayers, sf); }));
                }
                else
                {
                    switch (ev)
                    {
                    case Slicer.eSliceEvent.eSliceStarted:
                        SetMainMessage("Slicing Started");
                        break;

                    case Slicer.eSliceEvent.eLayerSliced:
                        break;

                    case Slicer.eSliceEvent.eSliceCompleted:
                        //show the gcode
                        ctlGcodeView1.Text = UVDLPApp.Instance().m_gcode.RawGCode;
                        ctl3DView1.SetNumLayers(totallayers);
                        ctlSliceView1.SetNumLayers(totallayers);
                        SetMainMessage("Slicing Completed");
                        String timeest = BuildManager.EstimateBuildTime(UVDLPApp.Instance().m_gcode);
                        SetTimeMessage("Estimated Build Time: " + timeest);
                        //show the slice in the slice view
                        ViewLayer(0, null, BuildManager.SLICE_NORMAL);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex.Message);
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Removes the currently selected object
 /// </summary>
 public void RemoveCurrentModel()
 {
     try
     {
         if (SelectedObject != null)
         {
             UVDLPApp.Instance().m_undoer.SaveDelition(SelectedObject);
             foreach (Object3d sup in SelectedObject.m_supports)
             {
                 UVDLPApp.Instance().m_undoer.SaveDelition(sup);
                 UVDLPApp.Instance().m_undoer.LinkToPrev();
                 m_engine3d.RemoveObject(sup, false); // remove all the supports of this object, hold out on sending events
             }
             m_engine3d.RemoveObject(SelectedObject); // now remove the object
             SelectedObject = null;
             RaiseAppEvent(eAppEvent.eModelRemoved, "model removed");
         }
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogError(ex);
     }
 }
Exemplo n.º 9
0
 private void SetConnectionStatus()
 {
     if (UVDLPApp.Instance().m_deviceinterface.Connected)
     {
         cmdConnect.Enabled    = false;
         cmdDisconnect.Enabled = true;
         //cmdRefresh.Enabled = false;
         //cmbSerial.Enabled = false;
         cmdControl.Enabled = true;
         cmdBuild.Enabled   = true;
         cmdStop.Enabled    = true;
     }
     else
     {
         cmdConnect.Enabled    = true;
         cmdDisconnect.Enabled = false;
         //cmdRefresh.Enabled = true;
         //cmbSerial.Enabled = true;
         cmdControl.Enabled = false;
         cmdBuild.Enabled   = false;
         cmdStop.Enabled    = false;
     }
 }
Exemplo n.º 10
0
 private bool GetValues()
 {
     try
     {
         UVDLPApp.Instance().m_buildparms.ZThick = Single.Parse(txtZThick.Text);
         UVDLPApp.Instance().m_buildparms.exportgcode = chkgengcode.Checked;
         UVDLPApp.Instance().m_buildparms.exportimages = chkExportSlices.Checked;
         UVDLPApp.Instance().m_buildparms.exportsvg = chkexportsvg.Checked;
         UVDLPApp.Instance().m_buildparms.layertime_ms = int.Parse(txtLayerTime.Text);
         UVDLPApp.Instance().m_buildparms.firstlayertime_ms = int.Parse(txtFirstLayerTime.Text);
         UVDLPApp.Instance().m_buildparms.blanktime_ms = int.Parse(txtBlankTime.Text);
         UVDLPApp.Instance().m_buildparms.XOffset = int.Parse(txtXOffset.Text);
         UVDLPApp.Instance().m_buildparms.YOffset = int.Parse(txtYOffset.Text);
         UVDLPApp.Instance().m_buildparms.liftdistance = double.Parse(txtLiftDistance.Text);
         UVDLPApp.Instance().m_buildparms.direction = (SliceBuildConfig.eBuildDirection)Enum.Parse(typeof(SliceBuildConfig.eBuildDirection), cmbBuildDirection.SelectedItem.ToString());
         return(true);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Please check input parameters\r\n" + ex.Message, "Input Error");
         return(false);
     }
 }
Exemplo n.º 11
0
        /*
         * /// <summary>
         * /// Adds a new dummy support
         * /// </summary>
         * public void AddSupport()
         * {
         *  // Cylinder3d cyl = new Cylinder3d();
         *  // cyl.Create(2.5, 1.5, 10, 15, 2);
         *  Support s = new Support();
         *  //s.Create((float)m_supportconfig.fbrad, 1.5f, 1.5f, .75f, 2f, 5f, 2f, 20);
         *  s.Create(null, (float)m_supportconfig.fbrad, (float)m_supportconfig.ftrad, (float)m_supportconfig.hbrad,
         *      (float)m_supportconfig.htrad, 2f, 5f, 2f, 11);
         *  m_engine3d.AddObject(s);
         *  UVDLPApp.Instance().m_undoer.SaveAddition(s);
         *  RaiseAppEvent(eAppEvent.eModelAdded, "Model Created");
         * }
         */
        /// <summary>
        /// Adds a support base plate under objects
        /// </summary>
        public void AddSupportBase(bool selectedObjectsOnly)
        {
            // add support base - SHS
            List <Object3d> stdObs = new List <Object3d>();

            foreach (Object3d obj in UVDLPApp.Instance().m_engine3d.m_objects)
            {
                if (selectedObjectsOnly && !obj.m_inSelectedList)
                {
                    continue;
                }

                if ((obj != null) && (obj.tag == Object3d.OBJ_NORMAL))
                {
                    stdObs.Add(obj);
                }
            }

            foreach (Object3d obj in stdObs)
            {
                // remove old support base if exists
                SupportBase sb = obj.GetSupportBase();
                if (sb != null)
                {
                    obj.RemoveSupport(sb);
                    UVDLPApp.Instance().m_undoer.SaveDelition(sb);
                    UVDLPApp.Instance().m_engine3d.RemoveObject(sb);
                }
                sb = new SupportBase();
                sb.Generate(obj, 5);
                //lstsupports.Add(sb);
                obj.AddSupport(sb);
                m_engine3d.AddObject(sb);
                UVDLPApp.Instance().m_undoer.SaveAddition(sb);
            }
            RaiseAppEvent(eAppEvent.eModelAdded, "Support bases Created");
        }
Exemplo n.º 12
0
        private void ViewLayer(int layer, Bitmap image, int layertype)
        {
            try
            {
                // if this is a normal slice that is specified, move to the correct 3d view of the layer,
                // otherwise, keep showing the current 3d layer
                if (layertype == BuildManager.SLICE_NORMAL)
                {
                    Slice sl = (Slice)UVDLPApp.Instance().m_slicefile.m_slices[layer];
                    UVDLPApp.Instance().Engine3D.RemoveAllLines();
                    UVDLPApp.Instance().Engine3D.AddGrid();
                    UVDLPApp.Instance().Engine3D.AddPlatCube();

                    foreach (PolyLine3d ln in sl.m_segments)
                    {
                        ln.m_color = Color.Red;
                        UVDLPApp.Instance().Engine3D.AddLine(ln);
                    }
                    glControl1.Invalidate();
                }
                //render the 2d slice
                Bitmap bmp = null;
                if (image == null) // we're here because of the scroll bar in the gui
                {
                    bmp = UVDLPApp.Instance().m_slicefile.RenderSlice(layer);
                }
                else // the image was specified from the build manager
                {
                    bmp = image;
                }
                //this bmp could be a normal, blank, or calibration image
                picSlice.Image = bmp;//now show the 2d slice
                m_frmdlp.ShowImage(bmp);
                //lblCurSlice.Text = "Layer = " +layer;
            }
            catch (Exception) { }
        }
Exemplo n.º 13
0
        void PrintStatus(ePrintStat printstat)
        {
            // displays the print status
            if (InvokeRequired)
            {
                BeginInvoke(new MethodInvoker(delegate() { PrintStatus(printstat); }));
            }
            else
            {
                String message = "";
                switch (printstat)
                {
                case ePrintStat.ePrintCancelled:
                    message = "Print Cancelled";
                    break;

                case ePrintStat.eLayerCompleted:
                    message = "Layer Completed";
                    break;

                case ePrintStat.ePrintCompleted:
                    message = "Print Completed";
                    MessageBox.Show("Build Completed");
                    break;

                case ePrintStat.ePrintStarted:
                    message = "Print Started";
                    if (!ShowDLPScreen())
                    {
                        MessageBox.Show("Monitor " + UVDLPApp.Instance().m_printerinfo.m_monitorid + " not found, cancelling build", "Error");
                        UVDLPApp.Instance().m_buildmgr.CancelPrint();
                    }
                    break;
                }
                DebugLogger.Instance().LogRecord(message);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// This will return an intersection, not necessarily the closest one.
        /// </summary>
        /// <param name="direction"></param>
        /// <param name="origin"></param>
        /// <param name="intersect"></param>
        /// <returns></returns>
        public static bool FindIntersection(Vector3d direction, Point3d origin, ref Point3d intersect)
        {
            direction.Normalize();
            direction.Scale(10000.0);
            Point3d endp = new Point3d();

            endp.Set(origin);
            endp.x += direction.x;
            endp.y += direction.y;
            endp.z += direction.z;
            foreach (Polygon p in UVDLPApp.Instance().Scene.m_lstpolys)
            {
                intersect = new Point3d();
                // try a less- costly sphere intersect here
                if (RTUtils.IntersectSphere(origin, endp, ref intersect, p.m_center, p.m_radius))
                {
                    // if it intersects,
                    if (RTUtils.IntersectPoly(p, origin, endp, ref intersect))
                    {
                        return(true);

                        /*
                         * // and it's the lowest one
                         * if (intersect.z <= lowest.z)
                         * {
                         *  //save this point
                         *  intersected = true;
                         *  lowest.Set(intersect);
                         * }
                         * */
                    }
                }
            }


            return(false);
        }
Exemplo n.º 15
0
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException +=
                new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.EnableVisualStyles();
            Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            SetDefaultCulture(System.Globalization.CultureInfo.InvariantCulture);
            Application.SetCompatibleTextRenderingDefault(false);
            //init the app object


            if (UVDLPApp.Instance().DoAppStartup() == false) // start the app and load the plug-ins
            {
                Application.Exit();                          // by esyeon 20160127
                return;
            }



            // by esyeon 20151230


            try
            {
#if !DEBUG                                          // no splash screen under debug release
                frmSplash splash = new frmSplash(); // should pull from a licensed plug-in if need-be
                splash.Show();
#endif
                Application.Run(new frmMain2());
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex);
            }
        }
        /// <summary>
        /// I think I need to change this to make multiple posts
        /// one post for each licensed plug-in
        /// </summary>
        private void ContactServerThread()
        {
            // try the HTTP Post
            try
            {
                WebClient client   = new WebClient();
                string    postform = UVDLPApp.Instance().m_appconfig.m_contactform;
                string    posturl  = UVDLPApp.Instance().m_appconfig.m_serveraddress;
                string    postaddr = posturl + "/" + postform;
                foreach (PluginEntry pe in UVDLPApp.Instance().m_plugins)//foreach licensed plugin, generate the info...
                {
                    try
                    {
                        NameValueCollection nvc = new NameValueCollection();;
                        nvc["CWVersion"]        = Application.ProductVersion;                     // include the product version
                        nvc["Machine_ID"]       = FingerPrint.Value();                            //get the unique identifier of this machine
                        nvc["PluginLicenseKey"] = FindLicenseKey(pe.m_plugin.GetInt("VendorID")); // find the license key for this plugin
                        nvc["PluginName"]       = pe.m_plugin.GetString("PluginName");            //
                        nvc["PluginVendorID"]   = pe.m_plugin.GetInt("VendorID").ToString();
                        nvc["PluginVendorName"] = pe.m_plugin.GetString("VendorName");
                        nvc["PluginVersion"]    = pe.m_plugin.GetString("Version");// version of the plugin

                        var    response = client.UploadValues(postaddr, "POST", nvc);
                        string resp     = Encoding.Default.GetString(response);
                        //DebugLogger.Instance().LogInfo(resp); // log the response as a test
                        ParseResponse(resp);//parse the response
                    }
                    catch (Exception) { }
                }
            }
            catch (Exception ex)
            {
                //DebugLogger.Instance().LogError(ex);
                // may want to silently fail here
            }
        }
Exemplo n.º 17
0
        /*
         * This is the thread that controls the build process
         * it needs to read the lines of gcode, one by one
         * send them to the printer interface,
         * wait for the printer to respond,
         * and also wait for the layer interval timer
         */
        void BuildThread()
        {
            int now = GetTimerValue();
            int nextlayertime = 0;
            int sltime = -1, bltime = -1;

            while (m_running)
            {
                try
                {
                    //Thread.Sleep(1); //  sleep for 1 ms max
                    Thread.Sleep(0); //  sleep for 1 ms max
                    switch (m_state)
                    {
                    case BuildManager.STATE_START:
                        //start things off, reset some variables
                        RaiseStatusEvent(eBuildStatus.eBuildStarted, "Build Started");
                        m_state          = BuildManager.STATE_DO_NEXT_LAYER; // go to the first layer
                        m_gcodeline      = 0;                                // set the start line
                        m_curlayer       = 0;
                        m_printstarttime = new DateTime();
                        break;

                    case BuildManager.STATE_WAITING_FOR_LAYER:
                        //check time var
                        if (GetTimerValue() >= nextlayertime)
                        {
                            //   DebugLogger.Instance().LogInfo("elapsed Layer time: " + GetTimerValue().ToString());
                            //   DebugLogger.Instance().LogInfo("Diff = " + (GetTimerValue() - nextlayertime).ToString());
                            m_state = BuildManager.STATE_DO_NEXT_LAYER;     // move onto next layer
                        }
                        break;

                    case BuildManager.STATE_IDLE:
                        // do nothing
                        break;

                    case BuildManager.STATE_DO_NEXT_LAYER:
                        //check for done
                        if (m_gcodeline >= m_gcode.Lines.Length)
                        {
                            //we're done..
                            m_state = BuildManager.STATE_DONE;
                            continue;
                        }
                        string line = "";
                        // if the driver reports we're ready for the next command, or
                        // if we choose to ignore the driver ready status
                        if (UVDLPApp.Instance().m_deviceinterface.ReadyForCommand() || (UVDLPApp.Instance().m_appconfig.m_ignoreGCrsp == true))
                        {
                            // go through the gcode, line by line
                            line = m_gcode.Lines[m_gcodeline++];
                        }
                        else
                        {
                            continue;     // device is not ready
                        }
                        line = line.Trim();
                        if (line.Length > 0)     // if the line is not blank
                        {
                            // send  the line, whether or not it's a comment
                            // should check to see if the firmware is ready for another line

                            UVDLPApp.Instance().m_deviceinterface.SendCommandToDevice(line + "\r\n");
                            // if the line is a comment, parse it to see if we need to take action
                            if (line.Contains("<Delay> "))    // get the delay
                            {
                                nextlayertime = GetTimerValue() + getvarfromline(line);
                                //DebugLogger.Instance().LogInfo("Next Layer time: " + nextlayertime.ToString());
                                m_state = STATE_WAITING_FOR_LAYER;
                                continue;
                            }
                            else if (line.Contains("<DispCmd>"))      // display command
                            {
                                PerformDisplayCommand(line);
                            }
                            else if (line.Contains("<Slice> "))    //get the slice number
                            {
                                int    layer   = getvarfromline(line);
                                int    curtype = BuildManager.SLICE_NORMAL;  // assume it's a normal image to begin with
                                Bitmap bmp     = null;

                                if (layer == SLICE_BLANK)
                                {
                                    if (m_blankimage == null)      // blank image is null, create it
                                    {
                                        MakeBlank(m_sf.XRes, m_sf.YRes);
                                    }
                                    bmp     = m_blankimage;
                                    curtype = BuildManager.SLICE_BLANK;
                                    bltime  = GetTimerValue();
                                    //DebugLogger.Instance().LogInfo("Showing Blank image at :" + bltime.ToString());
                                    if (sltime != -1 && bltime != -1)
                                    {
                                        DebugLogger.Instance().LogInfo("Time between Blank and Slice :" + (bltime - sltime).ToString());
                                    }
                                }
                                else if (layer == SLICE_SPECIAL)     // plugins can override special images by named resource
                                {
                                    // get the special image from the plugin (no caching for now..)
                                    string special = GetSpecialName(line);
                                    bmp = UVDLPApp.Instance().GetPluginImage(special);
                                    if (bmp == null)              // no special image, even though it's specified..
                                    {
                                        if (m_blankimage == null) // blank image is null, create it
                                        {
                                            MakeBlank(m_sf.XRes, m_sf.YRes);
                                        }
                                        bmp = m_blankimage;
                                    }
                                    curtype = BuildManager.SLICE_BLANK;
                                }
                                else
                                {
                                    m_curlayer = layer;
                                    bmp        = m_sf.GetSliceImage(m_curlayer); // get the rendered image slice or load it if already rendered
                                    if (bmp == null)
                                    {
                                        DebugLogger.Instance().LogError("Buildmanager bitmap is null layer = " + m_curlayer + " ");
                                    }
                                    sltime = GetTimerValue();
                                    //DebugLogger.Instance().LogInfo("Showing Slice image at :" + sltime.ToString());
                                    if (sltime != -1 && bltime != -1)
                                    {
                                        DebugLogger.Instance().LogInfo("Time between slice and blank :" + (sltime - bltime).ToString());
                                    }
                                }

                                //raise a delegate so the main form can catch it and display layer information.
                                if (PrintLayer != null)
                                {
                                    PrintLayer(bmp, m_curlayer, curtype);
                                }
                            }
                        }
                        break;

                    case BuildManager.STATE_DONE:
                        try
                        {
                            m_running = false;
                            m_state   = BuildManager.STATE_IDLE;
                            StopBuildTimer();
                            DateTime endtime      = new DateTime();
                            double   totalminutes = (endtime - m_printstarttime).TotalMinutes;

                            m_printing = false;     // mark printing doe
                            //raise done message
                            RaiseStatusEvent(eBuildStatus.eBuildStatusUpdate, "Build 100% Completed");
                            RaiseStatusEvent(eBuildStatus.eBuildCompleted, "Build Completed");
                        }
                        catch (Exception ex)
                        {
                            DebugLogger.Instance().LogError(ex.StackTrace);
                        }
                        break;
                    }
                }
                catch (Exception ex)
                {
                    DebugLogger.Instance().LogError(ex.StackTrace);
                }
            }
        }
Exemplo n.º 18
0
 private void cmdsavepostliftgcode_Click(object sender, EventArgs e)
 {
     m_config.PostLiftCode = txtpostliftgcode.Text;
     m_config.SaveFile(UVDLPApp.Instance().ProfilePathString() + "postlift.gcode", txtpostliftgcode.Text);
 }
Exemplo n.º 19
0
 private void txtsaveendgcode_Click(object sender, EventArgs e)
 {
     m_config.FooterCode = txtendgcode.Text;
     m_config.SaveFile(UVDLPApp.Instance().ProfilePathString() + "end.gcode", txtendgcode.Text);
 }
Exemplo n.º 20
0
 private void cmdsavestartgcode_Click(object sender, EventArgs e)
 {
     m_config.HeaderCode = txtstartgcode.Text;
     m_config.SaveFile(UVDLPApp.Instance().ProfilePathString() + "start.gcode", txtstartgcode.Text);
 }
Exemplo n.º 21
0
 private void cmdsavepreslicegcode_Click(object sender, EventArgs e)
 {
     m_config.PreSliceCode = txtpreslicegcode.Text;
     m_config.SaveFile(UVDLPApp.Instance().ProfilePathString() + "preslice.gcode", txtpreslicegcode.Text);
 }
Exemplo n.º 22
0
        /// <summary>
        /// This function sends commands to the projector(s)
        /// The format is <DispCmd> MonitorID , cmdname
        /// Monitor ID can be any monitor on the system, or ALL
        /// </summary>
        /// <param name="line"></param>
        private void PerformDisplayCommand(string line)
        {
            try
            {
                line = line.Replace(';', ' '); // remove comments
                line = line.Replace(')', ' '); // remove comments
                int bidx = line.IndexOf('>');
                if (bidx == -1)
                {
                    DebugLogger.Instance().LogError("Improperly formated display command");
                    return;
                }
                string   ss1   = line.Substring(bidx + 1);
                string[] lines = ss1.Split(',');
                if (lines.Length != 2)
                {
                    DebugLogger.Instance().LogError("Improperly formated display command");
                    return;
                }
                string monname = lines[0].Trim();
                string cmdname = lines[1].Trim();
                //get the command name
                ProjectorCommand pc = null;
                pc = UVDLPApp.Instance().m_proj_cmd_lst.FindByName(cmdname);
                if (pc == null)
                {
                    DebugLogger.Instance().LogError("Could not find Display Command " + cmdname);
                    return;
                }
                // get the monitor ID
                if (monname.Equals("All"))
                {
                    //iterate through all configured monitors in machine monitor list
                    foreach (MonitorConfig mc in UVDLPApp.Instance().m_printerinfo.m_lstMonitorconfigs)
                    {
                        SendProjCmd(mc, pc);
                    }
                }
                else
                {
                    MonitorConfig mc = UVDLPApp.Instance().m_printerinfo.FindMonitorByName(monname);
                    if (mc != null)
                    {
                        SendProjCmd(mc, pc);
                    }
                    else
                    {
                        DebugLogger.Instance().LogError("Monitor ID " + monname + " not found");
                        return;
                    }
                }

                // get the commands name
                //find the command in the projector command list
                // make sure the com port for the projector is open
                //send the command to the projector over serial
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex);
            }
        }
Exemplo n.º 23
0
 private void cmdStop_Click(object sender, EventArgs e)
 {
     UVDLPApp.Instance().m_buildmgr.CancelPrint();
 }
Exemplo n.º 24
0
        //alright, it looks like I'm going to have to code up a 2d scanline fill algorithm
        // I suppose the first step is to convert all the 3d-ish polyline points in this slice into
        // 2d polylines, then use those to implement the fill
        /// <summary>
        /// This new slicing function renders into a pre-allocated bitmap
        /// </summary>
        /// <param name="sp"></param>
        /// <param name="bmp"></param>
        public void RenderSlice(SliceBuildConfig sp, ref Bitmap bmp)
        {
            try
            {
                Graphics graph = Graphics.FromImage(bmp);
                Point    pnt1  = new Point(); // create some points for drawing
                Point    pnt2  = new Point();
                Pen      pen   = new Pen(UVDLPApp.Instance().m_appconfig.m_foregroundcolor, 1);
                //convert all to 2d lines
                int hxres = sp.xres / 2;
                int hyres = sp.yres / 2;

                List <Line2d> lines2d = Get2dLines(sp, m_segments);
                if (lines2d.Count == 0)
                {
                    return;
                }
                Render2dlines(graph, lines2d, sp);

                // find the x/y min/max
                MinMax_XY mm = CalcMinMax_XY(lines2d);
                // iterate from the ymin to the ymax
                for (int y = mm.ymin; y < mm.ymax; y++) // this needs to be in scaled value
                {
                    //      get a line of lines that intersect this 2d line
                    List <Line2d> intersecting = GetIntersecting2dYLines(y, lines2d);
                    //      get the list of point intersections
                    List <Point2d> points = GetIntersectingPoints(y, intersecting);
                    // sort the points in increasing x order
                    //SortXIncreasing(points);
                    points.Sort();
                    SortBackfaces(points);

                    if (UVDLPApp.Instance().m_slicer.m_slicemethod == Slicer.eSliceMethod.eEvenOdd)
                    {
                        //      draw the X-Spans (should be even number)
                        //    For a given pair of intersectin points
                        //    (Xi, Y), (Xj, Y)
                        //  −> Fill ceiling(Xi) to floor(Xj)

                        if (points.Count % 2 == 0)                          // is even
                        {
                            for (int cnt = 0; cnt < points.Count; cnt += 2) // increment by 2
                            {
                                Point2d p1 = (Point2d)points[cnt];
                                Point2d p2 = (Point2d)points[cnt + 1];
                                pnt1.X = (int)(p1.x + sp.XOffset + hxres);
                                pnt1.Y = (int)(p1.y + sp.YOffset + hyres);
                                pnt2.X = (int)(p2.x + sp.XOffset + hxres);
                                pnt2.Y = (int)(p2.y + sp.YOffset + hyres);
                                //graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                                graph.DrawLine(pen, pnt1.X, pnt1.Y, pnt2.X, pnt2.Y);
                            }
                        }
                        else  // flag error
                        {
                            DebugLogger.Instance().LogRecord("Row y=" + y + " odd # of points = " + points.Count + " - Model may have holes");
                        }
                    }

                    else if (UVDLPApp.Instance().m_slicer.m_slicemethod == Slicer.eSliceMethod.eNormalCount)
                    {
                        Point2d p1        = null;
                        Point2d p2        = null;
                        int     turncount = 0;
                        if (points.Count != 0)
                        {
                            for (int cnt = 0; cnt < points.Count; cnt++)
                            {
                                if (points[cnt].m_backfacing)
                                {
                                    if (turncount == 0) //p1 == null)
                                    {
                                        p1 = (Point2d)points[cnt];
                                    }
                                    turncount++;
                                }
                                else
                                {
                                    //if (turncount > 0)
                                    turncount--;
                                    if ((turncount == 0) && (p1 != null))
                                    {
                                        p2     = (Point2d)points[cnt];
                                        pnt1.X = (int)(p1.x + sp.XOffset + hxres);
                                        pnt1.Y = (int)(p1.y + sp.YOffset + hyres);
                                        pnt2.X = (int)(p2.x + sp.XOffset + hxres);
                                        pnt2.Y = (int)(p2.y + sp.YOffset + hyres);
                                        //graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                                        graph.DrawLine(pen, pnt1.X, pnt1.Y, pnt2.X, pnt2.Y);
                                        p1 = p2;
                                        p2 = null;
                                    }
                                }
                            }
                            if (turncount != 0)// flag error
                            {
                                DebugLogger.Instance().LogRecord("Row y=" + y + " non equal in/outs = " + turncount + " - Model may have holes");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex.Message);
            }
        }
Exemplo n.º 25
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            SetDefaultCulture(System.Globalization.CultureInfo.InvariantCulture);
            Application.SetCompatibleTextRenderingDefault(false);
            //init the app object
            UVDLPApp.Instance().DoAppStartup(); // start the app and load the plug-ins
            //iterate through the plugins
            bool showlicensedialog = false;
            bool nosplash = false;
            //iterate through all plugins,
            // if they are un-licensed and enabled - show licensing dialog.
            foreach (PluginEntry pe in UVDLPApp.Instance().m_plugins)
            {
                if (pe.m_licensed == false && pe.m_enabled == true) // if we don't have a license, and it's marked enabled
                {
                    showlicensedialog = true;
                }
                int options = pe.m_plugin.GetInt("Options");
                if (options != -1 && pe.m_enabled == true) // check to see if this plugin has options
                {
                    if ((options & PluginOptions.OPTION_TIMED_TRIAL) != 0) // check for timed trial bit
                    {
                        // check for trial version
                        //start trial version
                        if (!CheckTrial(pe))
                        {
                            //disable the plug-in
                            pe.m_enabled = false;
                            //exit?
                            Application.Exit();
                            return;

                        }
                    }
                    if ((options & PluginOptions.OPTION_NOSPLASH) != 0)
                    {
                        nosplash = true;
                    }
                }

            }
            if (showlicensedialog == true)
            {
                frmPluginManager pim = new frmPluginManager();
                pim.ShowDialog();
            }
            try
            {
            #if !DEBUG  // no splash screen under debug release
                if (!nosplash)
                {
                    frmSplash splash = new frmSplash(); // should pull from a licensed plug-in if need-be
                    splash.Show();
                }
            #endif
                Application.Run(new frmMain2());
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex);
            }
        }
        /// <summary>
        /// Loads a model, adds it to the 3d engine to be shown, and raises an app event
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool LoadModel(String filename)
        {
            try
            {
                ModelLoader ml = new ModelLoader();
                if (SceneFileName.Length == 0)
                {
                    SceneFileName = filename; // set it to be the first file loaded
                }
                List <Object3d> objs = ml.Load(filename);
                if (objs != null)
                {
                    foreach (Object3d obj in objs)
                    {
                        obj.CenterOnPlatform();
                        m_engine3d.AddObject(obj);
                        m_undoer.SaveAddition(obj);
                        SelectedObject = obj;
                    }
                    UVDLPApp.Instance().m_engine3d.UpdateLists();
                    m_slicefile = null; // the slice file is not longer current
                    RaiseAppEvent(eAppEvent.eModelAdded, "Model Loaded " + filename);

                    /*
                     * //now try to load the gcode file
                     * String gcodefile = Path.GetFileNameWithoutExtension(filename) + ".gcode";
                     * String gcodepath = SliceFile.GetSliceFilePath(filename);
                     *
                     * String gpath = gcodepath + UVDLPApp.m_pathsep + gcodefile;
                     * if (File.Exists(gpath))
                     * {
                     *  LoadGCode(gpath);
                     * }
                     * else // read the gcode from the zip file
                     * {
                     *  String zpath = gcodepath + ".zip";
                     *  if(File.Exists(zpath)) // make sure the file exists before we try to read it
                     *  {
                     *      Stream s = Utility.ReadFromZip(zpath, gcodefile);
                     *      if(s  != null)
                     *      {
                     *          s.Seek(0, 0); // go to the beginning of the stream
                     *          byte []array = Utility.ReadFully(s);
                     *          string gc = System.Text.Encoding.ASCII.GetString(array);
                     *          m_gcode = new GCodeFile(gc);
                     *          RaiseAppEvent(eAppEvent.eGCodeLoaded, "GCode Loaded " + gcodefile);
                     *      }
                     *      else
                     *      {
                     *          DebugLogger.Instance().LogError("Could not load GCode from Zip " + zpath);
                     *      }
                     *  }
                     *
                     * }
                     * if(m_gcode !=null)
                     * {
                     *  int xres, yres, numslices;
                     *  xres = m_gcode.GetVar("Projector X Res");
                     *  yres = m_gcode.GetVar("Projector Y Res");
                     *  numslices = m_gcode.GetVar("Number of Slices");
                     *  m_slicefile = new SliceFile(xres,yres,numslices);
                     *  m_slicefile.modelname = SelectedObject.m_fullname;
                     *  m_slicefile.m_config = null; //this can be null if we're loading it...
                     *  RaiseAppEvent(eAppEvent.eSlicedLoaded, "SliceFile Created");
                     * }
                     * */
                }
                else
                {
                    RaiseAppEvent(eAppEvent.eModelNotLoaded, "Model " + filename + " Failed to load");
                }

                return(objs != null);
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogRecord(ex.Message);
                return(false);
            }
        }
Exemplo n.º 27
0
        public void DoAppStartup()
        {
            m_dispmgr = DisplayManager.Instance();// initialze the displays
            m_apppath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            //get the path separater
            if (RunningPlatform() == Platform.Windows)
            {
                m_pathsep = "\\";
            }
            else
            {
                m_pathsep = "/";
            }
            // define some default paths
            m_PathMachines = m_apppath + m_pathsep + "Machines";  // use full paths - SHS
            m_PathProfiles = m_apppath + m_pathsep + "Profiles";

            // set up directories if they don't exist
            if (!Directory.Exists(m_PathMachines))
            {
                Utility.CreateDirectory(m_PathMachines);
            }
            if (!Directory.Exists(m_PathProfiles))
            {
                Utility.CreateDirectory(m_PathProfiles);
            }

            if (!m_appconfig.Load(m_apppath + m_pathsep + m_appconfigname))  // use full path - SHS
            {
                m_appconfig.CreateDefault();
                m_appconfig.Save(m_apppath + m_pathsep + m_appconfigname);  // use full path - SHS
            }
            // this will check and make sure the default machines have been created
            CheckAndCreateDefaultMachines();
            //load the current machine configuration file
            if (!m_printerinfo.Load(m_appconfig.m_curmachineeprofilename))
            {
                // m_printerinfo.Save(m_appconfig.m_curmachineeprofilename);
                DebugLogger.Instance().LogError("Cannot Load Machine Profile " + m_appconfig.m_curmachineeprofilename);
            }
            // machine configuration was just loaded here.
            RaiseAppEvent(eAppEvent.eMachineTypeChanged, ""); // notify the gui to set up correctly
            //load the projector command list

            if (!LoadProjectorCommands(m_appconfig.ProjectorCommandsFile))
            {
                SaveProjectorCommands(m_appconfig.ProjectorCommandsFile);
            }
            //load the current slicing profile
            if (!m_buildparms.Load(m_appconfig.m_cursliceprofilename))
            {
                m_buildparms.CreateDefault();
                m_buildparms.Save(m_appconfig.m_cursliceprofilename);
            }
            else
            {
                m_buildparms.CreateDefault();
                m_buildparms.Load(m_appconfig.m_cursliceprofilename);
            }
            // set up the drivers
            SetupDriver();
            //SetupDriverProjector();
            // load the support configuration
            if (!LoadSupportConfig(m_appconfig.SupportConfigName))
            {
                SaveSupportConfig(m_appconfig.SupportConfigName);
            }
            //load the license keys
            LoadLicenseKeys();
            //look for plug-ins and validate licensing
            ScanForPlugins();
            //look for 'lite' plugins
            ScanForPluginsLite();
            // validate those loaded plugins against license keys
            CheckLicensing();
            // initialize the plugins, the main form will send a secondary init after the main app gui is created
            PerformPluginCommand("InitCommand", true);
            m_sc = new ServerContact();
            m_sc.ServerContactEvenet += new ServerContact.Servercontacted(m_sc_ServerContactEvent);

            //contacting Server twise?? commenting this out for now
            //m_sc.UpdateRegInfo();
            m_undoer.RegisterCallback();
            // pack all 2d gl images
            //m_2d_graphics.GenereteUserTexture();


            //load Rsource files

            //this is not good way to load resource files. but the problem is visual studio cant generate auto-generation code for names with dot "."

            resman = new ResourceManager("UV_DLP_3D_Printer.Resource.en", typeof(UVDLPApp).Assembly);
            cul    = CultureInfo.CreateSpecificCulture("");

            if (UVDLPApp.Instance().m_appconfig.m_Selected_Language == "es")
            {
                resman = new ResourceManager("UV_DLP_3D_Printer.Resource.es", typeof(UVDLPApp).Assembly);
                cul    = CultureInfo.CreateSpecificCulture("");
            }
            else if (UVDLPApp.Instance().m_appconfig.m_Selected_Language == "en")
            {
                resman = new ResourceManager("UV_DLP_3D_Printer.Resource.en", typeof(UVDLPApp).Assembly);
                cul    = CultureInfo.CreateSpecificCulture("");
            }
            else
            {
                resman = new ResourceManager("UV_DLP_3D_Printer.Resource.en", typeof(UVDLPApp).Assembly);
                cul    = CultureInfo.CreateSpecificCulture("");
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// This function will immediately return a bitmap slice at the specified Z-Level
        /// </summary>
        /// <param name="zlev"></param>
        /// <returns></returns>
        public Bitmap SliceImmediate(float curz)
        {
            try
            {
                //first take care of scaling up the output bitmap paramters size, so we can re-sample later
                double scaler = 1.5;             // specify the scale factor
                m_saved.CopyFrom(m_sf.m_config); // save the orginal
                if (m_sf.m_config.antialiasing == true)
                {
                    scaler = m_sf.m_config.aaval;
                    m_sf.m_config.dpmmX *= scaler;
                    m_sf.m_config.dpmmY *= scaler;
                    m_sf.m_config.xres   = (int)(scaler * m_sf.m_config.xres);
                    m_sf.m_config.yres   = (int)(scaler * m_sf.m_config.yres);
                }
                SliceBuildConfig sbf = new SliceBuildConfig(m_sf.m_config);          // save it

                Bitmap   bmp   = new Bitmap(m_sf.m_config.xres, m_sf.m_config.yres); // create a new bitmap on a per-slice basis
                Graphics graph = Graphics.FromImage(bmp);
                graph.Clear(UVDLPApp.Instance().m_appconfig.m_backgroundcolor);      //clear the image for rendering

                //convert all to 2d lines
                Bitmap savebm = null;
                // check for cancelation

                foreach (Object3d obj in UVDLPApp.Instance().Engine3D.m_objects)
                {
                    savebm = bmp;                                                             // need to set this here in case it's not rendered
                    if (curz >= obj.m_min.z && curz <= obj.m_max.z)                           // only slice from the bottom to the top of the objects
                    {
                        List <Polygon>    lstply           = GetZPolys(obj, curz);            //get a list of polygons at this slice z height that potentially intersect
                        List <PolyLine3d> lstintersections = GetZIntersections(lstply, curz); //iterate through all the polygons and generate x/y line segments at this 3d z level
                        Slice             sl = new Slice();                                   //create a new slice
                        sl.m_segments = lstintersections;                                     // Set the list of intersections
                        sl.RenderSlice(m_sf.m_config, ref bmp);
                        savebm = bmp;
                    }
                }

                if (m_sf.m_config.antialiasing == true) // we're using anti-aliasing here, so resize the image
                {
                    savebm = ResizeImage(bmp, new Size(m_saved.xres, m_saved.yres));
                }
                if (m_sf.m_config.m_flipX == true)
                {
                    savebm = ReflectX(savebm);
                }
                if (m_sf.m_config.m_flipY == true)
                {
                    savebm = ReflectY(savebm);
                }
                //restore the original size
                m_sf.m_config.CopyFrom(m_saved);
                return(savebm);
            }
            catch (Exception ex)
            {
                string s = ex.StackTrace;
                DebugLogger.Instance().LogRecord(ex.Message);
                return(null);
            }
        }
Exemplo n.º 29
0
        private void slicefunc()
        {
            try
            {
                //first take care of scaling up the output bitmap paramters size, so we can re-sample later
                double scaler = 1.5;             // specify the scale factor
                m_saved.CopyFrom(m_sf.m_config); // save the original
                if (m_sf.m_config.antialiasing == true)
                {
                    scaler = m_sf.m_config.aaval;
                    //  scale them up.
                    m_sf.m_config.dpmmX *= scaler;
                    m_sf.m_config.dpmmY *= scaler;
                    m_sf.m_config.xres   = (int)(m_sf.m_config.xres * scaler);
                    m_sf.m_config.yres   = (int)(m_sf.m_config.yres * scaler);
                }
                else
                {
                    scaler = 1.0; // no scaling
                }

                //determine the number of slices
                //UVDLPApp.Instance().Scene.FindMinMax();

                MinMax mm = UVDLPApp.Instance().Engine3D.CalcSceneExtents();
                //int numslices = (int)((mm.m_max - mm.m_min) / m_sf.m_config.ZThick);
                int numslices = (int)((mm.m_max) / m_sf.m_config.ZThick);
                //int numslices = (int)((UVDLPApp.Instance().Scene.m_max.z) / m_sf.m_config.ZThick);
                // I should start slicing at Wz 0, not Oz 0
                float curz = 0; // start at Wz0

                // an alternative here is to slice the scene from wZ 0, therefore, all object geometry beneath the ground plane won't be slice;
                //double curz = (double)0.0;// start at the ground


                int    c         = 0;
                string scenename = "";
                // a little housework here...
                foreach (Object3d obj in UVDLPApp.Instance().Engine3D.m_objects)
                {
                    obj.CalcMinMaxes();
                    if (c == 0)
                    {
                        //get the first objects' name
                        scenename      = obj.m_fullname;
                        m_sf.modelname = obj.m_fullname;
                    }
                    c++;
                }
                m_sf.NumSlices = numslices;
                SliceStarted(scenename, numslices);
                DebugLogger.Instance().LogRecord("Slicing started");

                if (m_sf.m_config.export == false)
                {
                    // if we're not actually exporting slices right now, then
                    // raise the completed event and exit
                    SliceCompleted(scenename, 0, numslices);
                    m_sf.m_config.CopyFrom(m_saved);
                    isslicing = false;
                    return; // exit slicing, nothing more to do...
                }
                for (c = 0; c < numslices; c++)
                {
                    Bitmap bmp = new Bitmap(m_sf.m_config.xres, m_sf.m_config.yres); // create a new bitmap on a per-slice basis
                    //clear the image for rendering
                    Graphics graph = Graphics.FromImage(bmp);
                    graph.Clear(UVDLPApp.Instance().m_appconfig.m_backgroundcolor);

                    //convert all to 2d lines
                    Bitmap savebm = null;
                    // check for cancelation
                    if (m_cancel)
                    {
                        isslicing = false;
                        m_cancel  = false;
                        //restore the original sizes
                        m_sf.m_config.CopyFrom(m_saved);
                        RaiseSliceEvent(eSliceEvent.eSliceCancelled, c, numslices);
                        return;
                    }

                    foreach (Object3d obj in UVDLPApp.Instance().Engine3D.m_objects)
                    {
                        savebm = bmp;                                   // need to set this here in case it's not rendered
                        if (curz >= obj.m_min.z && curz <= obj.m_max.z) // only slice from the bottom to the top of the objects
                        {
                            //obj.ClearCached();
                            List <Polygon>    lstply           = GetZPolys(obj, curz);            //get a list of polygons at this slice z height that potentially intersect
                            List <PolyLine3d> lstintersections = GetZIntersections(lstply, curz); //iterate through all the polygons and generate x/y line segments at this 3d z level

                            Slice sl = new Slice();                                               //create a new slice
                            sl.m_segments = lstintersections;                                     // Set the list of intersections
                            // m_sf.m_slices.Add(sl);// add the slice to slicefile
                            // now render the slice into the scaled, pre-allocated bitmap
                            sl.RenderSlice(m_sf.m_config, ref bmp);
                            savebm = bmp;
                        }
                    }

                    if (m_sf.m_config.antialiasing == true) // we're using anti-aliasing here, so resize the image
                    {
                        savebm = ResizeImage(bmp, new Size(m_saved.xres, m_saved.yres));
                    }
                    if (m_sf.m_config.m_flipX == true)
                    {
                        savebm = ReflectX(savebm);
                    }
                    if (m_sf.m_config.m_flipY == true)
                    {
                        savebm = ReflectY(savebm);
                    }
                    curz += (float)m_sf.m_config.ZThick;// move the slice for the next layer
                    //raise an event to say we've finished a slice
                    LayerSliced(scenename, c, numslices, savebm);
                }
                // restore the original
                m_sf.m_config.CopyFrom(m_saved);
                SliceCompleted(scenename, c, numslices);
                DebugLogger.Instance().LogRecord("Slicing Completed");
                isslicing = false;
            }
            catch (Exception ex)
            {
                string s = ex.StackTrace;
                DebugLogger.Instance().LogRecord(ex.Message);
                //RaiseSliceEvent(eSliceEvent.eSliceCancelled,0,0);
                m_cancel = true;
            }
        }
        public override string Export(Stream stream, string filename)
        {
            m_stream = stream;
            if ((m_name == null) || (m_name.Length == 0))
            {
                m_name = Path.GetFileNameWithoutExtension(filename);
            }
            if ((m_description == null) || (m_description.Length == 0))
            {
                m_description = m_name;
            }
            try
            {
                ReportStart();
                SliceBuildConfig config = UVDLPApp.Instance().m_buildparms;
                config.UpdateFrom(UVDLPApp.Instance().m_printerinfo); // make sure we've got the correct display size and PixPerMM values

                // write header
                WriteString("1");              // version
                WriteString(m_name);           // scene name
                WriteString(m_description);    // scene description
                WriteDouble(1 / config.dpmmX); // pixel size in mm
                WriteDouble(config.ZThick);    // slice thickness
                WriteInt32(0);                 // base standoff layers (?)
                WriteInt32(0);                 // Number of base offset layers where extents are filled (?)
                WriteString("Reserved3");
                WriteString("Reserved2");
                WriteString("Reserved1");

                // write slices
                int numslices = UVDLPApp.Instance().m_slicer.GetNumberOfSlices(config);
                WriteInt32(numslices);

                float zlev = (float)(config.ZThick * 0.5);
                int   npix = config.xres * config.yres;
                int[] lbm  = new int[npix]; // current slice
                int   p;

                //Bitmap bm = new Bitmap(config.xres, config.yres, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // working bitmap
                //Color savecol = UVDLPApp.Instance().m_appconfig.m_foregroundcolor;

                if (UVDLPApp.Instance().m_slicer.SliceFile == null)
                {
                    SliceFile sf = new SliceFile(config);
                    sf.m_mode = SliceFile.SFMode.eImmediate;
                    UVDLPApp.Instance().m_slicer.SliceFile = sf; // wasn't set
                }

                for (int c = 0; c < numslices; c++)
                {
                    //bool layerneedssupport = false;
                    if (CancelExport)
                    {
                        return("Info|Export operation canceled");
                    }
                    ReportProgress(c * 100 / numslices);

                    /*Slice sl = UVDLPApp.Instance().m_slicer.GetSliceImmediate(zlev);
                     * zlev += (float)config.ZThick;
                     *
                     * if ((sl == null) || (sl.m_segments == null) || (sl.m_segments.Count == 0))
                     *  continue;
                     * sl.Optimize();// find loops
                     * using (Graphics gfx = Graphics.FromImage(bm))
                     *  gfx.Clear(Color.Transparent);
                     *
                     * //render current slice
                     * UVDLPApp.Instance().m_appconfig.m_foregroundcolor = Color.White;
                     * sl.RenderSlice(config, ref bm);*/

                    Bitmap bm = UVDLPApp.Instance().m_slicer.SliceImmediate(zlev);
                    zlev += (float)config.ZThick;
                    BitmapData data = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height),
                                                  ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                    Marshal.Copy(data.Scan0, lbm, 0, lbm.Length);
                    for (p = 0; p < npix; p++)
                    {
                        lbm[p] &= 0xFFFFFF;
                    }
                    bm.UnlockBits(data);
                    CrushSlice(lbm, config.xres, config.yres);
                }

                // write supports (currently not handled)
                WriteInt32(0); // zero supports
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex);
                return("Error|Export terminated unexpectedly");
            }

            return("Export|Export completed successfully");
        }