Пример #1
0
        public DCTreeNode CreateNewNodeComponent(DCTreeNode parentNode, string name, string description, DCThumbnail thumb
                                                 , DCFile compFile, Guid compGuid, DCMajorationSet[] majorationSets, DCParamDefaultValue[] defaultValues)
        {
            try
            {
                PLMPackEntities db0         = new PLMPackEntities();
                AspNetUser      user        = AspNetUser.GetByUserName(db0, UserName);
                TreeNode        tnParent    = TreeNode.GetById(db0, parentNode.ID);
                TreeNode        tnComponent = tnParent.InsertComponent(
                    db0, user.GroupId,
                    name, description,
                    compFile.Guid, compGuid,
                    Thumbnail.GetByID(db0, thumb.ID));

                // retrieve component
                PLMPackEntities db1  = new PLMPackEntities();
                Component       comp = Component.GetByGuid(db1, compGuid);

                // insert default parameter values
                foreach (DCParamDefaultValue pdv in defaultValues)
                {
                    comp.InsertParamDefaultValue(db1, user.GroupId, pdv.Name, pdv.Value);
                }

                // set majoration set
                foreach (DCMajorationSet mjset in majorationSets)
                {
                    CardboardProfile            cp = CardboardProfile.GetByID(db0, mjset.Profile.ID);
                    Dictionary <string, double> dictMajorations = new Dictionary <string, double>();
                    foreach (DCMajoration maj in mjset.Majorations)
                    {
                        dictMajorations[maj.Name] = maj.Value;
                    }
                    comp.UpdateMajorationSet(db1, cp, dictMajorations);
                }
                return(Db_2_DCTreeNode(db1, user, tnComponent));
            }
            catch (Exception ex)
            {
                string message = ex.ToString();
                throw ex;
            }
        }
Пример #2
0
  private void UpdateScreenDataFromActivity() {
    CardboardProfile.Device device = new CardboardProfile.Device();
    CardboardProfile.Screen screen = new CardboardProfile.Screen();

    float[] lensData = null;
    if (CallActivityMethod(ref lensData, "getLensParameters")) {
      device.lenses.separation = lensData[0];
      device.lenses.offset = lensData[1];
      device.lenses.screenDistance = lensData[2];
      device.lenses.alignment = (int)lensData[3];
    }

    float[] screenSize = null;
    if (CallActivityMethod(ref screenSize, "getScreenSizeMeters")) {
      screen.width = screenSize[0];
      screen.height = screenSize[1];
      screen.border = screenSize[2];
    }

    float[] distCoeff = null;
    if (CallActivityMethod(ref distCoeff, "getDistortionCoefficients")) {
      device.distortion.k1 = distCoeff[0];
      device.distortion.k2 = distCoeff[1];
    }

    float[] invDistCoeff = null;
    if (CallActivityMethod(ref invDistCoeff, "getInverseDistortionCoefficients")) {
      device.inverse.k1 = invDistCoeff[0];
      device.inverse.k2 = invDistCoeff[1];

    }

    float[] maxFov = null;
    if (CallActivityMethod(ref maxFov, "getLeftEyeMaximumFOV")) {
      device.maxFOV.outer = maxFov[0];
      device.maxFOV.upper = maxFov[1];
      device.maxFOV.inner = maxFov[2];
      device.maxFOV.lower = maxFov[3];
    }

    Profile = new CardboardProfile { screen=screen, device=device };
  }
Пример #3
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            try
            {
                PLMPackLibDb db = new PLMPackLibDb();
                #region Cardboad formats
                // create formats
                CardboardFormat cbf = null;
                if (!CardboardFormat.Exists(db, "F1"))
                {
                    cbf = CardboardFormat.CreateNew(db, "F1", "Form1", 1000.0f, 1000.0f);
                }
                if (!CardboardFormat.Exists(db, "F2"))
                {
                    cbf = CardboardFormat.CreateNew(db, "F2", "Form2", 2000.0f, 2000.0f);
                }
                if (!CardboardFormat.Exists(db, "F3"))
                {
                    cbf = CardboardFormat.CreateNew(db, "F3", "Form3", 3000.0f, 3000.0f);
                }
                // get list of formats
                foreach (CardboardFormat f in CardboardFormat.GetAll(db))
                {
                    _log.Info(f.ToString());
                }
                #endregion

                #region Cardboard profile
                CardboardProfile cbp = null;
                if (!CardboardProfile.Exists(db, "P1"))
                {
                    cbp = CardboardProfile.CreateNew(db, "P1", "Profile 1", 1.0f);
                }
                #endregion
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
Пример #4
0
        protected override Dictionary <string, double> LoadMajorationList()
        {
            if (null == Selected || null == _comp)
            {
                return(new Dictionary <string, double>());
            }
            if (null == _dictMajoration)
            {
                PPDataContext db = new PPDataContext();

                CardboardProfile selectedProfile = CardboardProfile.GetByName(db, _selectedProfile.Name);
                _dictMajoration = Pic.DAL.SQLite.Component.GetDefaultMajorations(
                    db,
                    _comp.ID,
                    selectedProfile,
                    // rounding to be applied while building majoration dictionary
                    Pic.DAL.SQLite.Component.IntToMajoRounding(Properties.Settings.Default.MajorationRounding)
                    );
            }
            return(_dictMajoration);
        }
 public static void MergeCardboardProfiles(PPDataContext dbFrom, PPDataContext dbTo, IProcessingCallback callback)
 {
     foreach (CardboardProfile cp in dbFrom.CardboardProfiles)
     {
         if (CardboardProfile.HasByName(dbTo, cp.Name))
         {
             if (null != callback)
             {
                 callback.Info(string.Format("Cardboard profile {0} already exists. Skipping...", cp.Name));
             }
         }
         else
         {
             if (null != callback)
             {
                 callback.Info(string.Format("Creating carboard profile {0}...", cp.Name));
             }
             CardboardProfile.CreateNew(dbTo, cp.Name, cp.Code, cp.Thickness);
         }
     }
 }
Пример #6
0
        public DCMajorationSet UpdateMajorationSet(Guid g, DCMajorationSet majorationSet)
        {
            PLMPackEntities  db   = new PLMPackEntities();
            AspNetUser       user = AspNetUser.GetByUserName(db, UserName);
            CardboardProfile cp   = CardboardProfile.GetByID(db, majorationSet.Profile.ID);
            Component        comp = Component.GetByGuid(db, g);

            Dictionary <string, double> dict = new Dictionary <string, double>();

            foreach (DCMajoration maj in majorationSet.Majorations)
            {
                dict.Add(maj.Name, maj.Value);
            }
            comp.UpdateMajorationSet(db, cp, dict);
            // retrieve majoration set
            Dictionary <string, double> dictOut = comp.GetMajorationSet(db, cp);

            DCMajorationSet majoSetOut = new DCMajorationSet()
            {
                Profile = new DCCardboardProfile()
                {
                    ID          = cp.Id,
                    Name        = cp.Name,
                    Description = cp.Description,
                    Code        = cp.Code,
                    Thickness   = cp.Thickness
                },
                Majorations = new DCMajoration[dictOut.Count]
            };
            int iCount = 0;

            foreach (KeyValuePair <string, double> v in dictOut)
            {
                majoSetOut.Majorations[iCount] = new DCMajoration()
                {
                    Name = v.Key, Value = v.Value
                }; ++iCount;
            }
            return(majoSetOut);
        }
Пример #7
0
 private void UpdateProfile()
 {
     GetProfile(profileData);
     CardboardProfile.Device device = new CardboardProfile.Device();
     CardboardProfile.Screen screen = new CardboardProfile.Screen();
     device.maxFOV.outer          = profileData[0];
     device.maxFOV.upper          = profileData[1];
     device.maxFOV.inner          = profileData[2];
     device.maxFOV.lower          = profileData[3];
     screen.width                 = profileData[4];
     screen.height                = profileData[5];
     screen.border                = profileData[6];
     device.lenses.separation     = profileData[7];
     device.lenses.offset         = profileData[8];
     device.lenses.screenDistance = profileData[9];
     device.lenses.alignment      = (int)profileData[10];
     device.distortion.k1         = profileData[11];
     device.distortion.k2         = profileData[12];
     device.inverse               = CardboardProfile.ApproximateInverse(device.distortion);
     Profile.screen               = screen;
     Profile.device               = device;
 }
        private void FormCreateDocument_Load(object sender, EventArgs e)
        {
            textBoxName.TextChanged        += new EventHandler(textBox_TextChanged);
            textBoxDescription.TextChanged += new EventHandler(textBox_TextChanged);
            fileSelectCtrl.FileNameChanged += new EventHandler(textBox_TextChanged);
            // file select control
            fileSelectCtrl.Filter = "Plugin file (*.dll)|*.dll";
            // initialize profile combo box
            comboBoxProfile.Items.Clear();
            List <CardboardProfile> listProfile = CardboardProfile.getAll();

            foreach (CardboardProfile profile in listProfile)
            {
                comboBoxProfile.Items.Add(profile);
            }
            if (comboBoxProfile.Items.Count > 0)
            {
                comboBoxProfile.SelectedIndex = 0;
            }
            // disable Ok button
            bnOk.Enabled = false;
        }
Пример #9
0
        private void FillListView()
        {
            try
            {
                // clear all existing items
                listViewProfile.Items.Clear();

                PPDataContext      db = new PPDataContext();
                CardboardProfile[] cardboardProfiles = CardboardProfile.GetAll(db);
                foreach (Pic.DAL.SQLite.CardboardProfile profile in cardboardProfiles)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = profile.Name;
                    item.SubItems.Add(profile.Code);
                    item.SubItems.Add(string.Format("{0}", profile.Thickness));
                    listViewProfile.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.ToString());
                _log.Debug(ex.ToString());
            }
        }
Пример #10
0
 private void UpdateSimulatedScreenData()
 {
     Profile = CardboardProfile.GetKnownProfile(screenSize, deviceType);
     ComputeEyesFromProfile();
 }
Пример #11
0
 public override void UpdateScreenData()
 {
     Profile = CardboardProfile.GetKnownProfile(Cardboard.SDK.ScreenSize, Cardboard.SDK.DeviceType);
     ComputeEyesFromProfile();
     profileChanged = true;
 }
Пример #12
0
    private void Setup()
    {
        // Shouldn't happen because of the check in Start(), but just in case...
        if (controller == null)
        {
            return;
        }

        var       monoCamera = controller.GetComponent <Camera>();
        Matrix4x4 proj       = Cardboard.SDK.Projection(eye);

        CopyCameraAndMakeSideBySide(controller, proj[0, 2], proj[1, 2]);

        // Zoom the stereo cameras if requested.
        float lerp = Mathf.Clamp01(controller.matchByZoom) * Mathf.Clamp01(controller.matchMonoFOV);
        // Lerping the reciprocal of proj(1,1) so zooming is linear in the frustum width, not the depth.
        float monoProj11 = monoCamera.projectionMatrix[1, 1];
        float zoom       = 2 / Mathf.Lerp(1 / proj[1, 1], 1 / monoProj11, lerp) / proj[1, 1];

        proj[0, 0] *= zoom;
        proj[1, 1] *= zoom;

        // Calculate stereo adjustments based on the center of interest.
        float ipdScale;
        float eyeOffset;

        controller.ComputeStereoAdjustment(proj[1, 1], transform.lossyScale.z,
                                           out ipdScale, out eyeOffset);

        // Set up the eye's view transform.
        transform.localPosition = ipdScale * Cardboard.SDK.EyePose(eye).Position +
                                  eyeOffset * Vector3.forward;

        // Set up the eye's projection.
        float near = monoCamera.nearClipPlane;
        float far  = monoCamera.farClipPlane;

        FixProjection(ref proj, near, far, ipdScale);
        camera.projectionMatrix = proj;

        if (Application.isEditor)
        {
            // So you can see the approximate frustum in the Scene view when the camera is selected.
            camera.fieldOfView = 2 * Mathf.Atan(1 / proj[1, 1]) * Mathf.Rad2Deg;
        }

        Vuforia.VuforiaBehaviour.Instance.ApplyCorrectedProjectionMatrix(proj, eye == Cardboard.Eye.Left);

        // Set up variables for an image effect that will do distortion correction, e.g. the
        // RadialDistortionEffect.  Note that native distortion correction should take precedence
        // over an image effect, so if that is active then we don't need to compute these variables.
        // (Exception: we're in the editor, so we use the image effect to preview the distortion
        // correction, because native distortion correction only works on the phone.)
        if (Cardboard.SDK.UseDistortionEffect)
        {
            Matrix4x4 realProj = Cardboard.SDK.Projection(eye, Cardboard.Distortion.Undistorted);
            FixProjection(ref realProj, near, far, ipdScale);
            // Parts of the projection matrices that we need to convert texture coordinates between
            // distorted and undistorted frustums.  Include the transform between texture space [0..1]
            // and NDC [-1..1] (that's what the -1 and the /2 are for).  Also note that the zoom
            // factor is removed, because that will interfere with the distortion calculation.
            Vector4 projvec = new Vector4(proj[0, 0] / zoom, proj[1, 1] / zoom,
                                          proj[0, 2] - 1, proj[1, 2] - 1) / 2;
            Vector4 unprojvec = new Vector4(realProj[0, 0], realProj[1, 1],
                                            realProj[0, 2] - 1, realProj[1, 2] - 1) / 2;
            Shader.SetGlobalVector("_Projection", projvec);
            Shader.SetGlobalVector("_Unprojection", unprojvec);
            CardboardProfile p = Cardboard.SDK.Profile;
            Shader.SetGlobalVector("_Undistortion",
                                   new Vector4(p.device.inverse.k1, p.device.inverse.k2));
            Shader.SetGlobalVector("_Distortion",
                                   new Vector4(p.device.distortion.k1, p.device.distortion.k2));
        }

        if (controller.StereoScreen == null)
        {
            Rect rect = camera.rect;
            if (!Cardboard.SDK.DistortionCorrection ||
                Cardboard.SDK.UseDistortionEffect)
            {
                // We are rendering straight to the screen.  Use the reported rect that is visible
                // through the device's lenses.
                Rect view = Cardboard.SDK.Viewport(eye);
                if (eye == Cardboard.Eye.Right)
                {
                    rect.x -= 0.5f;
                }
                rect.width  *= 2 * view.width;
                rect.x       = view.x + 2 * rect.x * view.width;
                rect.height *= view.height;
                rect.y       = view.y + rect.y * view.height;
            }
            if (Application.isEditor)
            {
                // The Game window's aspect ratio may not match the fake device parameters.
                float realAspect       = (float)Screen.width / Screen.height;
                float fakeAspect       = Cardboard.SDK.Profile.screen.width / Cardboard.SDK.Profile.screen.height;
                float aspectComparison = fakeAspect / realAspect;
                if (aspectComparison < 1)
                {
                    rect.width *= aspectComparison;
                    rect.x     *= aspectComparison;
                    rect.x     += (1 - aspectComparison) / 2;
                }
                else
                {
                    rect.height /= aspectComparison;
                }
            }
            camera.rect = rect;
        }
    }
    private static void ComputeMeshPoints(int width, int height, bool distortVertices,
                                          out Vector3[] vertices, out Vector2[] tex)
    {
        float[]          lensFrustum   = new float[4];
        float[]          noLensFrustum = new float[4];
        Rect             viewport;
        CardboardProfile profile = Cardboard.SDK.Profile;

        profile.GetLeftEyeVisibleTanAngles(lensFrustum);
        profile.GetLeftEyeNoLensTanAngles(noLensFrustum);
        viewport = profile.GetLeftEyeVisibleScreenRect(noLensFrustum);
        vertices = new Vector3[2 * width * height];
        tex      = new Vector2[2 * width * height];
        for (int e = 0, vidx = 0; e < 2; e++)
        {
            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++, vidx++)
                {
                    float u = (float)i / (width - 1);
                    float v = (float)j / (height - 1);
                    float s, t; // The texture coordinates in StereoScreen to read from.
                    if (distortVertices)
                    {
                        // Grid points regularly spaced in StreoScreen, and barrel distorted in the mesh.
                        s = u;
                        t = v;
                        float x = Mathf.Lerp(lensFrustum[0], lensFrustum[2], u);
                        float y = Mathf.Lerp(lensFrustum[3], lensFrustum[1], v);
                        float d = Mathf.Sqrt(x * x + y * y);
                        float r = profile.device.distortion.distortInv(d);
                        float p = x * r / d;
                        float q = y * r / d;
                        u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
                        v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
                    }
                    else
                    {
                        // Grid points regularly spaced in the mesh, and pincushion distorted in
                        // StereoScreen.
                        float p = Mathf.Lerp(noLensFrustum[0], noLensFrustum[2], u);
                        float q = Mathf.Lerp(noLensFrustum[3], noLensFrustum[1], v);
                        float r = Mathf.Sqrt(p * p + q * q);
                        float d = profile.device.distortion.distort(r);
                        float x = p * d / r;
                        float y = q * d / r;
                        s = Mathf.Clamp01((x - lensFrustum[0]) / (lensFrustum[2] - lensFrustum[0]));
                        t = Mathf.Clamp01((y - lensFrustum[3]) / (lensFrustum[1] - lensFrustum[3]));
                    }
                    // Convert u,v to mesh screen coordinates.
                    float aspect = profile.screen.width / profile.screen.height;
                    u = (viewport.x + u * viewport.width - 0.5f) * aspect;
                    v = viewport.y + v * viewport.height - 0.5f;
                    vertices[vidx] = new Vector3(u, v, 1);
                    // Adjust s to account for left/right split in StereoScreen.
                    s         = (s + e) / 2;
                    tex[vidx] = new Vector2(s, t);
                }
            }
            float w = lensFrustum[2] - lensFrustum[0];
            lensFrustum[0] = -(w + lensFrustum[0]);
            lensFrustum[2] = w - lensFrustum[2];
            w = noLensFrustum[2] - noLensFrustum[0];
            noLensFrustum[0] = -(w + noLensFrustum[0]);
            noLensFrustum[2] = w - noLensFrustum[2];
            viewport.x       = 1 - (viewport.x + viewport.width);
        }
    }
Пример #14
0
    public void Render()
    {
        // Shouldn't happen because of the check in Start(), but just in case...
        if (controller == null)
        {
            return;
        }

        var       camera     = GetComponent <Camera>();
        var       monoCamera = controller.GetComponent <Camera>();
        Matrix4x4 proj       = Cardboard.SDK.Projection(eye);

        CopyCameraAndMakeSideBySide(controller, proj[0, 2], proj[1, 2]);

        // Zoom the stereo cameras if requested.
        float lerp = Mathf.Clamp01(controller.matchByZoom) * Mathf.Clamp01(controller.matchMonoFOV);
        // Lerping the reciprocal of proj(1,1) so zooming is linear in the frustum width, not the depth.
        float monoProj11 = monoCamera.projectionMatrix[1, 1];
        float zoom       = 1 / Mathf.Lerp(1 / proj[1, 1], 1 / monoProj11, lerp) / proj[1, 1];

        proj[0, 0] *= zoom;
        proj[1, 1] *= zoom;

        // Calculate stereo adjustments based on the center of interest.
        float ipdScale;
        float eyeOffset;

        controller.ComputeStereoAdjustment(proj[1, 1], transform.lossyScale.z,
                                           out ipdScale, out eyeOffset);

        // Set up the eye's view transform.
        transform.localPosition = ipdScale * Cardboard.SDK.EyeOffset(eye) +
                                  eyeOffset * Vector3.forward;

        // Set up the eye's projection.
        float near = monoCamera.nearClipPlane;
        float far  = monoCamera.farClipPlane;

        FixProjection(ref proj, near, far, ipdScale);
        camera.projectionMatrix = proj;

        if (Application.isEditor)
        {
            // So you can see the approximate frustum in the Scene view when the camera is selected.
            camera.fieldOfView = 2 * Mathf.Atan(1 / proj[1, 1]) * Mathf.Rad2Deg;
        }

        if (!Cardboard.SDK.nativeDistortionCorrection)
        {
            Matrix4x4 realProj = Cardboard.SDK.UndistortedProjection(eye);
            FixProjection(ref realProj, near, far, ipdScale);
            // Parts of the projection matrices that we need to convert texture coordinates between
            // distorted and undistorted frustums.  Include the transform between texture space [0..1]
            // and NDC [-1..1] (that's what the -1 and the /2 are for).  Also note that the zoom
            // factor is removed, because that will interfere with the distortion calculation.
            Vector4 projvec = new Vector4(proj[0, 0] / zoom, proj[1, 1] / zoom,
                                          proj[0, 2] - 1, proj[1, 2] - 1) / 2;
            Vector4 unprojvec = new Vector4(realProj[0, 0], realProj[1, 1],
                                            realProj[0, 2] - 1, realProj[1, 2] - 1) / 2;
            Shader.SetGlobalVector("_Projection", projvec);
            Shader.SetGlobalVector("_Unprojection", unprojvec);
            CardboardProfile p = Cardboard.SDK.Profile;
            Shader.SetGlobalVector("_Undistortion",
                                   new Vector4(p.device.inverse.k1, p.device.inverse.k2));
            Shader.SetGlobalVector("_Distortion",
                                   new Vector4(p.device.distortion.k1, p.device.distortion.k2));
        }

        RenderTexture stereoScreen = controller.StereoScreen;
        int           screenWidth  = stereoScreen ? stereoScreen.width : Screen.width;
        int           screenHeight = stereoScreen ? stereoScreen.height : Screen.height;

        if (stereoScreen == null)
        {
            // We are rendering straight to the screen.  Use the reported rect that is visible
            // through the device's lenses.
            Rect view = Cardboard.SDK.EyeRect(eye);
            Rect rect = camera.rect;
            if (eye == Cardboard.Eye.Right)
            {
                rect.x -= 0.5f;
            }
            rect.width  *= 2 * view.width;
            rect.x       = view.x + 2 * rect.x * view.width;
            rect.height *= view.height;
            rect.y       = view.y + rect.y * view.height;
            if (Application.isEditor)
            {
                // The Game window's aspect ratio may not match the fake device parameters.
                float realAspect       = (float)screenWidth / screenHeight;
                float fakeAspect       = Cardboard.SDK.Profile.screen.width / Cardboard.SDK.Profile.screen.height;
                float aspectComparison = fakeAspect / realAspect;
                if (aspectComparison < 1)
                {
                    rect.width *= aspectComparison;
                    rect.x     *= aspectComparison;
                    rect.x     += (1 - aspectComparison) / 2;
                }
                else
                {
                    rect.height /= aspectComparison;
                }
            }
            camera.rect = rect;
        }

        // Use the "fast" or "slow" method.  Fast means the camera draws right into one half of
        // the stereo screen.  Slow means it draws first to a side buffer, and then the buffer
        // is written to the screen. The slow method is provided because a lot of Image Effects
        // don't work if you draw to only part of the window.
        if (controller.directRender)
        {
            // Redirect to our stereo screen.
            camera.targetTexture = stereoScreen;
            // Draw!
            camera.Render();
        }
        else
        {
            // Save the viewport rectangle and reset to "full screen".
            Rect pixRect = camera.pixelRect;
            camera.rect = new Rect(0, 0, 1, 1);
            // Redirect to a temporary texture.  The defaults are supposedly Android-friendly.
            int depth = stereoScreen ? stereoScreen.depth : 16;
            RenderTextureFormat format = stereoScreen ? stereoScreen.format : RenderTextureFormat.RGB565;
            camera.targetTexture = RenderTexture.GetTemporary((int)pixRect.width, (int)pixRect.height,
                                                              depth, format);
            // Draw!
            camera.Render();
            // Blit the temp texture to the stereo screen.
            RenderTexture oldTarget = RenderTexture.active;
            RenderTexture.active = stereoScreen;
            GL.PushMatrix();
            GL.LoadPixelMatrix(0, screenWidth, screenHeight, 0);
            // Camera rects are in screen coordinates (bottom left is origin), but DrawTexture takes a
            // rect in GUI coordinates (top left is origin).
            Rect blitRect = pixRect;
            blitRect.y = screenHeight - pixRect.height - pixRect.y;
            // Blit!
            Graphics.DrawTexture(blitRect, camera.targetTexture);
            // Clean up.
            GL.PopMatrix();
            RenderTexture.active = oldTarget;
            RenderTexture.ReleaseTemporary(camera.targetTexture);
        }
        camera.targetTexture = null;
    }
        public static void MergeTreeNodesRecursively(PPDataContext dbFrom, PPDataContext dbTo, TreeNode nodeFrom, TreeNode nodeTo, IProcessingCallback callback)
        {
            if (null != callback && !nodeFrom.IsDocument)
            {
                callback.Info(string.Format("Processing branch {0}", nodeFrom.Name));
            }

            // get thumbnail path of node to insert
            string thumbnailPath = nodeFrom.Thumbnail.File.Path(dbFrom);

            // handle childrens
            foreach (TreeNode childFrom in nodeFrom.Childrens(dbFrom))
            {
                // get thumbnail of node to insert
                thumbnailPath = childFrom.Thumbnail.File.Path(dbFrom);

                if (childFrom.IsDocument)
                {
                    Document docFrom     = childFrom.Documents(dbFrom)[0];
                    string   docTypeName = docFrom.DocumentType.Name;

                    if (nodeTo.HasChild(dbTo, childFrom.Name))
                    {
                        if (null != callback)
                        {
                            callback.Info(string.Format("Document {0} already exists...", childFrom.Name));
                        }
                    }
                    else
                    {
                        if (string.Equals("Parametric component", docTypeName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            if (null != callback)
                            {
                                callback.Info(string.Format("Parametric component {0} already exists...", childFrom.Name));
                            }
                            // insert as component
                            Component compFrom = docFrom.Components[0];
                            Component compTo   = Component.GetByGuid(dbTo, compFrom.Guid);
                            if (null == compTo)
                            {
                                if (null != callback)
                                {
                                    callback.Info(string.Format("Inserting component {0}...", childFrom.Name));
                                }
                                compTo = nodeTo.InsertComponent(dbTo, docFrom.File.Path(dbFrom), compFrom.Guid, childFrom.Name, childFrom.Description, thumbnailPath);

                                // parameter default values
                                Dictionary <string, double> dictNameValues = compFrom.GetParamDefaultValues();
                                if (dictNameValues.Count > 0)
                                {
                                    if (null != callback)
                                    {
                                        string sParameters = string.Empty;
                                        foreach (string defParamName in dictNameValues.Keys)
                                        {
                                            StringBuilder sb = new StringBuilder();
                                            sb.Append(defParamName);
                                            sb.Append("=");
                                            sb.Append(dictNameValues[defParamName]);
                                            sb.Append(", ");
                                            sParameters += sb.ToString();
                                        }
                                        sParameters.Trim();
                                        sParameters.Trim(',');
                                        callback.Info(string.Format("Default parameter values : {0}", sParameters));
                                    }
                                    compTo.InsertNewParamDefaultValues(dbTo, dictNameValues);
                                }
                                // majorations
                                foreach (MajorationSet mjset in compFrom.MajorationSets)
                                {
                                    // retrieve profile
                                    string           profileName = mjset.CardboardProfile.Name;
                                    CardboardProfile profileTo   = CardboardProfile.GetByName(dbTo, profileName);
                                    if (null == profileTo)
                                    {
                                        if (null != callback)
                                        {
                                            callback.Error(string.Format("Failed to retrieve profile {0}", mjset.CardboardProfile.Name));
                                        }
                                        continue;
                                    }
                                    // get majorations
                                    Dictionary <string, double> majorations = new Dictionary <string, double>();
                                    string sMajo = string.Format("prof = {0} -> ", profileName);
                                    foreach (Majoration mj in mjset.Majorations)
                                    {
                                        majorations.Add(mj.Name, mj.Value);
                                        sMajo += string.Format("{0}={1}, ", mj.Name, mj.Value);
                                    }
                                    // insert
                                    if (null != callback)
                                    {
                                        callback.Info(sMajo);
                                    }
                                    compTo.InsertNewMajorationSet(dbTo, profileTo.Name, majorations);
                                }
                            }
                            else
                            {
                                if (null != callback)
                                {
                                    callback.Info(string.Format("Component with GUID {0} already exists...", compFrom.Guid));
                                }
                            }
                        }
                        else
                        {
                            if (null != callback)
                            {
                                callback.Info(string.Format("Inserting document {0}...", childFrom.Name));
                            }
                            // insert as document
                            nodeTo.InsertDocument(dbTo, docFrom.File.Path(dbFrom), childFrom.Name, childFrom.Description, docTypeName, thumbnailPath);
                        }
                    }
                }
                else
                {
                    TreeNode childTo = null;
                    if (nodeTo.HasChild(dbTo, childFrom.Name))
                    {
                        if (null != callback)
                        {
                            callback.Info(string.Format("Branch {0} already exists.Skipping...", childFrom.Name));
                        }
                        childTo = nodeTo.GetChild(dbTo, childFrom.Name);
                    }
                    else
                    {
                        if (null != callback)
                        {
                            callback.Info(string.Format("Inserting branch {0}...", childFrom.Name));
                        }
                        childTo = nodeTo.CreateChild(dbTo, childFrom.Name, childFrom.Description, thumbnailPath);
                    }
                    MergeTreeNodesRecursively(dbFrom, dbTo, childFrom, childTo, callback);
                }
            }
        }
        static void Main(string[] args)
        {
            // set up a simple configuration that logs on the console.
            XmlConfigurator.Configure();

            bool deleteAll = true;

            try
            {
                // ================================ CardboardFormat
                try
                {
                    PPDataContext   db   = new PPDataContext();
                    CardboardFormat cbf1 = CardboardFormat.CreateNew(db, "F1", "Format 1", 1000.0f, 1000.0f);
                    _log.Info(string.Format("Created new cardboard format with Id = {0}", cbf1.ID));
                    CardboardFormat cbf2 = CardboardFormat.CreateNew(db, "F2", "Format 2", 2000.0f, 2000.0f);
                    _log.Info(string.Format("Created new cardboard format with Id = {0}", cbf2.ID));
                    CardboardFormat cbf3 = CardboardFormat.CreateNew(db, "F3", "Format 3", 3000.0f, 3000.0f);
                    _log.Info(string.Format("Created new cardboard format with Id = {0}", cbf3.ID));

                    foreach (CardboardFormat cbf in CardboardFormat.GetAll(db))
                    {
                        _log.Info(cbf.ToString());
                    }
                }
                catch (System.Exception ex) { _log.Error(ex.Message); }
                // ================================
                // ================================ CardboardProfile
                // get list of existing cardboards
                try
                {
                    PPDataContext db = new PPDataContext();
                    IEnumerable <CardboardProfile> profiles = from cp in db.CardboardProfiles select cp;
                    foreach (CardboardProfile cbp in profiles)
                    {
                        _log.Info(cbp.ToString());
                    }
                    db.Dispose();
                }
                catch (System.Exception ex) { _log.Error(ex.Message); }
                // add first CardboardProfile ->expected to throw exception if already exists
                try
                {
                    PPDataContext    db         = new PPDataContext();
                    CardboardProfile cbprofile1 = CardboardProfile.CreateNew(db, "Profile1", "P1", 0.1f);
                    _log.Info(string.Format("created cardboard profile with Id = {0}", cbprofile1.ID));
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }
                // add second CardboardProfile
                try
                {
                    PPDataContext    db         = new PPDataContext();
                    CardboardProfile cbprofile2 = CardboardProfile.CreateNew(db, "Profile2", "P2", 0.2f);
                    _log.Info(string.Format("created cardboard profile with Id = {0}", cbprofile2.ID));
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }
                // delete CardboardProfile
                {
                    PPDataContext    db      = new PPDataContext();
                    CardboardProfile profile = db.CardboardProfiles.Single <CardboardProfile>(cp => cp.Code == "P2");
                    db.CardboardProfiles.DeleteOnSubmit(profile);
                    db.SubmitChanges();
                }
                // ================================
                // ================================ DocumentType
                // add new DocumentType
                try
                {
                    PPDataContext db      = new PPDataContext();
                    DocumentType  docType = DocumentType.CreateNew(db, "Parametric component", "Parametric component to be used in PicParam", "PicParam");
                    _log.Info(string.Format("created document type with Id = {0}", docType.ID));
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }

                // ================================
                // ================================ TreeNode
                // create new rootNodes
                string imageFilePath = string.Empty;
                try
                {
                    PPDataContext db        = new PPDataContext();
                    TreeNode      rootNode1 = TreeNode.CreateNew(db, "Parametric components", "Parametric component to be used in PicParam", imageFilePath);
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }

                try
                {
                    PPDataContext db        = new PPDataContext();
                    TreeNode      rootNode2 = TreeNode.CreateNew(db, "Drawing files", "Either PicGEOM or Autocad dxf files", imageFilePath);
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }

                // create new child treenode
                try
                {
                    PPDataContext db         = new PPDataContext();
                    TreeNode      parentNode = TreeNode.GetRootNodes(db)[0];
                    TreeNode      childNode1 = parentNode.CreateChild(db, "Node1", "Node1", imageFilePath);
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }

                Guid guidComponent = Guid.Empty;

                // ================================
                // ================================ Component
                // create new child node + component
                try
                {
                    PPDataContext db         = new PPDataContext();
                    TreeNode      parentNode = TreeNode.GetRootNodes(db)[0];
                    TreeNode      childNode1 = parentNode.Childrens(db)[0];
                    TreeNode      childNode2 = null;
                    try
                    {
                        childNode2 = childNode1.CreateChild(db, "Node2", "Node2", imageFilePath);
                        _log.Info(string.Format("successfully created Node with ID = {0}", childNode2.ID));
                    }
                    catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                    if (null == childNode2)
                    {
                        childNode2 = childNode1.Childrens(db)[0];
                    }
                    // insert component
                    string    filePath  = @"K:\Codesion\PicSharp\Pic.Plugin.SimpleRectangle\bin\Release\Pic.Plugin.SimpleRectangle.dll";
                    Component component = childNode2.InsertComponent(db, filePath, Guid.NewGuid(), "Rounded rectangle", "Rounded rectangle", "");
                    guidComponent = component.Guid;
                    // set majorations
                    Dictionary <string, double> majorations = new Dictionary <string, double>();
                    majorations.Add("m1", 1.0);
                    majorations.Add("m2", 2.0);
                    component.InsertNewMajorationSet(db, "Profile1", majorations);
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }
                // ================================
                // ================================ Document
                // create documents
                try
                {
                    PPDataContext db         = new PPDataContext();
                    TreeNode      parentNode = TreeNode.GetRootNodes(db)[0];
                    string        filePath   = @"K:\SVN Projects\PicSharp\Pic.Plugin.SimpleRectangle\bin\Release\Pic.Plugin.SimpleRectangle.dll";
                    parentNode.InsertDocument(db, filePath, "Rounded rectangle", "Rounded Rectangle", "Parametric component", "");
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }

                // ================================
                // ================================ TreeBuilder
                // show document tree
                TreeBuilder builder     = new TreeBuilder();
                TreeConsole treeConsole = new TreeConsole();
                builder.BuildTree(treeConsole);
                // ================================
                // ================================
                try
                {
                    // retrieve component
                    PPDataContext db        = new PPDataContext();
                    Component     component = Component.GetByGuid(db, guidComponent);
                    if (null == component)
                    {
                        throw new ExceptionDAL(string.Format("No component with Guid = {0}", guidComponent));
                    }

                    CardboardProfile profile3 = CardboardProfile.GetByName(db, "P3");
                    if (null == profile3)
                    {
                        profile3 = CardboardProfile.CreateNew(db, "P3", "P3", 3.0f);
                    }
                    Dictionary <string, double> defaultMajorations = Component.GetDefaultMajorations(db, component.ID, profile3, Component.MajoRounding.ROUDING_FIRSTDECIMALNEAREST);
                    component.InsertNewMajorationSet(db, profile3.Name, defaultMajorations);
                    defaultMajorations["m1"] = 100.0;
                    defaultMajorations["m2"] = 100.0;
                    component.UpdateMajorationSet(db, profile3, defaultMajorations);
                    db.Dispose();
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (Exception ex) { _log.Error(ex.Message); }
                // ================================
                // ================================ TreeBuilder
                // show document tree
                builder.BuildTree(treeConsole);
                // ================================
                // ================================ Delete components / documents
                try
                {
                    if (deleteAll)
                    {
                        PPDataContext db = new PPDataContext();
                        Component.DeleteAll(db);
                        _log.Info("Successfully deleted Components...");
                        Document.DeleteAll(db);
                        _log.Info("Successfully deleted Documents...");
                        DocumentType.DeleteAll(db);
                        _log.Info("Successfully deleted DocumentTypes...");
                        TreeNode.DeleteAll(db);
                        _log.Info("Successfully deleted TreeNodes...");
                        CardboardProfile.DeleteAll(db);
                        _log.Info("Successfully deleted CardboardProfile...");
                        CardboardFormat.DeleteAll(db);
                        _log.Info("Successfully deleted Cardboard formats...");
                        db.Dispose();
                    }
                }
                catch (ExceptionDAL ex) { _log.Debug(ex.Message); }
                catch (System.Exception ex) { _log.Error(ex.Message); }
                // ================================
                // ================================ TreeBuilder
                // show document tree
                builder.BuildTree(treeConsole);
                // ================================
            }
            catch (System.Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }