Example #1
0
        public static GeometryModel3D CreateTextLabelModel3D(string text, Brush textColor, bool isDoubleSided, double height, Point3D center, Vector3D textDirection, Vector3D updirection)
        {
            // First we need a textblock containing the text of our label
            var tb = new TextBlock(new Run(text))
            {
                Foreground = textColor, FontFamily = new FontFamily("Arial")
            };

            tb.FontWeight = FontWeights.Bold;

            // Now use that TextBlock as the brush for a material
            var mat = new DiffuseMaterial {
                Brush = new VisualBrush(tb)
            };

            // We just assume the characters are square
            double width = text.Length * height * 0.6;

            // tb.Measure(new Size(text.Length * height * 2, height * 2));
            // width=tb.DesiredSize.Width;

            // Since the parameter coming in was the center of the label,
            // we need to find the four corners
            // p0 is the lower left corner
            // p1 is the upper left
            // p2 is the lower right
            // p3 is the upper right
            var p0 = center - width / 2 * textDirection - height / 2 * updirection;
            var p1 = p0 + updirection * 1 * height;
            var p2 = p0 + textDirection * width;
            var p3 = p0 + updirection * 1 * height + textDirection * width;

            // Now build the geometry for the sign.  It's just a
            // rectangle made of two triangles, on each side.
            var mg = new MeshGeometry3D {
                Positions = new Point3DCollection {
                    p0, p1, p2, p3
                }
            };

            if (isDoubleSided)
            {
                mg.Positions.Add(p0); // 4
                mg.Positions.Add(p1); // 5
                mg.Positions.Add(p2); // 6
                mg.Positions.Add(p3); // 7
            }

            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(3);
            mg.TriangleIndices.Add(1);
            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(2);
            mg.TriangleIndices.Add(3);

            if (isDoubleSided)
            {
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(5);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(6);
            }

            // These texture coordinates basically stretch the
            // TextBox brush to cover the full side of the label.
            mg.TextureCoordinates.Add(new Point(0, 1));
            mg.TextureCoordinates.Add(new Point(0, 0));
            mg.TextureCoordinates.Add(new Point(1, 1));
            mg.TextureCoordinates.Add(new Point(1, 0));

            if (isDoubleSided)
            {
                mg.TextureCoordinates.Add(new Point(1, 1));
                mg.TextureCoordinates.Add(new Point(1, 0));
                mg.TextureCoordinates.Add(new Point(0, 1));
                mg.TextureCoordinates.Add(new Point(0, 0));
            }

            // And that's all.  Return the result.
            return(new GeometryModel3D(mg, mat));
        }
Example #2
0
        private void drawSynchy()
        {
            DiffuseMaterial material  = new DiffuseMaterial(Brushes.Wheat);
            int             lineWidth = 3;

            for (int i = 0; i < GUIComponents.synchyList.Count; ++i)
            {
                if (GUIComponents.synchyList[i].Center.Z == 0)
                {
                    continue;
                }

                if ((bool)parentGUI.show3DCheck.IsChecked)
                {
                    Bar3D baseBar = new Bar3D();
                    baseBar.SideCount = 100;

                    Transform3DGroup transGroupBase = new Transform3DGroup();
                    //   transGroupBase.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), -90)));
                    transGroupBase.Children.Add(new ScaleTransform3D(0.1, 0.1, 0.05));
                    transGroupBase = getSynchyTransGroup(transGroupBase, i);

                    double heightFactor = 1.7;
                    transGroupBase.Children.Add(new TranslateTransform3D(-1 * Vector3D.Divide(GUIComponents.synchyList[i].zPar, heightFactor))); //new Vector3D(height*GUIComponents.synchyList[i].zPar.X, GUIComponents.synchyList[i].zPar.Y, GUIComponents.synchyList[i].zPar.Z)));
                    transGroupBase.Children.Add(new TranslateTransform3D(new Vector3D(GUIComponents.synchyList[i].Center.X, GUIComponents.synchyList[i].Center.Y, GUIComponents.synchyList[i].Center.Z)));
                    baseBar.Transform = transGroupBase;                                                                                          //.Identity;
                    baseBar.Material  = material;
                    show_viewport3D.Children.Add(baseBar);

                    Box3D            bodyBox = new Box3D();
                    double           l = 0.08, w = 0.08, h = 0.12;
                    Transform3DGroup transGroupBody = new Transform3DGroup();
                    transGroupBody.Children.Add(new ScaleTransform3D(l, w, h));
                    transGroupBody.Children.Add(new TranslateTransform3D(new Vector3D(-l / 2, -w / 2, -h / 2))); //new Vector3D(height*GUIComponents.synchyList[i].zPar.X, GUIComponents.synchyList[i].zPar.Y, GUIComponents.synchyList[i].zPar.Z)));

                    transGroupBody = getSynchyTransGroup(transGroupBody, i);
                    transGroupBody.Children.Add(new TranslateTransform3D(new Vector3D(GUIComponents.synchyList[i].Center.X, GUIComponents.synchyList[i].Center.Y, GUIComponents.synchyList[i].Center.Z)));
                    bodyBox.Transform = transGroupBody;
                    bodyBox.Material  = material;
                    show_viewport3D.Children.Add(bodyBox);

                    Spherical3D      headSphere     = new Spherical3D();
                    Transform3DGroup transGroupHead = new Transform3DGroup();
                    transGroupHead.Children.Add(new ScaleTransform3D(0.1, 0.1, 0.1));
                    transGroupHead = getSynchyTransGroup(transGroupHead, i);
                    transGroupHead.Children.Add(new TranslateTransform3D(Vector3D.Divide(GUIComponents.synchyList[i].zPar, heightFactor)));
                    transGroupHead.Children.Add(new TranslateTransform3D(new Vector3D(GUIComponents.synchyList[i].Center.X, GUIComponents.synchyList[i].Center.Y, GUIComponents.synchyList[i].Center.Z)));
                    headSphere.Transform = transGroupHead;
                    headSphere.Material  = material;
                    show_viewport3D.Children.Add(headSphere);

                    ScreenSpaceLines3D x = new ScreenSpaceLines3D();
                    x.Thickness = lineWidth;
                    x.Color     = Colors.Red;
                    Point3D origin = new Point3D(GUIComponents.synchyList[i].Center.X, GUIComponents.synchyList[i].Center.Y, GUIComponents.synchyList[i].Center.Z);
                    Point3D x_unit = new Point3D(GUIComponents.synchyList[i].xUnit.X, GUIComponents.synchyList[i].xUnit.Y, GUIComponents.synchyList[i].xUnit.Z);

                    x.Points.Add(origin);
                    x.Points.Add(x_unit);
                    this.show_viewport3D.Children.Add(x);
                }
                else
                {
                    ScreenSpaceLines3D x = new ScreenSpaceLines3D();
                    ScreenSpaceLines3D y = new ScreenSpaceLines3D();
                    ScreenSpaceLines3D z = new ScreenSpaceLines3D();

                    x.Thickness = lineWidth;
                    x.Color     = Colors.Gray;
                    y.Thickness = lineWidth;
                    y.Color     = Colors.BlueViolet;
                    z.Thickness = lineWidth;
                    z.Color     = Colors.Pink;

                    Point3D origin = new Point3D(GUIComponents.synchyList[i].Center.X, GUIComponents.synchyList[i].Center.Y, GUIComponents.synchyList[i].Center.Z);
                    Point3D x_unit = new Point3D(GUIComponents.synchyList[i].xUnit.X, GUIComponents.synchyList[i].xUnit.Y, GUIComponents.synchyList[i].xUnit.Z);
                    Point3D y_unit = new Point3D(GUIComponents.synchyList[i].yUnit.X, GUIComponents.synchyList[i].yUnit.Y, GUIComponents.synchyList[i].yUnit.Z);
                    Point3D z_unit = new Point3D(GUIComponents.synchyList[i].zUnit.X, GUIComponents.synchyList[i].zUnit.Y, GUIComponents.synchyList[i].zUnit.Z);
                    x.Points.Add(origin);
                    x.Points.Add(x_unit);

                    y.Points.Add(origin);
                    y.Points.Add(y_unit);

                    z.Points.Add(origin);
                    z.Points.Add(z_unit);

                    this.show_viewport3D.Children.Add(x);
                    this.show_viewport3D.Children.Add(y);
                    this.show_viewport3D.Children.Add(z);
                }
            }
        }
Example #3
0
        // Add the model to the Model3DGroup.
        private void DefineModel()
        {
            // Brushes.
#if MONOCHROME
            SolidColorBrush pink_brush         = new SolidColorBrush(Color.FromArgb(255, 224, 224, 224));
            SolidColorBrush lightgreen_brush   = new SolidColorBrush(Color.FromArgb(255, 150, 150, 150));
            SolidColorBrush lightergreen_brush = new SolidColorBrush(Color.FromArgb(255, 200, 200, 200));
            SolidColorBrush lightblue_brush    = new SolidColorBrush(Color.FromArgb(255, 100, 100, 100));
            SolidColorBrush red_brush          = new SolidColorBrush(Color.FromArgb(255, 60, 60, 60));
            SolidColorBrush green_brush        = new SolidColorBrush(Color.FromArgb(255, 80, 80, 80));
            SolidColorBrush blue_brush         = new SolidColorBrush(Color.FromArgb(255, 160, 160, 160));
            SolidColorBrush seg_brush          = new SolidColorBrush(Color.FromArgb(255, 20, 20, 20));
#else
            SolidColorBrush pink_brush       = Brushes.Pink;
            SolidColorBrush lightgreen_brush = Brushes.LightGreen;
            SolidColorBrush lightblue_brush  = Brushes.LightBlue;
            SolidColorBrush red_brush        = Brushes.Red;
            SolidColorBrush green_brush      = Brushes.Green;
            SolidColorBrush blue_brush       = Brushes.Blue;
            SolidColorBrush seg_brush        = Brushes.Red;
#endif

            // Octahedron.
            MeshGeometry3D octo_mesh = new MeshGeometry3D();
            octo_mesh.AddOctahedron(3, null);
            DiffuseMaterial octo_material = new DiffuseMaterial(lightergreen_brush);
            GeometryModel3D octo_model    = new GeometryModel3D(octo_mesh, octo_material);
            MainModel3Dgroup.Children.Add(octo_model);

            // Cube.
            double         s         = octo_mesh.Positions[0].Y;
            MeshGeometry3D cube_mesh = new MeshGeometry3D();
            cube_mesh.AddCube(s, null);
            DiffuseMaterial cube_material = new DiffuseMaterial(pink_brush);
            GeometryModel3D cube_model    = new GeometryModel3D(cube_mesh, cube_material);
            MainModel3Dgroup.Children.Add(cube_model);

#if AXES
            // Axes.
            Point3D        origin         = new Point3D();
            const double   axis_thickness = 0.05;
            const double   axis_length    = 3;
            MeshGeometry3D xaxis_mesh     = new MeshGeometry3D();
            xaxis_mesh.AddSegment(origin, new Point3D(axis_length, 0, 0), axis_thickness, true);
            DiffuseMaterial xaxis_material = new DiffuseMaterial(red_brush);
            GeometryModel3D xaxis_model    = new GeometryModel3D(xaxis_mesh, xaxis_material);
            MainModel3Dgroup.Children.Add(xaxis_model);

            MeshGeometry3D yaxis_mesh = new MeshGeometry3D();
            yaxis_mesh.AddSegment(origin, new Point3D(0, axis_length, 0), axis_thickness, true);
            DiffuseMaterial yaxis_material = new DiffuseMaterial(green_brush);
            GeometryModel3D yaxis_model    = new GeometryModel3D(yaxis_mesh, yaxis_material);
            MainModel3Dgroup.Children.Add(yaxis_model);

            MeshGeometry3D zaxis_mesh = new MeshGeometry3D();
            zaxis_mesh.AddSegment(origin, new Point3D(0, 0, axis_length), axis_thickness, true);
            DiffuseMaterial zaxis_material = new DiffuseMaterial(blue_brush);
            GeometryModel3D zaxis_model    = new GeometryModel3D(zaxis_mesh, zaxis_material);
            MainModel3Dgroup.Children.Add(zaxis_model);
#endif
        }
Example #4
0
        internal static Model3DGroup CreateGeometry(List <MaterialColorProps> materialBrushes, List <EmissiveMaterial> selectionEmissives, Transform3D transform, Color baseColor, SpecularMaterial baseSpecular, Color colorColor, SpecularMaterial colorSpecular, bool isFinal)
        {
            const double SCALE = .66d;

            Model3DGroup retVal = new Model3DGroup();

            GeometryModel3D  geometry;
            MaterialGroup    material;
            DiffuseMaterial  diffuse;
            SpecularMaterial specular;

            #region Main Cylinder

            geometry = new GeometryModel3D();
            material = new MaterialGroup();
            diffuse  = new DiffuseMaterial(new SolidColorBrush(baseColor));
            materialBrushes.Add(new MaterialColorProps(diffuse, baseColor));
            material.Children.Add(diffuse);
            specular = baseSpecular;
            materialBrushes.Add(new MaterialColorProps(specular));
            material.Children.Add(specular);

            if (!isFinal)
            {
                EmissiveMaterial selectionEmissive = new EmissiveMaterial(Brushes.Transparent);
                material.Children.Add(selectionEmissive);
                selectionEmissives.Add(selectionEmissive);
            }

            geometry.Material     = material;
            geometry.BackMaterial = material;

            geometry.Geometry = GetMeshBase(SCALE, isFinal);

            retVal.Children.Add(geometry);

            #endregion

            #region Ring

            geometry = new GeometryModel3D();
            material = new MaterialGroup();
            diffuse  = new DiffuseMaterial(new SolidColorBrush(colorColor));
            materialBrushes.Add(new MaterialColorProps(diffuse, colorColor));
            material.Children.Add(diffuse);
            specular = colorSpecular;
            materialBrushes.Add(new MaterialColorProps(specular));
            material.Children.Add(specular);

            if (!isFinal)
            {
                EmissiveMaterial selectionEmissive = new EmissiveMaterial(Brushes.Transparent);
                material.Children.Add(selectionEmissive);
                selectionEmissives.Add(selectionEmissive);
            }

            geometry.Material     = material;
            geometry.BackMaterial = material;

            geometry.Geometry = GetMeshColor(SCALE, isFinal);

            retVal.Children.Add(geometry);

            #endregion

            // Transform
            retVal.Transform = transform;

            // Exit Function
            return(retVal);
        }
        public ModelMoverOverlayWithZUpAxisSample()
        {
            // To use custom axes in ModelMoverVisual3D we could also change the default axes direction with the changing the following static fields:
            // This way we could define the ModelMoverVisual3D in XAML.
            // But here we will rather use a ModelMoverVisual3D constructor that takes custom axes as parameters.
            //ModelMoverVisual3D.DefaultXAxis = new Vector3D(1, 0, 0);
            //ModelMoverVisual3D.DefaultYAxis = new Vector3D(0, 0, -1);
            //ModelMoverVisual3D.DefaultZAxis = new Vector3D(0, 1, 0);


            InitializeComponent();


            // Calculate the inverted matrix at startup (used to convert from standard Y up to our Z up coordinate system)
            var invertedZUpMatrix = ZUpMatrix;

            invertedZUpMatrix.Invert();

            _zUpTransform3D         = new MatrixTransform3D(ZUpMatrix);
            _invertedZUpTransform3D = new MatrixTransform3D(invertedZUpMatrix);



            // To define custom axes directions for ModelMoverVisual3D, use the constructor that takes axes direction (note that this cannot be done in XAML)
            _modelMover = new ModelMoverVisual3D(xAxisVector3D: new Vector3D(ZUpMatrix.M11, ZUpMatrix.M12, ZUpMatrix.M13),
                                                 yAxisVector3D: new Vector3D(ZUpMatrix.M21, ZUpMatrix.M22, ZUpMatrix.M23),
                                                 zAxisVector3D: new Vector3D(ZUpMatrix.M31, ZUpMatrix.M32, ZUpMatrix.M33))
            {
                AxisLength      = 50,
                AxisRadius      = 1.5,
                AxisArrowRadius = 5
            };


            // Setup event handlers on ModelMoverVisual3D
            _modelMover.ModelMoveStarted += delegate(object o, EventArgs eventArgs)
            {
                if (_selectedBoxModel == null)
                {
                    return;
                }

                _startMovePosition = _selectedBoxModel.CenterPosition;
            };

            _modelMover.ModelMoved += delegate(object o, Ab3d.Common.ModelMovedEventArgs e)
            {
                if (_selectedBoxModel == null)
                {
                    return;
                }


                // When using custom coordinate system we need to transform the e.MoveVector3D.
                // Because the e.MoveVector3D is defined in standard Y up WPF 3D coordinate system,
                // we need to convert that into out Z up coordinate system.
                // This is done with using the inverted YUpMatrix:
                var transformedMoveVector3D = _invertedZUpTransform3D.Transform(e.MoveVector3D);

                var newCenterPosition = _startMovePosition + transformedMoveVector3D;

                if (Math.Abs(newCenterPosition.X) > 2000 ||
                    Math.Abs(newCenterPosition.Y) > 2000 ||
                    Math.Abs(newCenterPosition.Z) > 2000)
                {
                    InfoTextBlock.Text = "Move out of range";
                    return;
                }

                _selectedBoxModel.CenterPosition = newCenterPosition;


                var position = GetSelectedModelWorldPosition(); // GetSelectedModelPosition gets the _selectedBoxModel.CenterPosition and transforms it with the transformations of parent ModelVisual3D objects

                // Because ModelMoverVisual3D is in a separate Viewport3D that does not use the ZUpMatrix transformation,
                // we need to transform the position from z up coordinate system into the standard WPF 3D coordinate system:
                _modelMover.Position = _zUpTransform3D.Transform(position);


                InfoTextBlock.Text = string.Format("MoveVector3D: {0:0}", e.MoveVector3D);
            };

            _modelMover.ModelMoveEnded += delegate(object sender, EventArgs args)
            {
                InfoTextBlock.Text = "";
            };

            RootOverlayModelVisual3D.Children.Add(_modelMover);



            // Update the axes for CameraAxisPanel
            CustomCameraAxisPanel1.CustomizeAxes(new Vector3D(1, 0, 0), "X", Colors.Red,
                                                 new Vector3D(0, 1, 0), "Z", Colors.Blue,
                                                 new Vector3D(0, 0, -1), "Y", Colors.Green);



            // Set the ZUpMatrix to transform all the shown objects.
            // This way the objects will use the Z up matrix, but before rendering this will be transformed into the standard WPF 3D y up coordinate system.
            ZUpRootVisual.Transform = _zUpTransform3D;


            // We need to synchronize the Camera and Lights in OverlayViewport with the camera in the MainViewport
            Camera1.CameraChanged += delegate(object s, CameraChangedRoutedEventArgs args)
            {
                OverlayViewport.Camera         = MainViewport.Camera;
                OverlayViewportLight.Direction = ((DirectionalLight)Camera1.CameraLight).Direction;
            };


            _normalMaterial = new DiffuseMaterial(Brushes.Silver);
            _eventManager   = new Ab3d.Utilities.EventManager3D(MainViewport);

            CreateRandomScene();
        }
Example #6
0
        public void CreateElement(string groupel, string ingroupel, string iningroupel, double getPosX, double getPosY, double getPosZ, double getLenX, double getLenY, double getLenZ, int getAngleX, int getAngleY, int getAngleZ, int idmaterial, ModelUIElement3D thisobject1, double otx, double oty, double otz, string text = "-1", int id = -1)
        {
            if (text == "-1")
            {
                text = win.soureseDefault;
            }
            if (id == -1)
            {
                id = win.iddefaultB;
            }
            ModelImporter importer  = new ModelImporter();
            Material      material1 = new DiffuseMaterial(win.defcolor);

            importer.DefaultMaterial = material1;
            string           request          = "select sourse from elements where id=" + idmaterial;
            NpgsqlConnection npgSqlConnection = new NpgsqlConnection(win.connectionString);

            npgSqlConnection.Open();
            NpgsqlCommand    npgSqlCommand = new NpgsqlCommand(request, npgSqlConnection);
            NpgsqlDataReader reader        = npgSqlCommand.ExecuteReader();
            string           str           = "";

            while (reader.Read())
            {
                str = reader.GetString(0);
            }
            Model3DGroup model = new Model3DGroup();

            model = importer.Load(str);
            double maxx = 0;
            int    idd  = win.rand.Next(0, 100000);
            double xx   = 9999;
            double yy   = 9999;
            double zz   = 9999;

            for (int i = 0; i < model.Children.Count; i++)
            {
                GeometryModel3D   gmodel = model.Children[i] as GeometryModel3D;
                MeshGeometry3D    mmodel = (MeshGeometry3D)gmodel.Geometry;
                Point3DCollection p3dc   = mmodel.Positions;
                if (gmodel.Bounds.SizeX > maxx)
                {
                    maxx = gmodel.Bounds.SizeX;
                }
                if (gmodel.Bounds.SizeY > maxx)
                {
                    maxx = gmodel.Bounds.SizeY;
                }
                if (gmodel.Bounds.SizeZ > maxx)
                {
                    maxx = gmodel.Bounds.SizeZ;
                }
                if (gmodel.Bounds.X < xx)
                {
                    xx = gmodel.Bounds.X;
                }
                if (gmodel.Bounds.Y < yy)
                {
                    yy = gmodel.Bounds.Y;
                }
                if (gmodel.Bounds.Z < zz)
                {
                    zz = gmodel.Bounds.Z;
                }
            }
            for (int i = 0; i < model.Children.Count; i++)
            {
                GeometryModel3D   gmodel = model.Children[i] as GeometryModel3D;
                MeshGeometry3D    mmodel = (MeshGeometry3D)gmodel.Geometry;
                Point3DCollection p3dc   = mmodel.Positions;
                gmodel.Material = new DiffuseMaterial(win.defcolor);
                for (int ii = 0; ii < p3dc.Count; ii++)
                {
                    Point3D tp = p3dc[ii];
                    tp.X     = tp.X / maxx;
                    tp.Y     = tp.Y / maxx;
                    tp.Z     = tp.Z / maxx;
                    p3dc[ii] = tp;
                }
                for (int ii = 0; ii < p3dc.Count; ii++)
                {
                    Point3D tp = p3dc[ii];
                    tp.X     = tp.X - xx / maxx;
                    tp.Y     = tp.Y - yy / maxx;
                    tp.Z     = tp.Z - zz / maxx;
                    p3dc[ii] = tp;
                }
                ModelUIElement3D modelUI = new ModelUIElement3D();
                modelUI.Model = gmodel;
                ElementCabinet tempmodel = new ElementCabinet(modelUI, 1, 1, 1, 0, 0, 0);
                tempmodel.idtexture   = id;
                tempmodel.groupel     = groupel;
                tempmodel.ingroupel   = ingroupel;
                tempmodel.iningroupel = iningroupel;
                tempmodel.hashtable   = win.CreatedElements;
                win.CreatedElements.Add(modelUI.GetHashCode(), tempmodel);
                win.container.Children.Add(modelUI);
                modelUI.MouseUp += win.ClickOnModel;
                tempmodel.LenZ   = 2;
                tempmodel.changeObjectLen(getLenX, getLenY, getLenZ);
                tempmodel.changeObjectPos(getPosX, getPosY, getPosZ);
                tempmodel.ChangeAngleX(getAngleX);
                tempmodel.ChangeAngleY(getAngleY);
                tempmodel.ChangeAngleZ(getAngleZ);
                tempmodel.idelement          = idmaterial;
                tempmodel.select             = win.CreatedElements[thisobject1.GetHashCode()] as ElementCabinet;
                tempmodel.otsx               = otx;
                tempmodel.otsy               = oty;
                tempmodel.otsz               = otz;
                tempmodel.thismodel.Material = new DiffuseMaterial(new SolidColorBrush(win.defcolor.Color));
            }
        }
Example #7
0
        public CollisionCheckViewModel CalculateBeamCollision(PlanSetup planSetup, Beam beam)
        {
            var  calculator = new CollisionSummariesCalculator();
            var  modelGroup = new Model3DGroup();
            var  isoctr     = GetIsocenter(beam);
            bool isVMAT     = false;
            bool isStatic   = false;
            bool isElectron = false;
            bool isSRSArc   = false;

            var            collisionSummary = new CollisionCheckViewModel();
            MeshGeometry3D bodyMesh;
            var            iso3DMesh = CalculateIsoMesh(isoctr);
            var            body      = planSetup.StructureSet.Structures.Where(x => x.Id.Contains("BODY")).First();
            Structure      couch     = null;
            MeshGeometry3D couchMesh = null;

            try
            {
                foreach (Structure structure in planSetup.StructureSet.Structures)
                {
                    if (structure.StructureCodeInfos.FirstOrDefault().Code == "Support")
                    {
                        couch     = structure;
                        couchMesh = couch.MeshGeometry;
                    }
                }
            }
            catch
            {
                couch = null;
            }
            bodyMesh = body.MeshGeometry;
            var collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Green));

            if (beam.EnergyModeDisplayName.Contains("E"))
            {
                isElectron = true;
            }
            if (beam.EnergyModeDisplayName.Contains("SRS"))
            {
                isSRSArc = true;
            }
            if (beam.MLCPlanType.ToString() == "VMAT" || beam.Technique.Id.Contains("ARC"))
            {
                isVMAT             = true;
                collimatorMaterial = collimatorMaterialVMAT;
            }
            if (beam.Technique.ToString().Contains("STATIC"))
            {
                isStatic           = true;
                collimatorMaterial = collimatorMaterialStatic;
            }

            MeshGeometry3D collimatorMesh = CalculateCollimatorMesh(beam, isoctr, isVMAT, isStatic, isElectron, isSRSArc);

            collisionSummary = calculator.GetFieldCollisionSummary(beam, couch, body);
            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = iso3DMesh, Material = redMaterial, BackMaterial = redMaterial
            });
            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = collimatorMesh, Material = collimatorMaterial, BackMaterial = darkblueMaterial
            });
            return(collisionSummary);
        }
        private Model3DGroup Initialize_Environment(List <string> modelsNames)
        {
            try
            {
                ModelImporter import = new ModelImporter();
                joints = new List <Joint>();

                foreach (string modelName in modelsNames)
                {
                    var              materialGroup = new MaterialGroup();
                    Color            mainColor     = Colors.White;
                    EmissiveMaterial emissMat      = new EmissiveMaterial(new SolidColorBrush(mainColor));
                    DiffuseMaterial  diffMat       = new DiffuseMaterial(new SolidColorBrush(mainColor));
                    SpecularMaterial specMat       = new SpecularMaterial(new SolidColorBrush(mainColor), 200);
                    materialGroup.Children.Add(emissMat);
                    materialGroup.Children.Add(diffMat);
                    materialGroup.Children.Add(specMat);

                    var             link  = import.Load(basePath + modelName);
                    GeometryModel3D model = link.Children[0] as GeometryModel3D;
                    model.Material     = materialGroup;
                    model.BackMaterial = materialGroup;
                    joints.Add(new Joint(link));
                }

                RA.Children.Add(joints[0].model);
                RA.Children.Add(joints[1].model);
                RA.Children.Add(joints[2].model);
                RA.Children.Add(joints[3].model);
                RA.Children.Add(joints[4].model);

                changeModelColor(joints[0], Colors.Red);
                changeModelColor(joints[1], Colors.Pink);
                changeModelColor(joints[2], Colors.Blue);
                changeModelColor(joints[3], Colors.Green);
                changeModelColor(joints[4], Colors.Yellow);


                joints[0].angleMin  = -110;
                joints[0].angleMax  = 110;
                joints[0].rotAxisX  = 0;
                joints[0].rotAxisY  = 0;
                joints[0].rotAxisZ  = 1;
                joints[0].rotPointX = 0;
                joints[0].rotPointY = 0;
                joints[0].rotPointZ = 100;   //no use

                joints[1].angleMin  = -120;
                joints[1].angleMax  = 120;
                joints[1].rotAxisX  = 0;
                joints[1].rotAxisY  = 0;
                joints[1].rotAxisZ  = 1;
                joints[1].rotPointX = 250;
                joints[1].rotPointY = 0;
                joints[1].rotPointZ = 100;   //no use

                joints[2].angleMin  = -110;  //linear movement
                joints[2].angleMax  = 110;
                joints[2].rotAxisX  = 0;
                joints[2].rotAxisY  = 0;
                joints[2].rotAxisZ  = 1;
                joints[2].rotPointX = 400;
                joints[2].rotPointY = 0;
                joints[2].rotPointZ = 100;

                joints[3].angleMin  = -360;
                joints[3].angleMax  = 360;
                joints[3].rotAxisX  = 0;
                joints[3].rotAxisY  = 0;
                joints[3].rotAxisZ  = 1;
                joints[3].rotPointX = 400;
                joints[3].rotPointY = 0;
                joints[3].rotPointZ = 100;    //no use
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception Error:" + e.StackTrace);
            }
            return(RA);
        }
Example #9
0
        private Model3D ConvertVisualToModel3D(Visual visual, ref double z)
        {
            Model3D    model    = null;
            Rect       bounds   = VisualTreeHelper.GetContentBounds(visual);
            Viewport3D viewport = visual as Viewport3D;

            if (viewport != null)
            {
                bounds = new Rect(viewport.RenderSize);
            }
            if (this.includeEmptyVisuals)
            {
                bounds.Union(VisualTreeHelper.GetDescendantBounds(visual));
            }
            if (!bounds.IsEmpty && bounds.Width > 0 && bounds.Height > 0)
            {
                MeshGeometry3D mesh = new MeshGeometry3D();
                mesh.Positions.Add(new Point3D(bounds.Left, bounds.Top, z));
                mesh.Positions.Add(new Point3D(bounds.Right, bounds.Top, z));
                mesh.Positions.Add(new Point3D(bounds.Right, bounds.Bottom, z));
                mesh.Positions.Add(new Point3D(bounds.Left, bounds.Bottom, z));
                mesh.TextureCoordinates.Add(new Point(0, 0));
                mesh.TextureCoordinates.Add(new Point(1, 0));
                mesh.TextureCoordinates.Add(new Point(1, 1));
                mesh.TextureCoordinates.Add(new Point(0, 1));
                mesh.Normals.Add(new Vector3D(0, 0, 1));
                mesh.Normals.Add(new Vector3D(0, 0, 1));
                mesh.Normals.Add(new Vector3D(0, 0, 1));
                mesh.Normals.Add(new Vector3D(0, 0, 1));
                mesh.TriangleIndices = new Int32Collection(new int[] { 0, 1, 2, 2, 3, 0 });
                mesh.Freeze();

                Brush           brush    = this.MakeBrushFromVisual(visual, bounds);
                DiffuseMaterial material = new DiffuseMaterial(brush);
                material.Freeze();

                model = new GeometryModel3D(mesh, material);
                ((GeometryModel3D)model).BackMaterial = material;

                z -= 1;
            }

            int childrenCount = VisualTreeHelper.GetChildrenCount(visual);

            if (childrenCount > 0)
            {
                Model3DGroup group = new Model3DGroup();
                if (model != null)
                {
                    group.Children.Add(model);
                }
                for (int i = 0; i < childrenCount; i++)
                {
                    Visual childVisual = VisualTreeHelper.GetChild(visual, i) as Visual;
                    if (childVisual != null)
                    {
                        Model3D childModel = this.ConvertVisualToModel3D(childVisual, ref z);
                        if (childModel != null)
                        {
                            group.Children.Add(childModel);
                        }
                    }
                }
                model = group;
            }

            if (model != null)
            {
                Transform transform = VisualTreeHelper.GetTransform(visual);
                Matrix    matrix    = (transform == null ? Matrix.Identity : transform.Value);
                Vector    offset    = VisualTreeHelper.GetOffset(visual);
                matrix.Translate(offset.X, offset.Y);
                if (!matrix.IsIdentity)
                {
                    Matrix3D    matrix3D    = new Matrix3D(matrix.M11, matrix.M12, 0, 0, matrix.M21, matrix.M22, 0, 0, 0, 0, 1, 0, matrix.OffsetX, matrix.OffsetY, 0, 1);
                    Transform3D transform3D = new MatrixTransform3D(matrix3D);
                    transform3D.Freeze();
                    model.Transform = transform3D;
                }
                model.Freeze();
            }

            return(model);
        }
Example #10
0
        public CollisionCheckViewModel GetFieldCollisionSummary(Beam beam, Structure couch, Structure body)
        {
            Point3D        isoctr             = GetIsocenter(beam);
            MeshGeometry3D iso3DMesh          = CalculateIsoMesh(isoctr);
            bool           isVMAT             = false;
            bool           isStatic           = false;
            bool           isElectron         = false;
            bool           isSRSArc           = false;
            var            collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Green));

            if (beam.EnergyModeDisplayName.Contains("E"))
            {
                isElectron = true;
            }
            if (beam.EnergyModeDisplayName.Contains("SRS"))
            {
                isSRSArc = true;
            }
            if (beam.MLCPlanType.ToString() == "VMAT" || beam.Technique.Id.Contains("ARC"))
            {
                isVMAT             = true;
                collimatorMaterial = collimatorMaterialVMAT;
            }
            if (beam.Technique.ToString().Contains("STATIC"))
            {
                isStatic           = true;
                collimatorMaterial = collimatorMaterialStatic;
            }

            var bodyMesh = body.MeshGeometry;

            MeshGeometry3D collimatorMesh        = CalculateCollimatorMesh(beam, isoctr, isVMAT, isStatic, isElectron, isSRSArc);
            string         shortestDistanceBody  = "2000000";
            string         shortestDistanceTable = "2000000";
            string         status = "Clear";

            shortestDistanceBody = ShortestDistance(collimatorMesh, bodyMesh);
            if (couch != null)
            {
                var couchMesh = couch.MeshGeometry;
                shortestDistanceTable = ShortestDistance(collimatorMesh, couchMesh);
            }

            else
            {
                shortestDistanceTable = " - ";
                status = " - ";
            }
            Console.WriteLine(beam.Id + " - gantry to body is " + shortestDistanceBody + " cm");
            Console.WriteLine(beam.Id + " - gantry to table is " + shortestDistanceTable + " cm");
            if (shortestDistanceTable != " - ")
            {
                if ((Convert.ToDouble(shortestDistanceBody) < 3.0) || (Convert.ToDouble(shortestDistanceTable) < 3.0))
                {
                    collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red));
                    status             = "Collision";
                }
                if ((Convert.ToDouble(shortestDistanceBody) < 4.0) || (Convert.ToDouble(shortestDistanceTable) < 4.0))
                {
                    collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red));
                    status             = "Warning";
                }
            }
            var collisionSummary = new CollisionCheckViewModel
            {
                View    = true,
                FieldID = beam.Id,
                GantryToBodyDistance  = shortestDistanceBody + " cm",
                GantryToTableDistance = shortestDistanceTable + " cm",
                Status = status
            };

            return(collisionSummary);
        }
Example #11
0
        // Make a 3D surface.
        private void MakeSurface(Model3DGroup surface_model, FunctionOfXZ F,
                                 double xmin, double zmin, double xmax, double zmax,
                                 double dx, double dz, double ymin, double ymax)
        {
            // Make colored materials.
            LinearGradientBrush surface_brush = new LinearGradientBrush();

            surface_brush.StartPoint = new Point(0, 0);
            surface_brush.EndPoint   = new Point(0, 1);
            surface_brush.GradientStops.Add(new GradientStop(Colors.Blue, 0.0));
            surface_brush.GradientStops.Add(new GradientStop(Colors.Lime, 0.25));
            surface_brush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.5));
            surface_brush.GradientStops.Add(new GradientStop(Colors.Orange, 0.75));
            surface_brush.GradientStops.Add(new GradientStop(Colors.Red, 1.0));
            Material surface_material = new DiffuseMaterial(surface_brush);

            // Make a mesh.
            MeshGeometry3D  surface_mesh = new MeshGeometry3D();
            GeometryModel3D new_model    = new GeometryModel3D(surface_mesh, surface_material);

            surface_model.Children.Add(new_model);

            double dy    = ymax - ymin;
            int    num_x = (int)((xmax - xmin) / dx);
            int    num_z = (int)((zmax - zmin) / dz);
            double x     = xmin;

            for (int ix = 0; ix <= num_x - 2; ix++)
            {
                double z = zmin;
                for (int iz = 0; iz <= num_z - 2; iz++)
                {
                    // Make the points.
                    int    i1 = surface_mesh.Positions.Count;
                    double y1 = F(x, z);
                    surface_mesh.Positions.Add(new Point3D(x, y1, z));
                    surface_mesh.TextureCoordinates.Add(new Point(0, (y1 - ymin) / dy));

                    int    i2 = surface_mesh.Positions.Count;
                    double y2 = F(x, z + dz);
                    surface_mesh.Positions.Add(new Point3D(x, y2, z + dz));
                    surface_mesh.TextureCoordinates.Add(new Point(0, (y2 - ymin) / dy));

                    int    i3 = surface_mesh.Positions.Count;
                    double y3 = F(x + dx, z + dz);
                    surface_mesh.Positions.Add(new Point3D(x + dx, y3, z + dz));
                    surface_mesh.TextureCoordinates.Add(new Point(0, (y3 - ymin) / dy));

                    int    i4 = surface_mesh.Positions.Count;
                    double y4 = F(x + dx, z);
                    surface_mesh.Positions.Add(new Point3D(x + dx, y4, z));
                    surface_mesh.TextureCoordinates.Add(new Point(0, (y4 - ymin) / dy));

                    // Make the triangles.
                    surface_mesh.TriangleIndices.Add(i1);
                    surface_mesh.TriangleIndices.Add(i2);
                    surface_mesh.TriangleIndices.Add(i3);

                    surface_mesh.TriangleIndices.Add(i1);
                    surface_mesh.TriangleIndices.Add(i3);
                    surface_mesh.TriangleIndices.Add(i4);

                    z += dz;
                }
                x += dx;
            }
        }
Example #12
0
        // Make a horizontal label at the specified position.
        private void MakeTitle(Model3DGroup the_model)
        {
            Style lbl_sty = new Style(typeof(Label));

            lbl_sty.Setters.Add(new Setter(Label.ForegroundProperty, Brushes.Red));
            lbl_sty.Setters.Add(new Setter(Label.FontFamilyProperty, new FontFamily("Courier New")));
            lbl_sty.Setters.Add(new Setter(Label.FontWeightProperty, FontWeights.Bold));

            StackPanel sp = new StackPanel();

            sp.Background  = Brushes.Transparent;
            sp.Orientation = Orientation.Horizontal;
            Thickness normal = new Thickness(0, 0, 0, 0);
            Thickness backup = new Thickness(-5, 0, 0, 0);
            Thickness super  = new Thickness(-5, -3, 0, 0);

            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = normal, Content = "Cos(x"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = super, Content = "2"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = normal, Content = "+ z"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = super, Content = "2"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = backup, Content = ") / [1 + (x"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = super, Content = "2"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = normal, Content = "+ z"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = super, Content = "2"
            });
            sp.Children.Add(new Label()
            {
                Style = lbl_sty, Margin = backup, Content = ") / 2]"
            });

            Brush          label_brush    = new VisualBrush(sp);
            Material       label_material = new DiffuseMaterial(label_brush);
            MeshGeometry3D label_mesh     = null;

            MakeRectangle(the_model, ref label_mesh, label_material,
                          new Point3D(-3, 3, 4), new Point3D(-3, 1, 4),
                          new Point3D(-3, 1, -4), new Point3D(-3, 3, -4),
                          new Point(0, 0), new Point(0, 1), new Point(1, 1), new Point(1, 0));
        }
        public List <ModelUIElement3D> CreateModelUiElementsDs(IfcModel model, List <IfcGloballyUniqueId> elementIdsList, bool visualizeUnselectedElementsTransparent = true, DiffuseMaterial overrideMaterial = null)
        {
            tempMaterialLibrary = new Dictionary <string, DiffuseMaterial>();
            // Refresh the selected Models
            SelectedModels   = new Dictionary <string, GeometryModel3D>();
            VisualizedModels = new Dictionary <string, ModelUIElement3D>();

            xModel  = model.GetModel();
            context = model.GetModelContext();

            // Loop through Entities and visualze them in the viewport
            var res = new HashSet <IfcGloballyUniqueId>(elementIdsList);

            var elementList = new List <ModelUIElement3D>();

            // GET GEOREFERENCING
            var wcsTransformation = new XbimMatrix3D();
            var myIfcSite         = xModel.Instances.OfType <Xbim.Ifc2x3.ProductExtension.IfcSite>();
            var ifcSites          = myIfcSite as IList <Xbim.Ifc2x3.ProductExtension.IfcSite> ?? myIfcSite.ToList();

            if (ifcSites.Count == 1)
            {
                Xbim.Ifc2x3.ProductExtension.IfcSite mySite = ifcSites.First();
                IfcLocalPlacement relplacement = mySite.ObjectPlacement.ReferencedByPlacements.First();
                wcsTransformation = relplacement.ToMatrix3D();
            }

            foreach (var item in xModel.Instances.OfType <IIfcProduct>())
            {
                if (visualizeUnselectedElementsTransparent == false)
                {
                    if (!res.Contains(item.GlobalId))
                    {
                        continue;
                    }
                }
                // Get the Material
                var mat = new DiffuseMaterial();
                if (overrideMaterial == null)
                {
                    mat = res.Contains(item.GlobalId)
                        ? GeometryHandler.GetStyleFromXbimModel(item, context)
                        : GeometryHandler.GetStyleFromXbimModel(item, context, 0.03);
                }
                else
                {
                    mat = overrideMaterial;
                }

                var m = GeometryHandler.WriteTriangles(item, context, wcsTransformation);
                tempMaterialLibrary.Add(item.GlobalId, mat);
                var element = CreateModelUIElement3D(m, mat);
                element.MouseDown += ElementOnMouseDown;
                elementList.Add(element);
                VisualizedModels.Add(item.GlobalId, element);
            }
            return(elementList);
        }
        private void UpdateVisualization()
        {
            Clear();
            if (packing == null)
            {
                return;            // nothing to display
            }
            var modelGroup     = (Model3DGroup)MyModel.Content;
            var hiddenMaterial = new DiffuseMaterial(new SolidColorBrush(hiddenColor));

            if (selectedItemKey >= 0)
            {
                var selectedItem = packing.Items.Single(x => selectedItemKey == x.Key);
                var selectedPos  = packing.Positions[selectedItem.Key];

                var colorIdx = selectedItem.Value.Material;
                while (colorIdx < 0)
                {
                    colorIdx += colors.Length;
                }
                colorIdx = colorIdx % colors.Length;
                var color    = colors[colorIdx];
                var material = new DiffuseMaterial {
                    Brush = new SolidColorBrush(color)
                };
                materials[selectedItem.Value.Material] = material;

                var selectedModel = new GeometryModel3D {
                    Geometry = new MeshGeometry3D(), Material = material
                };
                AddSolidCube((MeshGeometry3D)selectedModel.Geometry, selectedPos.X, selectedPos.Y, selectedPos.Z,
                             selectedPos.Rotated ? selectedItem.Value.Depth : selectedItem.Value.Width,
                             selectedItem.Value.Height,
                             selectedPos.Rotated ? selectedItem.Value.Width : selectedItem.Value.Depth);
                modelGroup.Children.Add(selectedModel);

                foreach (var item in packing.Items.Where(x => selectedItemKey != x.Key))
                {
                    var position = packing.Positions[item.Key];

                    var w = position.Rotated ? item.Value.Depth : item.Value.Width;
                    var h = item.Value.Height;
                    var d = position.Rotated ? item.Value.Width : item.Value.Depth;

                    var model = new GeometryModel3D {
                        Geometry = new MeshGeometry3D(), Material = hiddenMaterial
                    };
                    AddWireframeCube((MeshGeometry3D)model.Geometry, position.X, position.Y, position.Z, w, h, d, 1);
                    modelGroup.Children.Add(model);
                }
            }
            else
            {
                foreach (var item in packing.Items)
                {
                    var position = packing.Positions[item.Key];

                    var w = position.Rotated ? item.Value.Depth : item.Value.Width;
                    var h = item.Value.Height;
                    var d = position.Rotated ? item.Value.Width : item.Value.Depth;

                    var model = new GeometryModel3D {
                        Geometry = new MeshGeometry3D()
                    };
                    DiffuseMaterial material;
                    if (!materials.TryGetValue(item.Value.Material, out material))
                    {
                        var colorIdx = item.Value.Material;
                        while (colorIdx < 0)
                        {
                            colorIdx += colors.Length;
                        }
                        colorIdx = colorIdx % colors.Length;
                        var color = colors[colorIdx];
                        material = new DiffuseMaterial {
                            Brush = new SolidColorBrush(color)
                        };
                        materials[item.Value.Material] = material;
                    }
                    var selectedModel = new GeometryModel3D {
                        Geometry = new MeshGeometry3D(), Material = material
                    };
                    AddSolidCube((MeshGeometry3D)selectedModel.Geometry, position.X, position.Y, position.Z, w, h, d);
                    modelGroup.Children.Add(selectedModel);
                }
            }

            var container      = packing.BinShape;
            var containerModel = new GeometryModel3D(new MeshGeometry3D(), new DiffuseMaterial(new SolidColorBrush(containerColor)));

            modelGroup.Children.Add(containerModel);
            AddWireframeCube((MeshGeometry3D)containerModel.Geometry, container.Origin.X - .5, container.Origin.Y - .5, container.Origin.Z - .5, container.Width + 1, container.Height + 1, container.Depth + 1);

            var ratio = Math.Max(container.Width, Math.Max(container.Height, container.Depth));

            scale.ScaleX = 1.0 / ratio;
            scale.ScaleY = 1.0 / ratio;
            scale.ScaleZ = 1.0 / ratio;

            scaleZoom.CenterX = rotateX.CenterX = rotateY.CenterX = container.Width / (2.0 * ratio);
            scaleZoom.CenterY = rotateX.CenterY = rotateY.CenterY = container.Height / (2.0 * ratio);
            scaleZoom.CenterZ = rotateX.CenterZ = rotateY.CenterZ = container.Depth / (2.0 * ratio);

            camMain.Position = new Point3D(
                scaleZoom.CenterX,
                3,
                3);
            camMain.LookDirection = new Vector3D(
                0,
                scaleZoom.CenterY - camMain.Position.Y,
                scaleZoom.CenterZ - camMain.Position.Z);
        }
Example #15
0
        public static Model3DGroup AddFieldMesh(PlanSetup planSetup, Beam beam, string status)
        {
            DiffuseMaterial collimatorMaterialStatic = new DiffuseMaterial(new SolidColorBrush(Colors.Green));
            DiffuseMaterial collimatorMaterialVMAT   = new DiffuseMaterial(new SolidColorBrush(Colors.GreenYellow));

            if (status == "Collision")
            {
                collimatorMaterialStatic = new DiffuseMaterial(new SolidColorBrush(Colors.Red));
                collimatorMaterialVMAT   = new DiffuseMaterial(new SolidColorBrush(Colors.Red));
            }
            if (status == "Warning")
            {
                collimatorMaterialStatic = new DiffuseMaterial(new SolidColorBrush(Colors.DarkOrange));
                collimatorMaterialVMAT   = new DiffuseMaterial(new SolidColorBrush(Colors.DarkOrange));
            }
            DiffuseMaterial redMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red));

            DiffuseMaterial darkblueMaterial   = new DiffuseMaterial(new SolidColorBrush(Colors.DarkBlue));
            var             isoModelGroup      = new Model3DGroup();
            var             collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Green));
            var             modelGroup         = new Model3DGroup();
            bool            isVMAT             = false;
            bool            isStatic           = false;
            bool            isElectron         = false;
            bool            isSRSArc           = false;
            var             upDir     = new Vector3D(0, -1, 0);
            var             isoctr    = GetIsocenter(beam);
            var             iso3DMesh = CalculateIsoMesh(isoctr);

            if (beam.EnergyModeDisplayName.Contains("E"))
            {
                isElectron = true;
            }
            if (beam.EnergyModeDisplayName.Contains("SRS"))
            {
                isSRSArc = true;
            }
            if (beam.MLCPlanType.ToString() == "VMAT" || beam.Technique.Id.Contains("ARC"))
            {
                isVMAT             = true;
                collimatorMaterial = collimatorMaterialVMAT;
            }
            if (beam.Technique.ToString().Contains("STATIC"))
            {
                isStatic           = true;
                collimatorMaterial = collimatorMaterialStatic;
            }
            if (planSetup.TreatmentOrientation.ToString() == "HeadFirstProne")
            {
                upDir = new Vector3D(0, 1, 0);
            }
            MeshGeometry3D collimatorMesh = CalculateCollimatorMesh(beam, isoctr, isVMAT, isStatic, isElectron, isSRSArc);

            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = collimatorMesh, Material = collimatorMaterial, BackMaterial = darkblueMaterial
            });
            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = iso3DMesh, Material = redMaterial, BackMaterial = redMaterial
            });
            modelGroup.Freeze();
            return(modelGroup);
        }
Example #16
0
        public MultipleTransformationsExample()
        {
            // Declare scene objects.
            Viewport3D      myViewport3D    = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object. In this sample a
            // linear gradient covers the surface of the 3D object.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(myHorizontalGradient);

            myGeometryModel.Material = myMaterial;
            // Apply multiple transformations to the object. In this sample, a rotation and scale
            // transform is applied.

            // Create and apply a transformation that rotates the object.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;

            // Add the rotation transform to a Transform3DGroup
            Transform3DGroup myTransform3DGroup = new Transform3DGroup();

            myTransform3DGroup.Children.Add(myRotateTransform3D);

            // Create and apply a scale transformation that stretches the object along the local x-axis
            // by 200 percent and shrinks it along the local y-axis by 50 percent.
            ScaleTransform3D myScaleTransform3D = new ScaleTransform3D();

            myScaleTransform3D.ScaleX = 2;
            myScaleTransform3D.ScaleY = 0.5;
            myScaleTransform3D.ScaleZ = 1;

            // Add the scale transform to the Transform3DGroup.
            myTransform3DGroup.Children.Add(myScaleTransform3D);

            // Set the Transform property of the GeometryModel to the Transform3DGroup which includes
            // both transformations. The 3D object now has two Transformations applied to it.
            myGeometryModel.Transform = myTransform3DGroup;
            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;

            myViewport3D.Children.Add(myModelVisual3D);

            // Apply the viewport to the page so it will be rendered.
            this.Content = myViewport3D;
        }
Example #17
0
        private FrameworkElement CreateVisualChild()
        {
            MeshGeometry3D simpleQuad = new MeshGeometry3D()
            {
                Positions          = new Point3DCollection(_mesh),
                TextureCoordinates = new PointCollection(_texCoords),
                TriangleIndices    = new Int32Collection(_indices)
            };

            // Front material is interactive, back material is not.
            Material frontMaterial = new DiffuseMaterial(Brushes.White);

            frontMaterial.SetValue(Viewport2DVisual3D.IsVisualHostMaterialProperty, true);

            VisualBrush vb = new VisualBrush(_logicalChild);

            SetCachingForObject(vb);  // big perf wins by caching!!
            Material backMaterial = new DiffuseMaterial(vb);

            _rotationTransform.Rotation = _quaternionRotation;
            var xfGroup = new Transform3DGroup()
            {
                Children = { _scaleTransform, _rotationTransform }
            };

            GeometryModel3D backModel = new GeometryModel3D()
            {
                Geometry = simpleQuad, Transform = xfGroup, BackMaterial = backMaterial
            };
            Model3DGroup m3dGroup = new Model3DGroup()
            {
                Children = { new DirectionalLight(Colors.White, new Vector3D(0,      0, -1)),
                             new DirectionalLight(Colors.White, new Vector3D(0.1, -0.1,  1)),
                             backModel }
            };

            // Non-interactive Visual3D consisting of the backside, and two lights.
            ModelVisual3D mv3d = new ModelVisual3D()
            {
                Content = m3dGroup
            };

            // Interactive frontside Visual3D
            Viewport2DVisual3D frontModel = new Viewport2DVisual3D()
            {
                Geometry = simpleQuad, Visual = _logicalChild, Material = frontMaterial, Transform = xfGroup
            };

            // Cache the brush in the VP2V3 by setting caching on it.  Big perf wins.
            SetCachingForObject(frontModel);

            // Scene consists of both the above Visual3D's.
            _viewport3d = new Viewport3D()
            {
                ClipToBounds = false, Children = { mv3d, frontModel }
            };

            UpdateRotation();

            return(_viewport3d);
        }
Example #18
0
        private Model3DGroup CreateGeometry(bool isFinal)
        {
            Model3DGroup retVal = new Model3DGroup();

            GeometryModel3D  geometry;
            MaterialGroup    material;
            DiffuseMaterial  diffuse;
            SpecularMaterial specular;

            int domeSegments     = isFinal ? 2 : 10;
            int cylinderSegments = isFinal ? 6 : 35;

            #region Mount Box

            geometry = new GeometryModel3D();
            material = new MaterialGroup();
            diffuse  = new DiffuseMaterial(new SolidColorBrush(WorldColors.GunBase_Color));
            this.MaterialBrushes.Add(new MaterialColorProps(diffuse, WorldColors.GunBase_Color));
            material.Children.Add(diffuse);
            specular = WorldColors.GunBase_Specular;
            this.MaterialBrushes.Add(new MaterialColorProps(specular));
            material.Children.Add(specular);

            if (!isFinal)
            {
                EmissiveMaterial selectionEmissive = new EmissiveMaterial(Brushes.Transparent);
                material.Children.Add(selectionEmissive);
                this.SelectionEmissives.Add(selectionEmissive);
            }

            geometry.Material     = material;
            geometry.BackMaterial = material;

            geometry.Geometry = UtilityWPF.GetCube(new Point3D(-.115, -.1, -.5), new Point3D(.115, .1, -.1));

            retVal.Children.Add(geometry);

            #endregion

            #region Barrel

            geometry = new GeometryModel3D();
            material = new MaterialGroup();
            diffuse  = new DiffuseMaterial(new SolidColorBrush(WorldColors.GunBarrel_Color));
            this.MaterialBrushes.Add(new MaterialColorProps(diffuse, WorldColors.GunBarrel_Color));
            material.Children.Add(diffuse);
            specular = WorldColors.GunBarrel_Specular;
            this.MaterialBrushes.Add(new MaterialColorProps(specular));
            material.Children.Add(specular);

            if (!isFinal)
            {
                EmissiveMaterial selectionEmissive = new EmissiveMaterial(Brushes.Transparent);
                material.Children.Add(selectionEmissive);
                this.SelectionEmissives.Add(selectionEmissive);
            }

            geometry.Material     = material;
            geometry.BackMaterial = material;

            const double OUTERRADIUS = .045;
            const double INNERRADIUS = .04;

            List <TubeRingBase> rings = new List <TubeRingBase>();

            rings.Add(new TubeRingRegularPolygon(0, false, OUTERRADIUS * 1.75d, OUTERRADIUS * 1.75d, false));           // Start at the base of the barrel
            rings.Add(new TubeRingRegularPolygon(.49, false, OUTERRADIUS * 1.75d, OUTERRADIUS * 1.75d, false));
            rings.Add(new TubeRingRegularPolygon(.02, false, OUTERRADIUS, OUTERRADIUS, false));
            rings.Add(new TubeRingRegularPolygon(.24, false, OUTERRADIUS, OUTERRADIUS, false));
            rings.Add(new TubeRingRegularPolygon(.01, false, OUTERRADIUS * 1.25d, OUTERRADIUS * 1.25d, false));
            rings.Add(new TubeRingRegularPolygon(.08, false, OUTERRADIUS * 1.25d, OUTERRADIUS * 1.25d, false)); // This is the tip of the barrel
            rings.Add(new TubeRingRegularPolygon(0, false, INNERRADIUS, INNERRADIUS, false));                   // Curl to the inside
            rings.Add(new TubeRingRegularPolygon(-.75d, false, INNERRADIUS, INNERRADIUS, false));               // Loop back to the base

            geometry.Geometry = UtilityWPF.GetMultiRingedTube(cylinderSegments, rings, true, false, new TranslateTransform3D(0, 0, -.49d));

            retVal.Children.Add(geometry);

            #endregion

            #region Grapple Pad

            geometry = new GeometryModel3D();
            material = new MaterialGroup();
            diffuse  = new DiffuseMaterial(new SolidColorBrush(WorldColors.GrapplePad_Color));
            this.MaterialBrushes.Add(new MaterialColorProps(diffuse, WorldColors.GrapplePad_Color));
            material.Children.Add(diffuse);
            specular = WorldColors.GrapplePad_Specular;
            this.MaterialBrushes.Add(new MaterialColorProps(specular));
            material.Children.Add(specular);

            if (!isFinal)
            {
                EmissiveMaterial selectionEmissive = new EmissiveMaterial(Brushes.Transparent);
                material.Children.Add(selectionEmissive);
                this.SelectionEmissives.Add(selectionEmissive);
            }

            geometry.Material     = material;
            geometry.BackMaterial = material;

            rings = new List <TubeRingBase>();
            rings.Add(new TubeRingRegularPolygon(0, false, OUTERRADIUS * 2d, OUTERRADIUS * 2d, false));
            rings.Add(new TubeRingRegularPolygon(.1, false, OUTERRADIUS * 4d, OUTERRADIUS * 4d, false));
            rings.Add(new TubeRingDome(.05, false, domeSegments));

            geometry.Geometry = UtilityWPF.GetMultiRingedTube(cylinderSegments, rings, true, false, new TranslateTransform3D(0, 0, .35d));

            retVal.Children.Add(geometry);

            #endregion

            #region Trim

            geometry = new GeometryModel3D();
            material = new MaterialGroup();
            diffuse  = new DiffuseMaterial(new SolidColorBrush(WorldColors.GunTrim_Color));
            this.MaterialBrushes.Add(new MaterialColorProps(diffuse, WorldColors.GunTrim_Color));
            material.Children.Add(diffuse);
            specular = WorldColors.GunTrim_Specular;
            this.MaterialBrushes.Add(new MaterialColorProps(specular));
            material.Children.Add(specular);

            if (!isFinal)
            {
                EmissiveMaterial selectionEmissive = new EmissiveMaterial(Brushes.Transparent);
                material.Children.Add(selectionEmissive);
                this.SelectionEmissives.Add(selectionEmissive);
            }

            geometry.Material     = material;
            geometry.BackMaterial = material;

            geometry.Geometry = UtilityWPF.GetCube(new Point3D(-.095, -.11, -.45), new Point3D(.095, .11, -.15));

            retVal.Children.Add(geometry);

            #endregion

            // Transform
            retVal.Transform = GetTransformForGeometry(isFinal);

            // Exit Function
            return(retVal);
        }
Example #19
0
        public EmissiveMaterialExample()
        {
            // Declare scene objects.
            Viewport3D      myViewport3D    = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;
            // The material property of GeometryModel3D specifies the material applied to the 3D object.
            // In this sample the material applied to the 3D object is made up of two materials layered
            // on top of each other - a DiffuseMaterial (gradient brush) with an EmissiveMaterial
            // layered on top (blue SolidColorBrush). The EmmisiveMaterial alters the appearance of
            // the gradient toward blue.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material that will use the gradient.
            DiffuseMaterial myDiffuseMaterial = new DiffuseMaterial(myHorizontalGradient);

            // Add this gradient to a MaterialGroup.
            MaterialGroup myMaterialGroup = new MaterialGroup();

            myMaterialGroup.Children.Add(myDiffuseMaterial);

            // Define an Emissive Material with a blue brush.
            Color c = new Color();

            c.ScA = 1;
            c.ScB = 255;
            c.ScR = 0;
            c.ScG = 0;
            EmissiveMaterial myEmissiveMaterial = new EmissiveMaterial(new SolidColorBrush(c));

            // Add the Emmisive Material to the Material Group.
            myMaterialGroup.Children.Add(myEmissiveMaterial);

            // Add the composite material to the 3D model.
            myGeometryModel.Material = myMaterialGroup;
            // Apply a transform to the object. In this sample, a rotation transform is applied,
            // rendering the 3D object rotated.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;
            myGeometryModel.Transform    = myRotateTransform3D;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;
            myViewport3D.Children.Add(myModelVisual3D);

            // Apply the viewport to the page so it will be rendered.
            this.Content = myViewport3D;
        }
Example #20
0
        /// <summary>
        /// Copies the rhinoMesh data to a new wpf mesh
        /// </summary>
        /// <param name="rhinoMesh"></param>
        /// <param name="wpfMesh"></param>
        /// <param name="material"></param>
        public static void ConvertRhinotoWpfMesh(Mesh rhinoMesh, MeshGeometry3D wpfMesh, DiffuseMaterial material)
        {
            // Make sure to start afresh
            //wpfMesh = new MeshGeometry3D();
            //material = new DiffuseMaterial();

            //define vertices
            for (int i = 0; i < rhinoMesh.Vertices.Count; i++)
            {
                /* TODO SharpDX update
                 * SharpDX.Vector3 me;
                 * me.X = rhinoMesh.Vertices[i].X;
                 * me.Y = rhinoMesh.Vertices[i].Y;
                 * me.Z = rhinoMesh.Vertices[i].Z;
                 * wpfMesh.Positions.Add(me);
                 */

                wpfMesh.Positions.Add(new Point3D(rhinoMesh.Vertices[i].X, rhinoMesh.Vertices[i].Y, rhinoMesh.Vertices[i].Z));
            }

            //define faces - triangulation only
            for (int i = 0; i < rhinoMesh.Faces.Count; i++)
            {
                wpfMesh.TriangleIndices.Add(rhinoMesh.Faces[i].A);
                wpfMesh.TriangleIndices.Add(rhinoMesh.Faces[i].B);
                wpfMesh.TriangleIndices.Add(rhinoMesh.Faces[i].C);
            }

            // Get colours
            double aveA = 0;
            double aveR = 0;
            double aveG = 0;
            double aveB = 0;

            for (int i = 0; i < rhinoMesh.VertexColors.Count; i++)
            {
                aveA += rhinoMesh.VertexColors[i].A;
                aveR += rhinoMesh.VertexColors[i].R;
                aveG += rhinoMesh.VertexColors[i].G;
                aveB += rhinoMesh.VertexColors[i].B;
            }

            if (rhinoMesh.VertexColors.Count > 0)
            {
                aveA /= rhinoMesh.VertexColors.Count;
                aveR /= rhinoMesh.VertexColors.Count;
                aveG /= rhinoMesh.VertexColors.Count;
                aveB /= rhinoMesh.VertexColors.Count;

                material.Brush = new SolidColorBrush(Color.FromArgb((byte)aveA, (byte)aveR, (byte)aveG, (byte)aveB));
            }

            else
            {
                material.Brush = new SolidColorBrush(Color.FromArgb((byte)220, (byte)51, (byte)188, (byte)188));
            }
        }
Example #21
0
        private void CreateSampleScene()
        {
            _physicallyBasedMaterial = new PhysicallyBasedMaterial();

            // We need to dispose the PhysicallyBasedMaterial when this sample is uloaded
            _disposables.Add(_physicallyBasedMaterial);


            UpdateBaseColor();
            UpdateMetalness();
            UpdateRoughness();

            var normalMapShaderResourceView = GetNormalMapShaderResourceView();

            if (normalMapShaderResourceView != null)
            {
                _physicallyBasedMaterial.SetTextureMap(TextureMapTypes.NormalMap, normalMapShaderResourceView, "bricks_normal.png");
            }

            var ambientOcclusionShaderResourceView = AmbientOcclusionShaderResourceView();

            if (ambientOcclusionShaderResourceView != null)
            {
                _physicallyBasedMaterial.SetTextureMap(TextureMapTypes.AmbientOcclusion, ambientOcclusionShaderResourceView, "bricks_ao.png");
            }



            var wpfMaterial = new DiffuseMaterial(Brushes.Red);

            wpfMaterial.SetUsedDXMaterial(_physicallyBasedMaterial);

            ModelPlaceholder.Content = null;
            ModelPlaceholder.Children.Clear();


            var sphereVisual3D = new Ab3d.Visuals.SphereVisual3D()
            {
                CenterPosition          = new Point3D(40, 12, 0),
                Radius                  = 12,
                Segments                = 50,
                Material                = wpfMaterial,
                FreezeMeshGeometry3D    = false,
                UseCachedMeshGeometry3D = false
            };

            ModelPlaceholder.Children.Add(sphereVisual3D);


            var boxVisual3D = new Ab3d.Visuals.BoxVisual3D()
            {
                CenterPosition          = new Point3D(-40, 10, 0),
                Size                    = new Size3D(20, 20, 20),
                Material                = wpfMaterial,
                FreezeMeshGeometry3D    = false,
                UseCachedMeshGeometry3D = false
            };

            ModelPlaceholder.Children.Add(boxVisual3D);


            var readerObj = new Ab3d.ReaderObj();

            var readModel3D = (GeometryModel3D)readerObj.ReadModel3D(_modelsFolder + "teapot-hires.obj");

            Ab3d.Utilities.ModelUtils.CenterAndScaleModel3D(readModel3D, new Point3D(0, 10, 0), new Size3D(40, 40, 40), true);

            //// This code is called for each GeometryModel3D inside Plane1
            //var tangentVectors = Ab3d.DirectX.Utilities.MeshUtils.CalculateTangentVectors((MeshGeometry3D)readModel3D.Geometry);

            ////// Assign tangent array to the MeshGeometry3D
            //readModel3D.Geometry.SetDXAttribute(DXAttributeType.MeshTangentArray, tangentVectors);



            readModel3D.Material = wpfMaterial;

            //ModelPlaceholder.Content = null;
            ModelPlaceholder.Children.Add(readModel3D.CreateModelVisual3D());



            // Rendering normal (bump) maps require tangent vectors.
            // The following code will generate tangent vectors and assign them to the MeshGeometry3D that form our 3D model.
            // If tangent vectors are not provided, they will be calculated on-demand in the pixel shader (slightly reducing performance).

            Ab3d.Utilities.ModelIterator.IterateGeometryModel3DObjects(ModelPlaceholder, delegate(GeometryModel3D geometryModel3D, Transform3D transform3D)
            {
                // This code is called for each GeometryModel3D inside Plane1
                var tangentVectors = Ab3d.DirectX.Utilities.MeshUtils.CalculateTangentVectors((MeshGeometry3D)geometryModel3D.Geometry);

                // Assign tangent array to the MeshGeometry3D
                geometryModel3D.Geometry.SetDXAttribute(DXAttributeType.MeshTangentArray, tangentVectors);
            });


            Camera1.Distance = 150;

            UpdateLights();
        }
        protected override void BeginTransition3D(
            TransitionElement transitionElement,
            ContentPresenter oldContent,
            ContentPresenter newContent,
            Viewport3D viewport)
        {
            Size size = transitionElement.RenderSize;

            Point   mouse2D = Mouse.GetPosition(transitionElement);
            Point3D mouse   = new Point3D(mouse2D.X, mouse2D.Y, 0.5 * size.Width);

            int xparticles = 10, yparticles = 10;

            if (size.Width > size.Height)
            {
                yparticles = (int)(xparticles * size.Height / size.Width);
            }
            else
            {
                xparticles = (int)(yparticles * size.Width / size.Height);
            }

            double   sx = 1.0 / xparticles, sy = 1.0 / yparticles;
            Vector3D u          = new Vector3D(size.Width * sx, 0, 0);
            Vector3D v          = new Vector3D(0, size.Height * sy, 0);
            Brush    cloneBrush = CreateBrush(oldContent);
            Material clone      = new DiffuseMaterial(cloneBrush);

            Vector3D[] velocities        = new Vector3D[xparticles * yparticles];
            Vector3D[] angularVelocities = new Vector3D[xparticles * yparticles];
            Point3D[]  centers           = new Point3D[xparticles * yparticles];

            Point3DCollection positions = new Point3DCollection(4 * xparticles * yparticles);
            PointCollection   textures  = new PointCollection(4 * xparticles * yparticles);
            Int32Collection   triangles = new Int32Collection(6 * xparticles * yparticles);
            int n = 0;

            for (int i = 0; i < xparticles; i++)
            {
                for (int j = 0; j < yparticles; j++)
                {
                    Point3D topleft = (Point3D)(i * u + j * v);
                    positions.Add(topleft);
                    positions.Add(topleft + u);
                    positions.Add(topleft + u + v);
                    positions.Add(topleft + v);

                    textures.Add(new Point(i * sx, j * sy));
                    textures.Add(new Point((i + 1) * sx, j * sy));
                    textures.Add(new Point((i + 1) * sx, (j + 1) * sy));
                    textures.Add(new Point(i * sx, (j + 1) * sy));


                    triangles.Add(n);
                    triangles.Add(n + 2);
                    triangles.Add(n + 1);

                    triangles.Add(n);
                    triangles.Add(n + 3);
                    triangles.Add(n + 2);

                    Vector3D f0 = positions[n] - mouse;
                    Vector3D f1 = positions[n + 1] - mouse;
                    Vector3D f2 = positions[n + 2] - mouse;
                    Vector3D f3 = positions[n + 3] - mouse;

                    f0 = f0 / f0.LengthSquared;
                    f1 = f1 / f1.LengthSquared;
                    f2 = f2 / f2.LengthSquared;
                    f3 = f3 / f3.LengthSquared;

                    velocities[n / 4] = 2 * size.Width * (f0 + f1 + f2 + f3);

                    Point3D center = centers[n / 4] = (Point3D)((i + 0.5) * u + (j + 0.5) * v);
                    angularVelocities[n / 4] = 200 * (Vector3D.CrossProduct(f0, positions[n] - center) +
                                                      Vector3D.CrossProduct(f1, positions[n + 1] - center) +
                                                      Vector3D.CrossProduct(f2, positions[n + 2] - center) +
                                                      Vector3D.CrossProduct(f3, positions[n + 3] - center));



                    n += 4;
                }
            }

            MeshGeometry3D mesh = new MeshGeometry3D();

            mesh.Positions          = positions;
            mesh.TextureCoordinates = textures;
            mesh.TriangleIndices    = triangles;

            GeometryModel3D geometryModel = new GeometryModel3D(mesh, clone);

            geometryModel.BackMaterial = clone;
            ModelVisual3D model = new ModelVisual3D();

            model.Content = geometryModel;
            viewport.Children.Add(model);



            DispatcherTimer timer        = new DispatcherTimer();
            int             t            = 0;
            double          opacityDelta = 1.0 / (Duration.TimeSpan.Seconds * 60.0);

            timer.Interval = TimeSpan.FromSeconds(1.0 / 60.0);
            timer.Tick    += delegate
            {
                t++;
                cloneBrush.Opacity = 1 - t * opacityDelta;
                if (cloneBrush.Opacity < opacityDelta)
                {
                    timer.Stop();
                    EndTransition(transitionElement, oldContent, newContent);
                    return;
                }
                mesh.Positions = null;
                AxisAngleRotation3D axisAngle = new AxisAngleRotation3D();
                RotateTransform3D   rotation  = new RotateTransform3D(axisAngle, new Point3D());
                for (int i = 0; i < positions.Count; i += 4)
                {
                    Vector3D velocity = velocities[i / 4];



                    axisAngle.Axis   = angularVelocities[i / 4];
                    axisAngle.Angle  = angularVelocities[i / 4].Length;
                    rotation.CenterX = centers[i / 4].X;
                    rotation.CenterY = centers[i / 4].Y;
                    rotation.CenterZ = centers[i / 4].Z;

                    positions[i]     = rotation.Transform(positions[i]) + velocity;
                    positions[i + 1] = rotation.Transform(positions[i + 1]) + velocity;
                    positions[i + 2] = rotation.Transform(positions[i + 2]) + velocity;
                    positions[i + 3] = rotation.Transform(positions[i + 3]) + velocity;


                    centers[i / 4] += velocity;
                }
                mesh.Positions = positions;
            };
            timer.Start();
        }
        // Create a DrawingVisual that contains a 3D object.
        private DrawingVisual Create3DVisualObject()
        {
            // Declare scene objects.

            // The Viewport3DVisual is used instead of the Viewport3D object because this 3D
            // object is drawn directly to the WPF visual layer. Using Viepwor3dVisual can provide
            // performance benefits over using Viewport3D although it does not support many of the
            // features that Viewport3D does.
            Viewport3DVisual myViewport3D    = new Viewport3DVisual();
            Model3DGroup     myModel3DGroup  = new Model3DGroup();
            GeometryModel3D  myGeometryModel = new GeometryModel3D();
            ModelVisual3D    myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object. In this sample a
            // linear gradient covers the surface of the 3D object.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(myHorizontalGradient);

            myGeometryModel.Material = myMaterial;

            // Apply a transform to the object. In this sample, a rotation transform is applied,
            // rendering the 3D object rotated.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;
            myGeometryModel.Transform    = myRotateTransform3D;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;

            // Create a rectangle to view the 3D object in.
            Rect myRectangle = new Rect();

            myRectangle.Location = new Point(10, 5);
            myRectangle.Size     = new Size(900, 900);

            myViewport3D.Children.Add(myModelVisual3D);
            myViewport3D.Viewport = myRectangle;

            DrawingVisual dv = new DrawingVisual();

            dv.Children.Add(myViewport3D);
            return(dv);
        }
Example #24
0
        public StreamLinesSample()
        {
            InitializeComponent();


            // We will set the tube path position color based on the Density
            string colorColumnName  = "Density"; // "AngularVelocity"
            bool   invertColorValue = false;     // This needs to be set to true when using AngularVelocity


            // First create a gradient legend and texture
            var gradientStopCollection = new GradientStopCollection();

            gradientStopCollection.Add(new GradientStop(Colors.Red, 1));
            gradientStopCollection.Add(new GradientStop(Colors.Yellow, 0.75));
            gradientStopCollection.Add(new GradientStop(Colors.Lime, 0.5));
            gradientStopCollection.Add(new GradientStop(Colors.Aqua, 0.25));
            gradientStopCollection.Add(new GradientStop(Colors.Blue, 0));

            var linearGradientBrush = new LinearGradientBrush(gradientStopCollection,
                                                              new System.Windows.Point(0, 1),  // startPoint (offset == 0) - note that y axis is down (so 1 is bottom)
                                                              new System.Windows.Point(0, 0)); // endPoint (offset == 1)

            // Create Legend control
            var gradientColorLegend = new GradientColorLegend()
            {
                Width  = 70,
                Height = 200,
                Margin = new Thickness(5, 5, 5, 5)
            };

            gradientColorLegend.GradientBrush = linearGradientBrush;

            var gradientTexture = gradientColorLegend.RenderToTexture(size: 256, isHorizontal: true);

            var imageBrush = new ImageBrush(gradientTexture);

            // IMPORTANT:
            // When texture coordinates have one components (for example y) always set to 0,
            // we need to change the ViewportUnits from the default RelativeToBoundingBox to Absolute.
            imageBrush.ViewportUnits = BrushMappingMode.Absolute;

            var gradientMaterial = new DiffuseMaterial(imageBrush);


            // Now load sample data
            // Sample data was created by using ParaView application and exporting the streamlines into csv file.
            string sampleDataFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\Streamlines.csv");


            // Create csv file reader that can read data from a csv file
            var csvDataReader = new CsvDataReader();

            csvDataReader.ReadFile(sampleDataFileName);


            float minValue, maxValue;

            csvDataReader.GetValuesRange(colorColumnName, out minValue, out maxValue);

            float dataRange = maxValue - minValue;


            var streamlineIndexes = csvDataReader.IndividualObjectIndexes;


            // Create the streamlines
            var allStreamlineBounds = new Rect3D();

            for (var i = 0; i < csvDataReader.IndividualObjectIndexes.Length - 1; i++)
            {
                Rect3D bounds;

                int startIndex = streamlineIndexes[i];
                int endIndex   = streamlineIndexes[i + 1] - 1;

                int dataCount = endIndex - startIndex;

                if (dataCount < 2) // Skip streamlines without any positions or with less then 2 positions
                {
                    continue;
                }

                var positions = csvDataReader.GetPositions(startIndex, dataCount, out bounds);

                allStreamlineBounds.Union(bounds);

                var pathPositions = new Point3DCollection(positions);


                float[] dataValues = csvDataReader.GetValues(colorColumnName, startIndex, dataCount);

                // Generate texture coordinates for each path position
                // Because our texture is one dimensional gradient image (size 256 x 1)
                // we set the x coordinate in range from 0 to 1 (0 = first gradient color; 1 = last gradient color).
                //
                // Note:
                // If we would only set x texture coordinate and preserve y at 0,
                // WPF would not render the texture because the y size would be 0
                // and because by default the ViewportUnits is set to RelativeToBoundingBox,
                // WPF "thinks" the texture is empty.
                // Therefore we need to set the imageBrush.ViewportUnits to Absolute.
                var positionsCount     = pathPositions.Count;
                var textureCoordinates = new PointCollection(positionsCount);
                for (int j = 0; j < dataCount; j++)
                {
                    float relativeDataValue = (dataValues[j] - minValue) / dataRange;

                    if (invertColorValue)
                    {
                        relativeDataValue = 1.0f - relativeDataValue;
                    }

                    textureCoordinates.Add(new Point(relativeDataValue, 0));
                }


                var tubePathMesh3D = new Ab3d.Meshes.TubePathMesh3D(
                    pathPositions: pathPositions,
                    pathPositionTextureCoordinates: textureCoordinates,
                    radius: 0.03,
                    isTubeClosed: true,
                    isPathClosed: false,
                    segments: 8);


                var geometryModel3D = new GeometryModel3D(tubePathMesh3D.Geometry, gradientMaterial);
                //var geometryModel3D = new GeometryModel3D(tubePathMesh3D.Geometry, new DiffuseMaterial(Brushes.Red));
                geometryModel3D.BackMaterial = new DiffuseMaterial(Brushes.DimGray);

                var modelVisual3D = new ModelVisual3D()
                {
                    Content = geometryModel3D
                };

                MainViewport.Children.Add(modelVisual3D);
            }

            Camera1.TargetPosition = allStreamlineBounds.GetCenterPosition();
            Camera1.Distance       = allStreamlineBounds.GetDiagonalLength();


            // Add legend control:
            int legendValuesCount = 5;

            for (int i = 0; i < legendValuesCount; i++)
            {
                float t        = (float)i / (float)(legendValuesCount - 1);
                float oneValue = minValue + t * (maxValue - minValue);

                string valueLegendText = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0.00}", oneValue);
                gradientColorLegend.LegendLabels.Add(new GradientColorLegend.LegendLabel(t, valueLegendText));
            }


            var legendTitleTextBlock = new TextBlock()
            {
                Text                = colorColumnName,
                FontSize            = 14,
                FontWeight          = FontWeights.Bold,
                Foreground          = Brushes.Black,
                HorizontalAlignment = HorizontalAlignment.Center
            };


            var stackPanel = new StackPanel()
            {
                Orientation         = Orientation.Vertical,
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Right,
                Margin = new Thickness(0, 0, 5, 5)
            };

            stackPanel.Children.Add(legendTitleTextBlock);
            stackPanel.Children.Add(gradientColorLegend);

            RootGrid.Children.Add(stackPanel);
        }
Example #25
0
        public System.Drawing.Image Render(RendererOptions options)
        {
            // The main object model group.
            Model3DGroup group = new Model3DGroup();

            // The camera.
            PerspectiveCamera camera = new PerspectiveCamera();

            Viewport3D viewport = new Viewport3D();

            // Give the camera its initial position.
            camera.FieldOfView = 5.75;
            viewport.Camera    = camera;

            // The camera's current location.

            string textureFilePath = options.TextureFilePath;
            int    size            = (int)options.OutputImageSize;
            double cameraPhi       = ToRadians(options.LatitudeShift);
            double cameraTheta     = ToRadians(options.LongutudeShift);
            double cameraR         = 20;

            // Calculate the camera's position in Cartesian coordinates.
            double y   = cameraR * Math.Sin(cameraPhi);
            double hyp = cameraR * Math.Cos(cameraPhi);
            double x   = hyp * Math.Cos(cameraTheta);
            double z   = hyp * Math.Sin(cameraTheta);

            camera.Position = new Point3D(x, y, z);

            // Look toward the origin.
            camera.LookDirection = new Vector3D(-x, -y, -z);

            // Set the Up direction.
            camera.UpDirection = new Vector3D(0, 1, 0);

            // Define lights.
            AmbientLight ambientLight = new AmbientLight(Colors.White);

            group.Children.Add(ambientLight);

            // Create the model.
            // Globe. Place it in a new model so we can transform it.
            Model3DGroup globe = new Model3DGroup();

            group.Children.Add(globe);

            ImageBrush globeBrush    = new ImageBrush(new BitmapImage(new Uri(textureFilePath, UriKind.RelativeOrAbsolute)));
            Material   globeMaterial = new DiffuseMaterial(globeBrush);

            MakeSphere(globe, globeMaterial, 1, 0, 0, 0, 64, 64);

            // Add the group of models to a ModelVisual3D.
            ModelVisual3D visual = new ModelVisual3D();

            visual.Content = group;

            // Display the main visual to the viewport.
            viewport.Children.Add(visual);

            viewport.Width  = size;
            viewport.Height = size;
            viewport.Measure(new System.Windows.Size(size, size));
            viewport.Arrange(new System.Windows.Rect(0, 0, size, size));
            viewport.InvalidateVisual();

            if (targetBitmap == null)
            {
                targetBitmap = new RenderTargetBitmap(size, size, 96, 96, PixelFormats.Pbgra32);
            }

            targetBitmap.Clear();
            targetBitmap.Render(viewport);

            return(ToWinFormsBitmap(targetBitmap));
        }
Example #26
0
        private Model3DGroup Initialize_Environment(List <string> modelsNames)
        {
            try
            {
                ModelImporter import = new ModelImporter();
                joints = new List <Joint>();

                foreach (string modelName in modelsNames)
                {
                    var              materialGroup = new MaterialGroup();
                    Color            mainColor     = Colors.White;
                    EmissiveMaterial emissMat      = new EmissiveMaterial(new SolidColorBrush(mainColor));
                    DiffuseMaterial  diffMat       = new DiffuseMaterial(new SolidColorBrush(mainColor));
                    SpecularMaterial specMat       = new SpecularMaterial(new SolidColorBrush(mainColor), 200);
                    materialGroup.Children.Add(emissMat);
                    materialGroup.Children.Add(diffMat);
                    materialGroup.Children.Add(specMat);

                    var             link  = import.Load(basePath + modelName);
                    GeometryModel3D model = link.Children[0] as GeometryModel3D;
                    model.Material     = materialGroup;
                    model.BackMaterial = materialGroup;
                    joints.Add(new Joint(link));
                }

                RA.Children.Add(joints[0].model);
                RA.Children.Add(joints[1].model);
                RA.Children.Add(joints[2].model);
                RA.Children.Add(joints[3].model);
                RA.Children.Add(joints[4].model);
                RA.Children.Add(joints[5].model);
                RA.Children.Add(joints[6].model);
                RA.Children.Add(joints[7].model);
                RA.Children.Add(joints[8].model);
                RA.Children.Add(joints[9].model);
                RA.Children.Add(joints[10].model);
#if IRB6700
                RA.Children.Add(joints[11].model);
                RA.Children.Add(joints[12].model);
                RA.Children.Add(joints[13].model);
                RA.Children.Add(joints[14].model);
                RA.Children.Add(joints[15].model);
                RA.Children.Add(joints[16].model);
                RA.Children.Add(joints[17].model);
                RA.Children.Add(joints[18].model);
                RA.Children.Add(joints[19].model);
#endif

#if IRB6700
                Color cableColor = Colors.DarkSlateGray;
                changeModelColor(joints[6], cableColor);
                changeModelColor(joints[7], cableColor);
                changeModelColor(joints[8], cableColor);
                changeModelColor(joints[9], cableColor);
                changeModelColor(joints[10], cableColor);
                changeModelColor(joints[11], cableColor);
                changeModelColor(joints[12], cableColor);
                changeModelColor(joints[13], cableColor);

                changeModelColor(joints[14], Colors.Gray);

                changeModelColor(joints[15], Colors.Red);
                changeModelColor(joints[16], Colors.Red);
                changeModelColor(joints[17], Colors.Red);

                changeModelColor(joints[18], Colors.Gray);
                changeModelColor(joints[19], Colors.Gray);

                joints[0].angleMin  = -180;
                joints[0].angleMax  = 180;
                joints[0].rotAxisX  = 0;
                joints[0].rotAxisY  = 0;
                joints[0].rotAxisZ  = 1;
                joints[0].rotPointX = 0;
                joints[0].rotPointY = 0;
                joints[0].rotPointZ = 0;

                joints[1].angleMin  = -100;
                joints[1].angleMax  = 60;
                joints[1].rotAxisX  = 0;
                joints[1].rotAxisY  = 1;
                joints[1].rotAxisZ  = 0;
                joints[1].rotPointX = 348;
                joints[1].rotPointY = -243;
                joints[1].rotPointZ = 775;

                joints[2].angleMin  = -90;
                joints[2].angleMax  = 90;
                joints[2].rotAxisX  = 0;
                joints[2].rotAxisY  = 1;
                joints[2].rotAxisZ  = 0;
                joints[2].rotPointX = 347;
                joints[2].rotPointY = -376;
                joints[2].rotPointZ = 1923;

                joints[3].angleMin  = -180;
                joints[3].angleMax  = 180;
                joints[3].rotAxisX  = 1;
                joints[3].rotAxisY  = 0;
                joints[3].rotAxisZ  = 0;
                joints[3].rotPointX = 60;
                joints[3].rotPointY = 0;
                joints[3].rotPointZ = 2125;

                joints[4].angleMin  = -115;
                joints[4].angleMax  = 115;
                joints[4].rotAxisX  = 0;
                joints[4].rotAxisY  = 1;
                joints[4].rotAxisZ  = 0;
                joints[4].rotPointX = 1815;
                joints[4].rotPointY = 0;
                joints[4].rotPointZ = 2125;

                joints[5].angleMin  = -180;
                joints[5].angleMax  = 180;
                joints[5].rotAxisX  = 1;
                joints[5].rotAxisY  = 0;
                joints[5].rotAxisZ  = 0;
                joints[5].rotPointX = 2008;
                joints[5].rotPointY = 0;
                joints[5].rotPointZ = 2125;
#else
                changeModelColor(joints[6], Colors.Red);
                changeModelColor(joints[7], Colors.Black);
                changeModelColor(joints[8], Colors.Black);
                changeModelColor(joints[9], Colors.Black);
                changeModelColor(joints[10], Colors.Gray);

                RA.Children.Add(joints[0].model);
                RA.Children.Add(joints[1].model);
                RA.Children.Add(joints[2].model);
                RA.Children.Add(joints[3].model);
                RA.Children.Add(joints[4].model);
                RA.Children.Add(joints[5].model);
                RA.Children.Add(joints[6].model);
                RA.Children.Add(joints[7].model);
                RA.Children.Add(joints[8].model);
                RA.Children.Add(joints[9].model);
                RA.Children.Add(joints[10].model);

                joints[0].angleMin  = -180;
                joints[0].angleMax  = 180;
                joints[0].rotAxisX  = 0;
                joints[0].rotAxisY  = 0;
                joints[0].rotAxisZ  = 1;
                joints[0].rotPointX = 0;
                joints[0].rotPointY = 0;
                joints[0].rotPointZ = 0;

                joints[1].angleMin  = -100;
                joints[1].angleMax  = 60;
                joints[1].rotAxisX  = 0;
                joints[1].rotAxisY  = 1;
                joints[1].rotAxisZ  = 0;
                joints[1].rotPointX = 175;
                joints[1].rotPointY = -200;
                joints[1].rotPointZ = 500;

                joints[2].angleMin  = -90;
                joints[2].angleMax  = 90;
                joints[2].rotAxisX  = 0;
                joints[2].rotAxisY  = 1;
                joints[2].rotAxisZ  = 0;
                joints[2].rotPointX = 190;
                joints[2].rotPointY = -700;
                joints[2].rotPointZ = 1595;

                joints[3].angleMin  = -180;
                joints[3].angleMax  = 180;
                joints[3].rotAxisX  = 1;
                joints[3].rotAxisY  = 0;
                joints[3].rotAxisZ  = 0;
                joints[3].rotPointX = 400;
                joints[3].rotPointY = 0;
                joints[3].rotPointZ = 1765;

                joints[4].angleMin  = -115;
                joints[4].angleMax  = 115;
                joints[4].rotAxisX  = 0;
                joints[4].rotAxisY  = 1;
                joints[4].rotAxisZ  = 0;
                joints[4].rotPointX = 1405;
                joints[4].rotPointY = 50;
                joints[4].rotPointZ = 1765;

                joints[5].angleMin  = -180;
                joints[5].angleMax  = 180;
                joints[5].rotAxisX  = 1;
                joints[5].rotAxisY  = 0;
                joints[5].rotAxisZ  = 0;
                joints[5].rotPointX = 1405;
                joints[5].rotPointY = 0;
                joints[5].rotPointZ = 1765;
#endif
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception Error:" + e.StackTrace);
            }
            return(RA);
        }
Example #27
0
        // Process the models.
        private void ProcessModels(bool invertTextures, bool zIsUp)
        {
            // Make the dictionary of materials.
            foreach (ObjMaterial material in AllMaterials)
            {
                // Make the material's MaterialGroup.
                material.MatGroup = new MaterialGroup();

                // Transparency. (Not used.)
                byte alpha = (byte)(material.Alpha * 255);

                // Diffuse.
                byte            diffR     = (byte)(material.Kd.X * 255);
                byte            diffG     = (byte)(material.Kd.Y * 255);
                byte            diffB     = (byte)(material.Kd.Z * 255);
                Color           diffColor = Color.FromArgb(255, diffR, diffG, diffB);
                SolidColorBrush diffBrush = new SolidColorBrush(diffColor);
                DiffuseMaterial diffMat   = new DiffuseMaterial(diffBrush);
                material.MatGroup.Children.Add(diffMat);

                // If it has a file, use it.
                if (material.Filename != null)
                {
                    // Use the file.
                    string     filename = material.Filename;
                    ImageBrush imgBrush = new ImageBrush();
                    imgBrush.ViewportUnits = BrushMappingMode.Absolute;
                    imgBrush.TileMode      = TileMode.Tile;

                    // Invert the texture if necessary.
                    if (invertTextures)
                    {
                        TransformGroup trans = new TransformGroup();
                        trans.Children.Add(new ScaleTransform(1, -1));
                        trans.Children.Add(new TranslateTransform(0, 1));
                        imgBrush.Transform = trans;
                    }

                    imgBrush.ImageSource = new BitmapImage(new Uri(filename, UriKind.Relative));
                    DiffuseMaterial imgMat = new DiffuseMaterial(imgBrush);
                    material.MatGroup.Children.Add(imgMat);
                }

                // Specular.
                byte             specR     = (byte)(material.Ks.X * 255);
                byte             specG     = (byte)(material.Ks.Y * 255);
                byte             specB     = (byte)(material.Ks.Z * 255);
                Color            specColor = Color.FromArgb(255, specR, specG, specB);
                SolidColorBrush  specBrush = new SolidColorBrush(specColor);
                SpecularMaterial specMat   = new SpecularMaterial(specBrush, material.Ns);
                material.MatGroup.Children.Add(specMat);

                // We ignore Ka and Tr.

                // Add it to the materials dictionary.
                MtlMaterials.Add(material.Name, material);
            }

            // Convert the object models into meshes.
            foreach (ObjModel model in AllObjectModels)
            {
                // Make the mesh.
                MeshGeometry3D mesh = new MeshGeometry3D();
                Meshes.Add(mesh);
                MeshNames.Add(model.Name);
                MaterialNames.Add(model.MaterialName);

                // Make a new list of smoothing groups.
                Dictionary <int, Dictionary <Point3D, int> > smoothingGroups =
                    new Dictionary <int, Dictionary <Point3D, int> >();

                // Entry 0 is null (no smoothing).
                smoothingGroups.Add(0, null);

                // Make the faces.
                foreach (ObjFace face in model.Faces)
                {
                    // Make the face's vertices.
                    int       numPoints = face.Vertices.Count;
                    Point3D[] points    = new Point3D[numPoints];
                    for (int i = 0; i < numPoints; i++)
                    {
                        points[i] = AllVertices[face.Vertices[i] - 1];
                    }

                    // Get texture coordinates if present.
                    Point[] textureCoords = null;
                    if (face.TextureCoords.Count > 0)
                    {
                        textureCoords = new Point[numPoints];
                        for (int i = 0; i < numPoints; i++)
                        {
                            textureCoords[i] = AllTextureCoordinates[face.TextureCoords[i] - 1];
                        }
                    }

                    // Get normals if present.
                    Vector3D[] normals = null;
                    if (face.Normals.Count > 0)
                    {
                        normals = new Vector3D[numPoints];
                        for (int i = 0; i < numPoints; i++)
                        {
                            normals[i] = AllNormals[face.Normals[i] - 1];
                        }
                    }

                    // Get the point dictionary for this smoothing group.
                    // Add new groups if needed.
                    if (!smoothingGroups.ContainsKey(face.SmoothingGroup))
                    {
                        smoothingGroups.Add(face.SmoothingGroup,
                                            new Dictionary <Point3D, int>());
                    }
                    Dictionary <Point3D, int> pointDict = smoothingGroups[face.SmoothingGroup];

                    // Make the polygon.
                    mesh.AddPolygon(pointDict: pointDict,
                                    textureCoords: textureCoords, normals: normals,
                                    points: points);
                }

                // If Z is up, rotate the model.
                if (zIsUp)
                {
                    mesh.ApplyTransformation(D3.Rotate(D3.XVector(), D3.Origin, -90));
                }
            }
        }
Example #28
0
        public static GeometryModel3D bitmapText(string _text, Brush textColor, bool isDoubleSided, double height, Point3D center, Vector3D textDirection, Vector3D updirection)
        {
            //Image myImage = new Image();
            FormattedText text = new FormattedText(_text,
                                                   new CultureInfo("en-us"),
                                                   FlowDirection.LeftToRight,
                                                   new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, new FontStretch()),
                                                   height,
                                                   textColor);

            DrawingVisual  drawingVisual  = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            drawingContext.DrawText(text, new Point(0, 0));
            drawingContext.Close();

            // We just assume the characters are square
            double width   = _text.Length * height * 0.6;
            int    _height = Convert.ToInt32(Math.Floor(height));
            int    _width  = Convert.ToInt32(Math.Floor(width));

            if (_height == 0)
            {
                _height = 1;
            }
            if (_width == 0)
            {
                _width = 1;
            }

            RenderTargetBitmap bmp = new RenderTargetBitmap(_width, _height, 240, 192, PixelFormats.Pbgra32);

            bmp.Render(drawingVisual);
            //myImage.Source = bmp;



            // Now use that TextBlock as the brush for a material
            var mat = new DiffuseMaterial {
                Brush = new ImageBrush(bmp)
                {
                    Viewport = new Rect(0, 0, 1, 1), Stretch = Stretch.Fill
                }
            };


            // tb.Measure(new Size(text.Length * height * 2, height * 2));
            // width=tb.DesiredSize.Width;

            // Since the parameter coming in was the center of the label,
            // we need to find the four corners
            // p0 is the lower left corner
            // p1 is the upper left
            // p2 is the lower right
            // p3 is the upper right
            var p0 = center - width / 2 * textDirection - height / 2 * updirection;
            var p1 = p0 + updirection * 1 * height;
            var p2 = p0 + textDirection * width;
            var p3 = p0 + updirection * 1 * height + textDirection * width;

            // Now build the geometry for the sign.  It's just a
            // rectangle made of two triangles, on each side.
            var mg = new MeshGeometry3D {
                Positions = new Point3DCollection {
                    p0, p1, p2, p3
                }
            };

            if (isDoubleSided)
            {
                mg.Positions.Add(p0); // 4
                mg.Positions.Add(p1); // 5
                mg.Positions.Add(p2); // 6
                mg.Positions.Add(p3); // 7
            }

            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(3);
            mg.TriangleIndices.Add(1);
            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(2);
            mg.TriangleIndices.Add(3);

            if (isDoubleSided)
            {
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(5);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(6);
            }

            // These texture coordinates basically stretch the
            // TextBox brush to cover the full side of the label.
            mg.TextureCoordinates.Add(new Point(0, 1));
            mg.TextureCoordinates.Add(new Point(0, 0));
            mg.TextureCoordinates.Add(new Point(1, 1));
            mg.TextureCoordinates.Add(new Point(1, 0));

            if (isDoubleSided)
            {
                mg.TextureCoordinates.Add(new Point(1, 1));
                mg.TextureCoordinates.Add(new Point(1, 0));
                mg.TextureCoordinates.Add(new Point(0, 1));
                mg.TextureCoordinates.Add(new Point(0, 0));
            }

            // And that's all.  Return the result.
            return(new GeometryModel3D(mg, mat));
        }
Example #29
0
        /// <summary>
        /// Creates a ModelVisual3D containing a text label. <see cref="http://www.ericsink.com/wpf3d/4_Text.html"/>
        /// </summary>
        /// <param name="text">The string</param>
        /// <param name="textColor">The color of the text.</param>
        /// <param name="bDoubleSided">Visible from both sides?</param>
        /// <param name="height">Height of the characters</param>
        /// <param name="center">The center of the label</param>
        /// <param name="over">Horizontal direction of the label</param>
        /// <param name="up">Vertical direction of the label</param>
        /// <returns>Suitable for adding to your Viewport3D</returns>
        public static ModelVisual3D CreateTextLabel3D(
            string text,
            Brush textColor,
            bool bDoubleSided,
            double maxWidth,
            double maxHeight,
            Point3D center,
            Vector3D over,
            Vector3D up)
        {
            // Initiate textblock containing the text of the label
            TextBlock tb = new TextBlock(new Run(text));

            tb.Foreground = textColor;
            tb.FontFamily = new FontFamily("Arial");

            // Use that TextBlock as the brush for a material
            DiffuseMaterial mat = new DiffuseMaterial();

            mat.Brush = new VisualBrush(tb);

            // Assume the characters are square
            double width;
            double height;

            if (text.Length * maxHeight < maxWidth)
            {
                height = maxHeight;
                width  = text.Length * maxHeight;
            }
            else
            {
                height = maxWidth / text.Length;
                width  = maxWidth;
            }

            // Find the four corners
            // p0 is the lower left corner
            // p1 is the upper left
            // p2 is the lower right
            // p3 is the upper right
            Point3D p0 = center - width / 2 * over - height / 2 * up;
            Point3D p1 = p0 + up * 1 * height;
            Point3D p2 = p0 + over * width;
            Point3D p3 = p0 + up * 1 * height + over * width;

            // Now build the geometry for the sign.  It's just a rectangle made of two triangles, on each side.
            MeshGeometry3D mg = new MeshGeometry3D();

            mg.Positions = new Point3DCollection();
            mg.Positions.Add(p0);    // 0
            mg.Positions.Add(p1);    // 1
            mg.Positions.Add(p2);    // 2
            mg.Positions.Add(p3);    // 3

            if (bDoubleSided)
            {
                mg.Positions.Add(p0);    // 4
                mg.Positions.Add(p1);    // 5
                mg.Positions.Add(p2);    // 6
                mg.Positions.Add(p3);    // 7
            }

            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(3);
            mg.TriangleIndices.Add(1);
            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(2);
            mg.TriangleIndices.Add(3);

            if (bDoubleSided)
            {
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(5);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(6);
            }

            // These texture coordinates basically stretch the TextBox brush to cover the full side of the label.
            mg.TextureCoordinates.Add(new Point(0, 1));
            mg.TextureCoordinates.Add(new Point(0, 0));
            mg.TextureCoordinates.Add(new Point(1, 1));
            mg.TextureCoordinates.Add(new Point(1, 0));

            if (bDoubleSided)
            {
                mg.TextureCoordinates.Add(new Point(1, 1));
                mg.TextureCoordinates.Add(new Point(1, 0));
                mg.TextureCoordinates.Add(new Point(0, 1));
                mg.TextureCoordinates.Add(new Point(0, 0));
            }

            // That's all.  Return the result.
            ModelVisual3D mv3d = new ModelVisual3D();

            mv3d.Content = new GeometryModel3D(mg, mat);;
            return(mv3d);
        }
Example #30
0
        private void drawFrameAxis(int kinectIndex)
        {
            if ((bool)parentGUI.show3DCheck.IsChecked)
            {
                Box3D           kinectBox = new Box3D();
                DiffuseMaterial material  = new DiffuseMaterial(Brushes.Black);
                kinectBox.Material = material;

                Transform3DGroup t = new Transform3DGroup();
                double           l = 0.2, w = 0.03, h = 0.03;
                t.Children.Add(new ScaleTransform3D(l, w, h));
                t.Children.Add(new TranslateTransform3D(new Vector3D(-l / 2, -w / 2, -h / 2))); //new Vector3D(height*GUIComponents.synchyList[i].zPar.X, GUIComponents.synchyList[i].zPar.Y, GUIComponents.synchyList[i].zPar.Z)));


                Point3D origin = new Point3D(0, 0, 0);
                Point3D x_unit = new Point3D(1, 0, 0);
                Point3D y_unit = new Point3D(0, 1, 0);
                Point3D z_unit = new Point3D(0, 0, 1);


                KinectData kp = new KinectData();

                origin = kp.transformPointto(origin, transfMatrix[kinectIndex]);
                x_unit = kp.transformPointto(x_unit, transfMatrix[kinectIndex]);
                y_unit = kp.transformPointto(y_unit, transfMatrix[kinectIndex]);
                z_unit = kp.transformPointto(z_unit, transfMatrix[kinectIndex]);

                Vector3D x = new Vector3D(x_unit.X - origin.X, x_unit.Y - origin.Y, x_unit.Z - origin.Z);
                Vector3D y = new Vector3D(y_unit.X - origin.X, y_unit.Y - origin.Y, y_unit.Z - origin.Z);
                Vector3D z = new Vector3D(z_unit.X - origin.X, z_unit.Y - origin.Y, z_unit.Z - origin.Z);

                x.Normalize();
                y.Normalize();
                z.Normalize();
                Vector3D X = new Vector3D(1, 0, 0);
                Vector3D Y = new Vector3D(0, 1, 0);
                Vector3D Z = new Vector3D(0, 0, 1);

                if (kinectIndex != 0)
                {
                    double rad2Deg = 180 / Math.PI;
                    //use z-N-Z Euler Angle rotation
                    Vector3D N = Vector3D.CrossProduct(new Vector3D(0, 0, 1), z);
                    N.Normalize();
                    double Z1 = z.X; // Vector3D.DotProduct(Z, x);
                    double Z2 = z.Y; // Vector3D.DotProduct(Z, y);
                    double Z3 = z.Z; // Vector3D.DotProduct(Z, z);
                    double X3 = x.Z; // Vector3D.DotProduct(X, z);
                    double Y3 = y.Z; // Vector3D.DotProduct(Y, z);

                    t.Children.Add(new RotateTransform3D(
                                       new AxisAngleRotation3D(
                                           Z,
                                           rad2Deg * Math.Atan2(Z1, -Z2)//Math.Acos(-z.Y / Math.Sqrt(1 - Math.Pow(z.Z, 2)))
                                           )));
                    //rotate around y
                    t.Children.Add(new RotateTransform3D(
                                       new AxisAngleRotation3D(N,
                                                               rad2Deg * Math.Acos(Z3))));
                    //rotate around z
                    t.Children.Add(new RotateTransform3D(
                                       new AxisAngleRotation3D(z,
                                                               rad2Deg * Math.Atan2(X3, Y3)//Math.Acos(y.Z / Math.Sqrt(1 - Math.Pow(z.Z, 2))))));
                                                               )));

                    t.Children.Add(new TranslateTransform3D(new Vector3D(origin.X, origin.Y, origin.Z)));
                }
                kinectBox.Transform = t;
                show_viewport3D.Children.Add(kinectBox);


                ScreenSpaceLines3D Vz = new ScreenSpaceLines3D();
                int    width          = 2;
                double factor         = 0.15;
                Vz.Points.Add(origin);
                Vz.Points.Add(new Point3D(z.X * factor + origin.X, z.Y * factor + origin.Y, z.Z * factor + origin.Z));
                Vz.Thickness = width;
                Vz.Color     = Colors.Red;
                show_viewport3D.Children.Add(Vz);
            }

            else
            {
                ScreenSpaceLines3D x = new ScreenSpaceLines3D();
                ScreenSpaceLines3D y = new ScreenSpaceLines3D();
                ScreenSpaceLines3D z = new ScreenSpaceLines3D();
                int    width         = 3;
                double factor        = 0.2;
                //    Color c = Colors.Violet;
                x.Thickness = width;
                x.Color     = Colors.Black;
                y.Thickness = width;
                y.Color     = Colors.Blue;
                z.Thickness = width;
                z.Color     = Colors.Red;

                Point3D origin = new Point3D(0, 0, 0);
                Point3D x_unit = new Point3D(factor, 0, 0);
                Point3D y_unit = new Point3D(0, factor, 0);
                Point3D z_unit = new Point3D(0, 0, factor);


                KinectData kp = new KinectData();

                origin = kp.transformPointto(origin, transfMatrix[kinectIndex]);
                x_unit = kp.transformPointto(x_unit, transfMatrix[kinectIndex]);
                y_unit = kp.transformPointto(y_unit, transfMatrix[kinectIndex]);
                z_unit = kp.transformPointto(z_unit, transfMatrix[kinectIndex]);


                /*
                 * x_unit = new Point3D(x_unit.X - origin.X, x_unit.Y - origin.Y, x_unit.Z - origin.Z);
                 * y_unit = new Point3D(y_unit.X - origin.X, y_unit.Y - origin.Y, y_unit.Z - origin.Z);
                 * z_unit = new Point3D(z_unit.X - origin.X, z_unit.Y - origin.Y, z_unit.Z - origin.Z);
                 * origin = new Point3D(0, 0, 0);
                 */
                x.Points.Add(origin);
                x.Points.Add(x_unit);

                y.Points.Add(origin);
                y.Points.Add(y_unit);

                z.Points.Add(origin);
                z.Points.Add(z_unit);

                this.show_viewport3D.Children.Add(x);
                this.show_viewport3D.Children.Add(y);
                this.show_viewport3D.Children.Add(z);
            }
        }
Example #31
0
        /// <summary>
        /// Generates triangle from 3 points.
        /// </summary>
        /// <param name="p0">A Kit3D.Windows.Media.Media3D.Point3D that specifies
        /// 3D point for visualization component.</param>
        /// <param name="p1">A Kit3D.Windows.Media.Media3D.Point3D that specifies
        /// 3D point for visualization component.</param>
        /// <param name="p2">A Kit3D.Windows.Media.Media3D.Point3D that specifies
        /// 3D point for visualization component.</param>
        /// <returns>A Kit3D.Windows.Media.Media3D.Model3DGroup that specifies
        /// trianle of triangle.</returns>
        private Model3DGroup CreateTriangleModel(Point3D p0, Point3D p1, Point3D p2)
        {
            MeshGeometry3D mesh = new MeshGeometry3D();
            mesh.Positions.Add(p0);
            mesh.Positions.Add(p1);
            mesh.Positions.Add(p2);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(2);
            mesh.TextureCoordinates.Add(new Point(1, 1));
            mesh.TextureCoordinates.Add(new Point(1, 0));
            mesh.TextureCoordinates.Add(new Point(0, 1));
            Material material = new DiffuseMaterial(new Kit3DBrush(
                new SolidColorBrush(CalculateColor(CalculateNormal(p0, p1, p2)))));
            GeometryModel3D model = new GeometryModel3D(
                mesh, material);
            Model3DGroup group = new Model3DGroup();
            group.Children.Add(model);

            return group;
        }