/// <summary>
        /// Constructor of the MainViewModel
        /// Sets up allProperties
        /// </summary>
        public MainViewModel(Size2 pcSize)
        {
            Size = pcSize;
            // Render Setup
            EffectsManager  = new DefaultEffectsManager();
            RenderTechnique = EffectsManager[DefaultRenderTechniqueNames.Blinn];

            // Window Setup
            this.Title    = "Point Cloud";
            this.SubTitle = null;

            // Camera Setup
            this.Camera = new HelixToolkit.Wpf.SharpDX.PerspectiveCamera
            {
                Position      = new Point3D(0, 3, -3),
                LookDirection = new Vector3D(0, -1, 4),
                UpDirection   = new Vector3D(0, 1, 0)
            };
            this.Camera.LookAt(new Point3D(0, 0, 0), 0);

            // Lines Setup
            this.LineThickness          = 1;
            this.TriangulationThickness = .5;
            this.ShowTriangleLines      = true;

            // Lighting Setup
            this.AmbientLightColor         = System.Windows.Media.Colors.White;
            this.DirectionalLightColor     = Color.White;
            this.DirectionalLightDirection = new Vector3(0, -1, 0);

            // Model Materials and Colors
            this.Material = PhongMaterials.PolishedBronze;


            // Grid Setup
            int GRID_SIZE            = 10;
            int GRID_LONG_RANGE_SIZE = 40;
            var gridTransform        = new Transform3DGroup();

            gridTransform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), 90)));
            gridTransform.Children.Add(new TranslateTransform3D(-GRID_SIZE / 2, -0.01, -GRID_SIZE / 2));
            GridTransform = gridTransform;

            // Major
            LineBuilder lb = new LineBuilder();

            lb.AddGrid(BoxFaces.Bottom, 11, 11, GRID_SIZE, GRID_SIZE);
            this.GridMajor = lb.ToLineGeometry3D();
            this.GridColor = System.Windows.Media.Color.FromArgb(15, 200, 200, 200);

            // Minor
            lb = new LineBuilder();
            lb.AddGrid(BoxFaces.Bottom, 101, 101, GRID_SIZE, GRID_SIZE);
            this.GridMinor = lb.ToLineGeometry3D();

            // Long range
            lb = new LineBuilder();
            lb.AddGrid(BoxFaces.Bottom, GRID_LONG_RANGE_SIZE + 1, GRID_LONG_RANGE_SIZE + 1, GRID_LONG_RANGE_SIZE, GRID_LONG_RANGE_SIZE);
            this.GridLongRange = lb.ToLineGeometry3D();
            GridLRTransform    = new TranslateTransform3D(-(GRID_LONG_RANGE_SIZE - GRID_SIZE) / 2, -(GRID_LONG_RANGE_SIZE - GRID_SIZE) / 2, 0);

            // Long range major
            lb = new LineBuilder();
            lb.AddGrid(BoxFaces.Bottom, GRID_LONG_RANGE_SIZE / 5 + 1, GRID_LONG_RANGE_SIZE / 5 + 1, GRID_LONG_RANGE_SIZE, GRID_LONG_RANGE_SIZE);
            this.GridLongRangeMajor = lb.ToLineGeometry3D();


            lb = new LineBuilder();
            lb.AddLine(new Vector3(0, 0, 0), new Vector3(GRID_SIZE / 2, 0, 0));
            this.XAxis = lb.ToLineGeometry3D();

            lb = new LineBuilder();
            lb.AddLine(new Vector3(0, 0, 0), new Vector3(0, GRID_SIZE / 2, 0));
            this.YAxis = lb.ToLineGeometry3D();

            lb = new LineBuilder();
            lb.AddLine(new Vector3(0, 0, 0), new Vector3(0, 0, GRID_SIZE / 2));
            this.ZAxis = lb.ToLineGeometry3D();

            var mb = new MeshBuilder();

            mb.AddSphere(new Vector3(0, 0, 0), 0.05);
            this.Origin = mb.ToMeshGeometry3D();

            OriginMaterial = new PhongMaterial()
            {
                AmbientColor      = System.Windows.Media.Colors.Gray.ToColor4(),
                DiffuseColor      = System.Windows.Media.Colors.Yellow.ToColor4(),
                SpecularColor     = System.Windows.Media.Colors.White.ToColor4(),
                SpecularShininess = 100f,
            };



            PointCloud           = new PointGeometry3D();
            PointCloud.IsDynamic = true;
            InitPointCloud(Color4Extensions.FromArgb(255, 0, 0));
        }
Example #2
0
        public void DetermineCollission(ref double offsetX, ref double offsetY, ref GeometryModel3D ball, ref TranslateTransform3D movementBall, List <Wall> wallList)
        {
            double radius        = ball.Bounds.SizeX / 2;
            double futureOffsetX = movementBall.OffsetX + offsetX;
            double futureOffsetY = movementBall.OffsetY + offsetY;

            foreach (Wall wall in wallList)
            {
                double distanceToWallY = Math.Abs(wall.wallY - futureOffsetY);
                double distanceToWallX = Math.Abs(wall.wallX - futureOffsetX);
                if (distanceToWallX - radius <= (wall.xWidth / 2) && distanceToWallY - radius <= (wall.yWidth / 2))
                {
                    if (distanceToWallX <= wall.xWidth / 2)
                    {
                        speedY  = -1 * (speedY / BOUNCE);
                        offsetY = 0;
                    }
                    else if (distanceToWallY <= wall.yWidth / 2)
                    {
                        speedX  = -1 * (speedX / BOUNCE);
                        offsetX = 0;
                    }
                    else
                    {
                        //Corner detection
                    }
                }
            }
        }
Example #3
0
 public box(RotateTransform3D _R, TranslateTransform3D _T)
 {
     R = _R;
     T = _T;
 }
Example #4
0
        public WireframeSample()
        {
            InitializeComponent();

            DXDiagnostics.IsCollectingStatistics = true;

            // Subscribe to DXSceneInitialized event
            // In the handler we will get the SceneNodes that are used in DXEngine to show WireframeVisual3D objects
            // This way we will be able to set some additional properties to DXEngine objects
            MainDXViewportView.DXSceneInitialized += (sender, e) => OnDXSceneViewInitialized();

            // Instead of subscribing to DXSceneInitialized event we could also manually call InitializeScene (the call is commented below) to create the SceneNode.
            // But this solution is slightly less efficient because at the time of initialization the size of the DXSceneView is not known (this means that the back buffers will not be initialized yet)
            // If we no not manually call InitializeScene, than this method will be called in the Loaded event of the DXSceneView.
            // MainViewportView.InitializeScene();

            if (DirectX.Client.Settings.DXEngineSettings.Current.UseDirectXOverlay)
            {
                Scene2Border.Margin = new Thickness(0, 0, RightSideBorder.Width, 0); // When using DirectX overlay add right margin so the WPF controls are visible (they cannot be added on top of overlayed DirectX host control)
            }
            DepthBiasInfoImage.ToolTip =
                @"DepthBias is a property that is available only when using DXEngine
(not available on WPF's WireframeVisual3D) and specify a bias (offset)
to the depth values used by DirectX.
This helps to show the wireframe on top of the solid model.
The values are specified in a local coordinate system.";


            FillWireframeTypesPanel();

            // PersonModel and HouseWithTreesModel are defined in App.xaml
            var houseWithTreesModel = this.FindResource("HouseWithTreesModel") as Model3D;

            //houseWithTreesModel = Ab3d.Reader3ds.Read(@"D:\Wpf\my 3d objects\from emails\Cadian errors\3ds files\err40.3ds");

            SceneModel1.Content = houseWithTreesModel;
            HouseWithThreesWireframeVisual.OriginalModel = houseWithTreesModel;


            var originalPersonModel = this.FindResource("PersonModel") as Model3D;

            // originalPersonModel is frozen so its Transform cannot be changed - therefore we create a new _personModel that could be changed
            _personModel = new Model3DGroup();
            _personModel.Children.Add(originalPersonModel);

            _personTranslate       = new TranslateTransform3D();
            _personModel.Transform = _personTranslate;

            SceneModel2.Content = _personModel;
            PersonWireframeVisual.OriginalModel = _personModel;


            this.Focusable       = true;                           // by default Page is not focusable and therefore does not recieve keyDown event
            this.PreviewKeyDown += WireframeSample_PreviewKeyDown; // Use PreviewKeyDown to get arrow keys also (KeyDown event does not get them)
            this.Focus();

            this.Loaded += WireframeSample_Loaded;

            // IMPORTANT:
            // It is very important to call Dispose method on DXSceneView after the control is not used any more (see help file for more info)
            this.Unloaded += (sender, args) => MainDXViewportView.Dispose();
        }
 public VectorTranslateTransform3D(TranslateTransform3D tt, xyz dir, double dist)
 {
     _tt       = tt;
     Direction = dir;
     Distance  = dist;
 }
Example #6
0
 /// <summary>
 /// Resets the ball position.
 /// </summary>
 public void ResetPosition()
 {
     Transform = new TranslateTransform3D(0d, 0d, 0d);
 }
Example #7
0
        private void UpdateMoleculeSetPositionByVelocity(double t)
        {
            bool isStop = true;

            for (int i = 0; i < MoleculeSet.Count; i++)
            {
                Molecule m = MoleculeSet[i];

                bool ballIsStop = true;
                if (Math.Abs(m.currentVelocity.X) < e)
                {
                    m.currentVelocity.X = 0;
                }
                else
                {
                    ballIsStop = false;
                }
                if (Math.Abs(m.currentVelocity.Y) < e)
                {
                    m.currentVelocity.Y = 0;
                }
                else
                {
                    ballIsStop = false;
                }
                if (Math.Abs(m.currentVelocity.Z) < e)
                {
                    m.currentVelocity.Z = 0;
                }
                else
                {
                    ballIsStop = false;
                }

                if (ballIsStop)
                {
                    continue;
                }
                else
                {
                    isStop = false;

                    //通过小球的速度来更新小球位置
                    if (m.position != m.oldPosition)
                    {
                        PhysicEngine.UpdatePositionByVelocity(ref m.position, ref m.oldPosition, ref m.currentVelocity, t);
                    }

                    CDE.UpdateToGridmap(i);

                    //更新小球显示的位置
                    TranslateTransform3D temp = (TranslateTransform3D)(m.MoleculeGeometryModel.Transform);
                    temp.OffsetX = m.position.X;
                    temp.OffsetY = m.position.Y;
                    temp.OffsetZ = m.position.Z;
                }
            }

            if (isStop)
            {
                StopGameLoop();

                stick.UpdateStickPosition(new Vector3D(whiteBall.position.X, whiteBall.position.Y, whiteBall.position.Z), shotDirection);

                stick.Visible = true;

                gameWindows.SetShootDirectionAndForceFactor();
            }
        }
Example #8
0
        public Transition3D()
            : base(new Viewport3D())
        {
            // camera to ue
            WrappedElement.Camera = new PerspectiveCamera();

            // the model visual 3D
            ModelVisual3D mv3D = new ModelVisual3D();

            mv3D.Content = new PointLight(Colors.White, new Point3D(0, 0, 0));

            WrappedElement.Children.Add(mv3D);

            MeshGeometry3D    plane     = new MeshGeometry3D();
            Point3DCollection positions = new Point3DCollection();

            positions.Add(new Point3D(-1, -1, 0));
            positions.Add(new Point3D(-1, 1, 0));
            positions.Add(new Point3D(1, 1, 0));
            positions.Add(new Point3D(1, -1, 0));
            positions.Freeze();
            plane.Positions = positions;

            PointCollection textureCoords = new PointCollection();

            textureCoords.Add(new Point(0, 1));
            textureCoords.Add(new Point(0, 0));
            textureCoords.Add(new Point(1, 0));
            textureCoords.Add(new Point(1, 1));
            textureCoords.Freeze();
            plane.TextureCoordinates = textureCoords;

            Int32Collection indices = new Int32Collection();

            indices.Add(0);
            indices.Add(3);
            indices.Add(1);
            indices.Add(1);
            indices.Add(3);
            indices.Add(2);
            indices.Freeze();
            plane.TriangleIndices = indices;

            Material planeMaterial = new DiffuseMaterial(Brushes.Blue);

            planeMaterial.SetValue(Viewport2DVisual3D.IsVisualHostMaterialProperty, true);

            m_visual3D          = new Viewport2DVisual3D();
            m_visual3D.Geometry = plane;
            m_visual3D.Material = planeMaterial;

            Transform3DGroup transform = new Transform3DGroup();

            m_rotation    = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 35);
            m_scale       = new ScaleTransform3D(0, 0, 0);
            m_translation = new TranslateTransform3D(-2.5, 0, -10);

            transform.Children.Add(m_scale);
            transform.Children.Add(new RotateTransform3D(m_rotation));
            transform.Children.Add(m_translation);

            m_visual3D.Transform = transform;

            WrappedElement.Children.Add(m_visual3D);
        }
Example #9
0
        private void wPushsPull(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.W || e.Key == Key.S)
            {
                //Get camera position, then use it to calculate the vector from camera to object current location
                Point3D  camPoint     = viewPort3d.Camera.Position;
                Vector3D camToCurrent = new Vector3D(currentPosition.X - camPoint.X, currentPosition.Y - camPoint.Y, currentPosition.Z - camPoint.Z);
                Console.WriteLine("Camera position is: " + camPoint.X + " " + camPoint.Y + " " + camPoint.Z);
                Console.WriteLine("Current position is: " + currentPosition.X + " " + currentPosition.Y + " " + currentPosition.Z);
                Console.WriteLine("The offset from Camera to Current is " + camToCurrent.X + " " + camToCurrent.Y + " " + camToCurrent.Z);

                //Get length of the camToCurrent vector. This length will be extended or reduced depending on which key was pressed.
                double camToCurrentLength = camToCurrent.Length;
                double camToGoalLength;
                if (e.Key == Key.W)
                {
                    camToGoalLength = camToCurrentLength + 10;
                }
                else
                {
                    camToGoalLength = camToCurrentLength - 10;
                }

                var centerPoint = getCenter();

                //Use the length of the goal vector to calculate the offset in each individual direction
                double xOffset;
                double yOffset;
                double zOffset;

                //Formula for new offset: sqrt((current_position*(goalVectorLength/currentVectorLength)^2)
                if (camToCurrent.X < 0)
                {
                    xOffset = -(Math.Sqrt((camToCurrent.X * (camToGoalLength / camToCurrentLength)) * (camToCurrent.X * (camToGoalLength / camToCurrentLength))));
                }
                else
                {
                    xOffset = Math.Sqrt((camToCurrent.X * (camToGoalLength / camToCurrentLength)) * (camToCurrent.X * (camToGoalLength / camToCurrentLength)));
                }
                if (camToCurrent.Y < 0)
                {
                    yOffset = -(Math.Sqrt((camToCurrent.Y * (camToGoalLength / camToCurrentLength)) * (camToCurrent.Y * (camToGoalLength / camToCurrentLength))));
                }
                else
                {
                    yOffset = Math.Sqrt((camToCurrent.Y * (camToGoalLength / camToCurrentLength)) * (camToCurrent.Y * (camToGoalLength / camToCurrentLength)));
                }
                if (camToCurrent.Z < 0)
                {
                    zOffset = -(Math.Sqrt((camToCurrent.Z * (camToGoalLength / camToCurrentLength)) * (camToCurrent.Z * (camToGoalLength / camToCurrentLength))));
                }
                else
                {
                    zOffset = Math.Sqrt((camToCurrent.Z * (camToGoalLength / camToCurrentLength)) * (camToCurrent.Z * (camToGoalLength / camToCurrentLength)));
                }

                Console.WriteLine("The offset from camera to goal is: " + xOffset + " " + yOffset + " " + zOffset);

                //Use the length of each individual direction to calculate the goal position
                double goalXPos = camPoint.X + xOffset;
                double goalYPos = camPoint.Y + yOffset;
                double goalZPos = camPoint.Z + zOffset;
                Console.WriteLine("Goal position is: " + goalXPos + " " + goalYPos + " " + goalZPos);

                Point3D goalPoint = new Point3D(goalXPos, goalYPos, goalZPos);

                //Create vector object using goal position and centerpoint for the translation
                Vector3D goalVector = new Vector3D(goalXPos - centerPoint.X, goalYPos - centerPoint.Y, goalZPos - centerPoint.Z);

                //Create transformation group - use to execute translation and also save previous rotation status
                Transform3DGroup     trans3dgroup = new Transform3DGroup();
                TranslateTransform3D trans        = new TranslateTransform3D(goalVector.X, goalVector.Y, goalVector.Z);
                currentPosition.X = goalXPos;
                currentPosition.Y = goalYPos;
                currentPosition.Z = goalZPos;
                RotateTransform3D rot = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 0, -1), degree), currentPosition);
                trans3dgroup.Children.Add(trans);
                trans3dgroup.Children.Add(rot);
                obj.Transform = trans3dgroup;

                myPCamera.LookDirection = new Vector3D(currentPosition.X - myPCamera.Position.X, currentPosition.Y - myPCamera.Position.Y, currentPosition.Z - myPCamera.Position.Z);
            }
        }
Example #10
0
 public Node translate_by(TranslateTransform3D translator)
 {
     point = translator.Transform(point);
     return(this);
 }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SelfEdgeUIElement"/> class.
 /// </summary>
 /// <param name="graphProvider">The <see cref="IGraphProvider"/>.</param>
 /// <param name="edge">The edge.</param>
 /// <param name="translateTransform">The <see cref="TranslateTransform3D"/> of the visual element representing the node of the edge.</param>
 public SelfEdgeUIElement(IGraphProvider graphProvider, Edge<NodeData, EdgeData> edge, TranslateTransform3D translateTransform)
     : base(graphProvider, edge)
 {
     this.Transform = translateTransform;
 }
        protected override void BeginTransition3D(TransitionPresenter transitionElement, ContentPresenter oldContent, ContentPresenter newContent, Viewport3D viewport)
        {
            Size size = transitionElement.RenderSize;

            Point3D  origin = new Point3D();                 // origin of 2nd face
            Vector3D u = new Vector3D(), v = new Vector3D(); // u & v vectors of 2nd face

            double          angle = Angle;
            Point3D         rotationCenter;
            Vector3D        rotationAxis;
            RotateDirection direction = Direction;

            TranslateTransform3D translation = null;
            double angleRads = Angle * Math.PI / 180;

            if (direction == RotateDirection.Left || direction == RotateDirection.Right)
            {
                if (Contained)
                {
                    rotationCenter = new Point3D(direction == RotateDirection.Left ? size.Width : 0, 0, 0);
                    translation    = new TranslateTransform3D();
                    DoubleAnimation x = new DoubleAnimation(direction == RotateDirection.Left ? -size.Width : size.Width, Duration);
                    x.AccelerationRatio = 0.4;
                    x.DecelerationRatio = 0.6;
                    translation.BeginAnimation(TranslateTransform3D.OffsetXProperty, x);
                }
                else
                {
                    rotationCenter = new Point3D(size.Width / 2, 0, size.Width / 2 * Math.Tan(angle / 2 * Math.PI / 180));
                }

                rotationAxis = new Vector3D(0, 1, 0);

                if (direction == RotateDirection.Left)
                {
                    u.X = -size.Width * Math.Cos(angleRads);
                    u.Z = size.Width * Math.Sin(angleRads);

                    origin.X = size.Width;
                }
                else
                {
                    u.X = -size.Width * Math.Cos(angleRads);
                    u.Z = -size.Width * Math.Sin(angleRads);

                    origin.X = -u.X;
                    origin.Z = -u.Z;
                }
                v.Y = size.Height;
            }
            else
            {
                if (Contained)
                {
                    rotationCenter = new Point3D(0, direction == RotateDirection.Up ? size.Height : 0, 0);
                    translation    = new TranslateTransform3D();
                    DoubleAnimation y = new DoubleAnimation(direction == RotateDirection.Up ? -size.Height : size.Height, Duration);
                    y.AccelerationRatio = 0.4;
                    y.DecelerationRatio = 0.6;
                    translation.BeginAnimation(TranslateTransform3D.OffsetYProperty, y);
                }
                else
                {
                    rotationCenter = new Point3D(0, size.Height / 2, size.Height / 2 * Math.Tan(angle / 2 * Math.PI / 180));
                }

                rotationAxis = new Vector3D(1, 0, 0);

                if (direction == RotateDirection.Up)
                {
                    v.Y = -size.Height * Math.Cos(angleRads);
                    v.Z = size.Height * Math.Sin(angleRads);

                    origin.Y = size.Height;
                }
                else
                {
                    v.Y = -size.Height * Math.Cos(angleRads);
                    v.Z = -size.Height * Math.Sin(angleRads);

                    origin.Y = -v.Y;
                    origin.Z = -v.Z;
                }
                u.X = size.Width;
            }

            double endAngle = 180 - angle;

            if (direction == RotateDirection.Right || direction == RotateDirection.Up)
            {
                endAngle = -endAngle;
            }

            ModelVisual3D m1, m2;

            viewport.Children.Add(m1 = MakeSide(oldContent, new Point3D(), new Vector3D(size.Width, 0, 0), new Vector3D(0, size.Height, 0), endAngle, rotationCenter, rotationAxis, null));
            viewport.Children.Add(m2 = MakeSide(newContent, origin, u, v, endAngle, rotationCenter, rotationAxis, delegate
            {
                EndTransition(transitionElement, oldContent, newContent);
            }));

            m1.Transform = m2.Transform = translation;
        }
Example #13
0
        private void SelectObject(ModelVisual3D newSelectedObject, Rect3D selectedObjectBounds)
        {
            if (newSelectedObject == null)
            {
                _selectedModelVisual3D              = null;
                _selectedObjectScaleTransform       = null;
                _selectedObjectTranslateTransform3D = null;

                if (_selectionWireBoxVisual3D != null)
                {
                    if (LinesVisual.Children.Contains(_selectionWireBoxVisual3D))
                    {
                        LinesVisual.Children.Remove(_selectionWireBoxVisual3D);
                    }

                    _selectionWireBoxVisual3D = null;
                }

                OverlayCanvas.ClearScreenPositions();
            }
            else
            {
                if (_selectionWireBoxVisual3D == null)
                {
                    _selectionWireBoxVisual3D = new CornerWireBoxVisual3D()
                    {
                        IsLineLengthPercent = false,
                        LineLength          = 5,
                        LineThickness       = 2,
                        LineColor           = SceneEditorContext.Current.SelectedColor
                    };
                }

                if (selectedObjectBounds.IsEmpty)
                {
                    selectedObjectBounds = ModelUtils.GetBounds(newSelectedObject, newSelectedObject.Transform, checkOnlyBounds: true);
                }

                double standardSelectionLineLength = 5;
                double minSize = Math.Min(selectedObjectBounds.SizeX, Math.Min(selectedObjectBounds.SizeY, selectedObjectBounds.SizeZ));

                if (minSize > standardSelectionLineLength * 3)
                {
                    _selectionWireBoxVisual3D.LineLength = standardSelectionLineLength;
                }
                else
                {
                    _selectionWireBoxVisual3D.LineLength = minSize / 3;
                }


                _selectionWireBoxVisual3D.CenterPosition = selectedObjectBounds.GetCenterPosition();
                _selectionWireBoxVisual3D.Size           = selectedObjectBounds.Size;


                if (!LinesVisual.Children.Contains(_selectionWireBoxVisual3D))
                {
                    LinesVisual.Children.Add(_selectionWireBoxVisual3D);
                }

                _selectedModelVisual3D = newSelectedObject;
                _selectedObjectTranslateTransform3D = GetFirstTranslateTransform3D(_selectedModelVisual3D.Transform);
                _selectedObjectScaleTransform       = GetFirstScaleTransform3D(_selectedModelVisual3D.Transform);
            }
        }
Example #14
0
        private void ProcessCreateMouseButtonPressed(MouseButtonEventArgs e)
        {
            if (_currentObjectCreationState == ObjectCreationStates.SelectStartPoint)
            {
                _objectStartPosition = _lastIntersectionPoint;

                if (CreateBoxButton.IsChecked ?? false)
                {
                    var newBoxVisual = new BoxVisual3D()
                    {
                        Material     = _standardMaterial,
                        BackMaterial = _standardBackMaterial,

                        FreezeMeshGeometry3D    = false, // Do not freeze and cache the MeshGeometry3D because we can change its positions
                        UseCachedMeshGeometry3D = false
                    };

                    // NOTE:
                    // We create the Box with its default size (1,1,1) and at its default position (0,0,0)
                    // We will not change those two properties because each of them triggers regeneration of the geometry.
                    // Instead we will define scale and translate transform that will update the 3D Box to the correct size and position.
                    // This is much better for performance and much more garbage collection friendly

                    // By default the box is already created on (0,0,0) and with size (1,1,1) so we can comment the following 2 lines:
                    //_newBoxVisual.CenterPosition = new Point3D(0, 0, 0);
                    //_newBoxVisual.Size = new Size3D(1, 1, 1);

                    _selectedObjectScaleTransform       = new ScaleTransform3D(0.0, NEW_OBJECT_HEIGHT, 0.0);
                    _selectedObjectTranslateTransform3D = new TranslateTransform3D(_objectStartPosition.X, _objectStartPosition.Y, _objectStartPosition.Z);

                    var transform3DGroup = new Transform3DGroup();
                    transform3DGroup.Children.Add(_selectedObjectScaleTransform);
                    transform3DGroup.Children.Add(_selectedObjectTranslateTransform3D);

                    newBoxVisual.Transform = transform3DGroup;

                    ObjectsVisual.Children.Add(newBoxVisual);

                    _selectedModelVisual3D = newBoxVisual;
                }
                else
                {
                    var newSphereVisual3D = new SphereVisual3D()
                    {
                        Material     = _standardMaterial,
                        BackMaterial = _standardBackMaterial,

                        FreezeMeshGeometry3D    = false, // Do not freeze and cache the MeshGeometry3D because we can change its positions
                        UseCachedMeshGeometry3D = false
                    };

                    _selectedObjectScaleTransform       = new ScaleTransform3D(NEW_OBJECT_HEIGHT, NEW_OBJECT_HEIGHT, NEW_OBJECT_HEIGHT);
                    _selectedObjectTranslateTransform3D = new TranslateTransform3D(_objectStartPosition.X, _objectStartPosition.Y, _objectStartPosition.Z);

                    var transform3DGroup = new Transform3DGroup();
                    transform3DGroup.Children.Add(_selectedObjectScaleTransform);
                    transform3DGroup.Children.Add(_selectedObjectTranslateTransform3D);

                    newSphereVisual3D.Transform = transform3DGroup;

                    ObjectsVisual.Children.Add(newSphereVisual3D);

                    _selectedModelVisual3D = newSphereVisual3D;
                }

                // Change state from SelectStartPoint => SelectBaseSize
                _currentObjectCreationState = ObjectCreationStates.SelectBaseSize;
            }
            else if (_currentObjectCreationState == ObjectCreationStates.SelectHeight)
            {
                // Finish box creation
                // Change state from SelectBaseSize => SelectStartPoint
                _currentObjectCreationState = ObjectCreationStates.SelectStartPoint;
            }
        }
Example #15
0
        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ThreeDeeType which = ThreeDeeType.Robot;

            _resDir = System.IO.Path.Combine(Utils.GetSourcePath(), "Resources");

            // Define WPF objects.
            ModelVisual3D visual3d = new ModelVisual3D();

            _group           = new Model3DGroup();
            visual3d.Content = _group;
            mainViewport.Children.Add(visual3d);

            // Define the camera.
            _camera = new PerspectiveCamera {
                FieldOfView = 60
            };
            _cameraController = new SphericalCameraController(_camera, mainViewport, this, mainGrid, mainGrid);

            // Define the lights.
            Color darker = Color.FromArgb(255, 96, 96, 96);
            Color dark   = Color.FromArgb(255, 128, 128, 128);

            _group.Children.Add(new AmbientLight(darker));
            _group.Children.Add(new DirectionalLight(dark, new Vector3D(0, -1, 0)));
            _group.Children.Add(new DirectionalLight(dark, new Vector3D(1, -3, -2)));
            _group.Children.Add(new DirectionalLight(dark, new Vector3D(-1, 3, 2)));

            ///// Define the model.
            if (which == ThreeDeeType.Robot)
            {
                // Move back a bit from the origin.
                Point3D coords = _cameraController.SphericalCoordinates;
                coords.X = 20;
                //coords.Y = 20;
                _cameraController.SphericalCoordinates = coords;
                DefineModelRobot();

                // Some animation.  red = x   green = y   blue = z

                // Mesh defines the surface.
                MeshGeometry3D animMesh = new MeshGeometry3D();
                Point3D        pt       = D3.Origin;

                //////// box
                int size = 2;
                animMesh.AddBox(pt, new Vector3D(size, 0, 0), new Vector3D(0, size, 0), new Vector3D(0, 0, size));

                //////// sphere
                //double radius = 2;
                //animMesh.AddSphere(pt, radius, 30, 10, true);
                //pt.Z += 2.5;
                //pt.X += 1;
                //animMesh.AddSphere(pt, radius, 30, 10, true);

                //////////// Common
                var dur = new Duration(TimeSpan.FromMilliseconds(5000));
                // Model is the thing that is manipulated.
                GeometryModel3D animModel = animMesh.MakeModel(Brushes.Violet);
                _group.Children.Add(animModel);
                var transGroup = new Transform3DGroup();
                animModel.Transform = transGroup;

                //////////// stretch
                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);
                transGroup.Children.Add(myScaleTransform3D);

                //////////// Move
                var anim = new DoubleAnimation(0.0, 3, dur)
                {
                    BeginTime      = TimeSpan.FromSeconds(0),
                    RepeatBehavior = RepeatBehavior.Forever
                };
                var offsetTransform = new TranslateTransform3D();
                //offsetTransform.BeginAnimation(TranslateTransform3D.OffsetXProperty, anim);
                //offsetTransform.BeginAnimation(TranslateTransform3D.OffsetYProperty, anim);
                offsetTransform.BeginAnimation(TranslateTransform3D.OffsetZProperty, anim);
                transGroup.Children.Add(offsetTransform);

                ///////// rotation
                var startAxis         = new Vector3D(1, 0, 0);// (0, 1, 0);
                var rot               = new AxisAngleRotation3D(startAxis, 180);
                var myRotateTransform = new RotateTransform3D(rot);
                // end, duration
                var rotateTo          = new Vector3D(-1, -1, -1);
                var myVectorAnimation = new Vector3DAnimation(rotateTo, dur)
                {
                    RepeatBehavior = RepeatBehavior.Forever
                };
                myRotateTransform.Rotation.BeginAnimation(AxisAngleRotation3D.AxisProperty, myVectorAnimation);
                transGroup.Children.Add(myRotateTransform);
            }
            else if (which == ThreeDeeType.Garden)
            {
                DefineModelGarden();
            }
        }
Example #16
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #region Init World

                _boundryMin = new Point3D(-BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF);
                _boundryMax = new Point3D(BOUNDRYSIZEHALF, BOUNDRYSIZEHALF, BOUNDRYSIZEHALF);

                _world           = new World();
                _world.Updating += new EventHandler <WorldUpdatingArgs>(World_Updating);

                _world.SetCollisionBoundry(_boundryMin, _boundryMax);

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Wall
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Wall      = _materialManager.AddMaterial(material);

                // Ball
                material       = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Ball = _materialManager.AddMaterial(material);

                #endregion
                #region Trackball

                // Trackball
                _trackball                       = new TrackBallRoam(_camera);
                _trackball.KeyPanScale           = 15d;
                _trackball.EventSource           = grdViewPort; //NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete_NoLeft));
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                _trackball.ShouldHitTestOnOrbit = true;
                //_trackball.UserMovedCamera += new EventHandler<UserMovedCameraArgs>(Trackball_UserMovedCamera);
                //_trackball.GetOrbitRadius += new EventHandler<GetOrbitRadiusArgs>(Trackball_GetOrbitRadius);

                #endregion

                #region Chased Ball

                _chasedBall = new ChasedBall();

                _chasedBall.MotionType_Position    = MotionType_Position.Stop;
                _chasedBall.MotionType_Orientation = MotionType_Orientation.Stop;

                _chasedBall.BoundrySizeChanged += new EventHandler(ChasedBall_BoundrySizeChanged);

                // Ball visual
                _chasedBallVisual           = GetChaseBallVisual_Position();
                _chasedBallTransform        = new TranslateTransform3D();
                _chasedBallVisual.Transform = _chasedBallTransform;
                _viewport.Children.Add(_chasedBallVisual);

                // Direction Visual
                var directionVisual = GetChaseBallVisual_Orientation();
                _chasedDirectionModel  = directionVisual.Item1;
                _chasedDirectionVisual = directionVisual.Item2;
                _viewport.Children.Add(_chasedDirectionVisual);

                // Panels (the act of instantiating them will update the ball's properties)
                pnlChasePosition.Content = new ChasedPosition(_chasedBall)
                {
                    Foreground = Brushes.White,
                };

                pnlChaseOrientation.Content = new ChasedOrientation(_chasedBall)
                {
                    Foreground = Brushes.White,
                };

                #endregion
                #region Debug Visuals

                // Put these on the viewport before the ball so that it is propertly semitransparent

                //TODO: Draw the bounding box.  Use XYZ colors.  This will help the user stay oriented

                #endregion
                #region Body Ball

                _bodyBall = new BodyBall(_world);

                //_bodyBall.PhysicsBody.AngularDamping = new Vector3D(.0001, .0001, .0001);
                //_bodyBall.PhysicsBody.AngularVelocity = new Vector3D(0, 0, 4 * Math.PI);

                _viewport.Children.AddRange(_bodyBall.Visuals3D);

                #endregion

                RedrawBoundry();

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void SliceScene()
        {
            _projectedModelBounds = Rect.Empty; // Reset the bounds of the model that is projected to the plane (used by showing 2D sliced lines)

            var plane          = GetSelectedPlane();
            var planeTransform = GetSelectedPlaneTransform(updateTransformationAmount: true);

            // Transform the plane that will be used to slice the model
            plane.Transform(planeTransform);


            double slicedModelsSeparation = _rootModelSize * 0.1;
            var    frontModelTransform    = new TranslateTransform3D(plane.A * slicedModelsSeparation, plane.B * slicedModelsSeparation, plane.C * slicedModelsSeparation);
            var    backModelTransform     = new TranslateTransform3D(plane.A * -slicedModelsSeparation, plane.B * -slicedModelsSeparation, plane.C * -slicedModelsSeparation);;


            // When _originalModelVisual3D is defined we demonstrate the use of SliceModelVisual3D method.
            if (_originalModelVisual3D != null)
            {
                ModelVisual3D frontModelVisual3D, backModelVisual3D;

                // Each SliceXXXX method returns two new object:
                // one that lies in front of the plane (as defined with plane's normal vector (A, B, C value in Plane object),
                // one that lines in the back of the plane.
                //
                // If we only need the front object, we can use the SliceXXXX method that only takes 1 or 2 parameters and return the front object - for example:
                //frontModelVisual3D = _plane.SliceModelVisual3D(_originalModelVisual3D, transform);
                //backModelVisual3D = null;

                plane.SliceModelVisual3D(_originalModelVisual3D, out frontModelVisual3D, out backModelVisual3D);


                RootModelVisual3D.Children.Clear();

                if (frontModelVisual3D != null)
                {
                    foreach (var modelVisual3D in frontModelVisual3D.Children.OfType <ModelVisual3D>())
                    {
                        if (modelVisual3D.Content != null)
                        {
                            Ab3d.Utilities.ModelUtils.ChangeBackMaterial(modelVisual3D.Content, new DiffuseMaterial(Brushes.Red));
                        }
                    }

                    frontModelVisual3D.Transform = frontModelTransform;
                    RootModelVisual3D.Children.Add(frontModelVisual3D);
                }

                if (backModelVisual3D != null)
                {
                    foreach (var modelVisual3D in backModelVisual3D.Children.OfType <ModelVisual3D>())
                    {
                        if (modelVisual3D.Content != null)
                        {
                            Ab3d.Utilities.ModelUtils.ChangeBackMaterial(modelVisual3D.Content, new DiffuseMaterial(Brushes.Red));
                        }
                    }

                    backModelVisual3D.Transform = backModelTransform;
                    RootModelVisual3D.Children.Add(backModelVisual3D);
                }

                return;
            }


            Model3D frontModel3D, backModel3D;

            // When _originalModel3D is defined we demonstrate the use of SliceModel3D method (can slice GeometryModel3D or Model3DGroup objects)
            if (_originalModel3D != null)
            {
                plane.SliceModel3D(_originalModel3D, frontModel3D: out frontModel3D, backModel3D: out backModel3D);

                // To get only front objects, we can use the following method:
                //frontModel3D = _plane.SliceModel3D(_originalModel3D, parentTransform: transform);
                //backModel3D = null;
            }
            // When _originalModel3D is defined we demonstrate the use of SliceMeshGeometry3D method.
            else if (_originalMesh3D != null)
            {
                MeshGeometry3D frontMesh, backMash;
                plane.SliceMeshGeometry3D(_originalMesh3D, frontMeshGeometry3D: out frontMesh, backMeshGeometry3D: out backMash);

                // To get only front objects, we can use the following method:
                //frontMesh = plane.SliceMeshGeometry3D(originalMesh3D, transform: transform);
                //backMash = null;

                var frontGeometryModel3D = new GeometryModel3D(frontMesh, new DiffuseMaterial(Brushes.Gold));
                frontModel3D = frontGeometryModel3D;

                if (backMash != null)
                {
                    var backGeometryModel3D = new GeometryModel3D(backMash, new DiffuseMaterial(Brushes.Gold));
                    backModel3D = backGeometryModel3D;
                }
                else
                {
                    backModel3D = null;
                }
            }
            else
            {
                frontModel3D = null;
                backModel3D  = null;
            }

            // Set back material to red so we will easily see the inner parts of the model
            if (frontModel3D != null)
            {
                Ab3d.Utilities.ModelUtils.ChangeBackMaterial(frontModel3D, new DiffuseMaterial(Brushes.Red));
            }

            if (backModel3D != null)
            {
                Ab3d.Utilities.ModelUtils.ChangeBackMaterial(backModel3D, new DiffuseMaterial(Brushes.Red));
            }


            // When the sliced 3D models is not ModelVisual3D, we show both sliced parts in WireframeVisual3D object (with all 3D lines)
            WireframeModels1.OriginalModel = frontModel3D;
            WireframeModels1.Transform     = frontModelTransform;

            WireframeModels2.OriginalModel = backModel3D;
            WireframeModels2.Transform     = backModelTransform;
        }
Example #18
0
        private void SetModelTask(ModelFileData modelData)
        {
            if (CurrentModelVisual != null)
            {
                this.Viewport.Children.Remove(CurrentModelVisual);
                CurrentModelVisual = null;
                GC.Collect(0, GCCollectionMode.Forced);
            }

            if (!this.Viewport.IsVisible)
            {
                this.ModelDataToLoadWhenVisible = modelData;
                return;
            }

            Model3DGroup  modelGroup  = new Model3DGroup();
            ModelVisual3D modelVisual = new ModelVisual3D();

            try
            {
                if (modelData != null)
                {
                    ModelFileData newModelData = new ModelFileData(modelData.FileFullPath);
                    this.ModelData    = newModelData;
                    Viewport.SubTitle = modelData.FileName;

                    newModelData.LoadBasicFileData();

                    if (userSettings.GetSettingBool(UserSettingEnum.EnableMaxSizeMBToLoadMeshInView) && modelData.FileSizeMB > userSettings.GetSettingInt(UserSettingEnum.MaxSizeMBToLoadMeshInView))
                    {
                        // TODO: Load generic model.
                        Viewport.SubTitle  = Loc.GetTextFormatted("FileSizeTooBigToLoadMB", modelData.FileSizeMB, userSettings.GetSettingInt(UserSettingEnum.MaxSizeMBToLoadMeshInView));
                        CurrentModelVisual = null;
                        return;
                    }

                    if (!newModelData.HasBytes())
                    {
                        newModelData.LoadFileBytes(newModelData.FileSizeMB < 50f);
                    }
                    if (newModelData.Mesh == null)
                    {
                        newModelData.ParseFile();
                    }
                    newModelData.ReleaseData(true, false);

                    if (newModelData.Mesh == null)
                    {
                        newModelData.ReleaseData(true, false);
                        SetModel(null);
                        return;
                    }

                    LoadModelInfoAvailableEvent?.Invoke(newModelData.FileName, newModelData.Mesh.TriangleCount, newModelData.Mesh.Vertices.Length, (int)newModelData.FileSizeKB);

                    float modelScale         = newModelData.Mesh.Scale / 4f;
                    float modelScaleMultiply = (newModelData.Mesh.Scale < 0.001f ? 0.1f : (newModelData.Mesh.Scale > 0.1 ? 10f : 1));


                    var transformTranslate           = new TranslateTransform3D(-newModelData.Mesh.OffsetX, -newModelData.Mesh.OffsetY, -newModelData.Mesh.OffsetZ);
                    AxisAngleRotation3D axisRotation = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 0);
                    transformObjectRotation = new RotateTransform3D(axisRotation, new Point3D(newModelData.Mesh.OffsetX, newModelData.Mesh.OffsetY, 0));
                    ScaleTransform3D transformScale = new ScaleTransform3D(modelScaleMultiply, modelScaleMultiply, modelScaleMultiply);

                    Transform3DGroup transforms = new Transform3DGroup();
                    transforms.Children.Add(transformObjectRotation);
                    transforms.Children.Add(transformTranslate);
                    transforms.Children.Add(transformScale);

                    Mesh3D mesh;

                    // Mesh decimation if enabled
                    if (userSettings.GetSettingBool(UserSettingEnum.EnableMeshDecimation) && newModelData.Mesh.TriangleCount > userSettings.GetSettingInt(UserSettingEnum.MinTrianglesForMeshDecimation))
                    {
                        MeshDecimator.Math.Vector3d[] vectors3D = newModelData.Mesh.Vertices.Select(v => new MeshDecimator.Math.Vector3d(v.x, v.y, v.z)).ToArray();
                        Mesh decimatorMesh = new Mesh(vectors3D, newModelData.Mesh.Triangles.ToArray());

                        Mesh decimatedMesh = MeshDecimation.DecimateMeshLossless(decimatorMesh);
                        mesh = new Mesh3D(decimatedMesh.Vertices.Select(v => new Point3D(v.x, v.y, v.z)), decimatedMesh.Indices);

                        // TODO: Possibly cache the decimated models to avoid re-processing.
                    }
                    else
                    {
                        mesh = new Mesh3D(Point3DFromLinearCoordinates(newModelData.Mesh.Vertices), newModelData.Mesh.Triangles);
                    }
                    GeometryModel3D geometryModel = new GeometryModel3D(mesh.ToMeshGeometry3D(), GetMaterial());
                    geometryModel.Freeze();

                    modelGroup.Children.Add(geometryModel);
                    modelGroup.Freeze();

                    _modelHeightPosition = newModelData.Mesh.Height * modelScaleMultiply;
                    newModelData.ReleaseData(true, true);

                    // Animation
                    if (ModelAutoRotationEnabled)
                    {
                        DoubleAnimation animation1 = new DoubleAnimation(-90, 395d, TimeSpan.FromMilliseconds(1000));
                        animation1.EasingFunction = new ExponentialEase();

                        DoubleAnimation animation2 = new DoubleAnimation(36d, 395d, TimeSpan.FromMilliseconds(7000));
                        animation2.RepeatBehavior = RepeatBehavior.Forever;

                        animation1.Completed += (o, e) => axisRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, animation2);
                        axisRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, animation1);
                    }

                    // Camera animation
                    var nomalizedOriginalPosition = _originalCameraPosition.ToVector3D();
                    nomalizedOriginalPosition.Normalize();
                    _modelCameraPosition = new Point3D(nomalizedOriginalPosition.X / modelScale * modelScaleMultiply, nomalizedOriginalPosition.Y / modelScale * modelScaleMultiply, nomalizedOriginalPosition.Z / modelScale * modelScaleMultiply);

                    Point3D targetCameraPosition = _modelCameraPosition;
                    if (_CurrentCameraPosition == CameraPositionEnum.Default)
                    {
                        var normalizedPosition = Viewport.Camera.Position.ToVector3D();
                        normalizedPosition.Normalize();
                        targetCameraPosition = new Point3D(normalizedPosition.X / modelScale * modelScaleMultiply, normalizedPosition.Y / modelScale * modelScaleMultiply, normalizedPosition.Z / modelScale * modelScaleMultiply);

                        Viewport.Camera.AnimateTo(targetCameraPosition, Viewport.Camera.LookDirection, Viewport.Camera.UpDirection, 500d);
                    }
                    else
                    {
                        ResetCamera(CameraPositionEnum.Current);
                    }

                    minZoom = targetCameraPosition.Multiply(0.5d).DistanceTo(new Point3D());
                    maxZoom = minZoom * 4d;

                    this.CurrentAxisRotation = axisRotation;
                    modelVisual.Transform    = transforms;
                }
                modelVisual.Content = modelGroup;
                this.Viewport.Children.Add(modelVisual);

                this.CurrentModelVisual = modelVisual;
            }
            catch (Exception ex)
            {
                if (CurrentModelVisual != null)
                {
                    this.Viewport.Children.Add(CurrentModelVisual);
                    this.CurrentModelVisual = null;
                }
            }
            if (modelData == null)
            {
                _modelCameraPosition = _originalCameraPosition;
                ResetCamera(CameraPositionEnum.Default, true);
                LoadModelInfoAvailableEvent?.Invoke("", 0, 0, 0);
                _modelHeightPosition = (float)(_originalCameraPosition.Z / 2d);
                Viewport.SubTitle    = string.Empty;
            }
            GC.Collect();
        }
Example #19
0
        private void Map_ItemAdded(object sender, MapItemArgs e)
        {
            #region Create blip

            Visual3D blip;
            List <Tuple <Visual3D, bool> > blips = new List <Tuple <Visual3D, bool> >();;

            if (e.Item is Asteroid)
            {
                blip = GetAsteroidBlip((Asteroid)e.Item);
                blips.Add(Tuple.Create(blip, false));
            }
            else if (e.Item is Mineral)
            {
                blip = GetMineralBlip((Mineral)e.Item);
                blips.Add(Tuple.Create(blip, false));
            }
            else if (e.Item is SpaceStation2D)
            {
                blip = GetStationBlip((SpaceStation2D)e.Item);
                blips.Add(Tuple.Create(blip, true));
            }
            else if (e.Item is Bot)
            {
                blip = GetShipBlip((Bot)e.Item);
                blips.Add(Tuple.Create(blip, true));

                blip = GetShipCompassBlip((Bot)e.Item);
                blips.Add(Tuple.Create(blip, false));
            }

            #endregion

            // Remove nulls (if the item isn't very significant, then no blip is made)
            blips = blips.Where(o => o.Item1 != null).ToList();
            if (blips.Count == 0)
            {
                return;
            }

            #region Create transforms

            List <BlipVisual> blipVisuals = new List <BlipVisual>();

            foreach (var tuple in blips)
            {
                // Transform
                Transform3DGroup    transform = new Transform3DGroup();
                AxisAngleRotation3D rotate    = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 0);
                transform.Children.Add(new RotateTransform3D(rotate));
                TranslateTransform3D translate = new TranslateTransform3D(e.Item.PositionWorld.ToVector());
                transform.Children.Add(translate);

                tuple.Item1.Transform = transform;

                blipVisuals.Add(new BlipVisual(tuple.Item1, tuple.Item2, translate, rotate));
            }

            #endregion

            // Store it
            _blips.Add(new Blip(e.Item, blipVisuals.ToArray()));
            _viewport.Children.AddRange(blipVisuals.Select(o => o.Visual));
        }
        private void SimpleBallAnimation()
        {
            Transform3DGroup myTransform3DGroup = new Transform3DGroup();

            //rotation
            AxisAngleRotation3D axis   = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 0);
            RotateTransform3D   rotate = new RotateTransform3D(axis);

            rotate.CenterX = -46;
            rotate.CenterY = 2;
            rotate.CenterZ = 46;

            myTransform3DGroup.Children.Add(rotate);

            SphereContainer.Transform = myTransform3DGroup;

            NameScope scope = new NameScope();
            FrameworkContentElement element = new FrameworkContentElement();

            NameScope.SetNameScope(element, scope);

            element.RegisterName("rotation", axis);

            DoubleAnimation animation = new DoubleAnimation
            {
                From           = 0,
                To             = -1548,
                Duration       = TimeSpan.FromSeconds(4),
                AutoReverse    = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            Storyboard myStoryboard = new Storyboard();

            Storyboard.SetTargetProperty(animation, new PropertyPath("Angle"));

            Storyboard.SetTargetName(animation, "rotation");
            myStoryboard.Children.Add(animation);
            myStoryboard.Duration = TimeSpan.FromSeconds(4);

            //translation
            TranslateTransform3D tran = new TranslateTransform3D(0, 0, 0);

            myTransform3DGroup.Children.Add(tran);
            SphereContainer.Transform = myTransform3DGroup;

            element.RegisterName("translation", tran);

            DoubleAnimation animation2 = new DoubleAnimation
            {
                From           = 0,
                To             = 54.036,
                Duration       = TimeSpan.FromSeconds(4),
                AutoReverse    = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            Storyboard.SetTargetProperty(animation2, new PropertyPath("OffsetX"));

            Storyboard.SetTargetName(animation2, "translation");
            myStoryboard.Children.Add(animation2);
            myStoryboard.Duration       = TimeSpan.FromSeconds(4);
            myStoryboard.RepeatBehavior = RepeatBehavior.Forever;
            myStoryboard.AutoReverse    = true;

            this.Resources.Add("id1111", myStoryboard);
            myStoryboard.Begin(element, HandoffBehavior.Compose);
        }
Example #21
0
        private static Model3DGroup CreateAxisAndArrowHead(RotateTransform3D rotateTransform, TranslateTransform3D translateTransform, Material material)
        {
            Model3DGroup      model3Dgroup      = new Model3DGroup();
            Model3DCollection model3Dcollection = new Model3DCollection();

            model3Dgroup.Children = model3Dcollection;
            Model3DGroup cylinder = Cylinder.CreateCylinder(0.02, 0.5, 12, material, material, (Material)null);

            if (rotateTransform != null)
            {
                cylinder.Transform = (Transform3D)rotateTransform;
            }
            model3Dgroup.Children.Add((Model3D)cylinder);
            Model3DGroup cone = Cone.CreateCone(0.04, 0.1, 12, material, material);

            if (rotateTransform != null)
            {
                cone.Transform = (Transform3D) new Transform3DGroup()
                {
                    Children =
                    {
                        (Transform3D)rotateTransform,
                        (Transform3D)translateTransform
                    }
                }
            }
            ;
            else
            {
                cone.Transform = (Transform3D)translateTransform;
            }
            model3Dgroup.Children.Add((Model3D)cone);
            model3Dgroup.Freeze();
            return(model3Dgroup);
        }
        // Called when a 3D model is selected
        // It add ModelMover to the scene and sets its event handlers
        private void SetupModelMover()
        {
            // Creat a new ModelMover
            _modelMover = new ModelMoverVisual3D();

            // IMPORTANT !!!
            // When ModelMoverVisual3D is used with EventManager3D
            // we need to call SubscribeWithEventManager3D to use EventManager3D for mouse events processing
            _modelMover.SubscribeWithEventManager3D(_eventManager);

            // Position ModelMover at the center of selected model
#if !USE_GENERIC_MODEL3D
            _modelMover.Position = _selectedBoxModel.CenterPosition;
#else
            _modelMover.Position = GetSelectedModelCenter();
#endif

            // Calculate axis length from model size
            var    modelBounds = _selectedBoxModel.Model.Bounds; // Because we know that we are using BoxVisual3D, we could also use _selectedBoxVisual3D.Size; But using Bounds is more generic
            double axisLength  = Math.Max(modelBounds.Size.X, Math.Max(modelBounds.Size.Y, modelBounds.Size.Z));

            _modelMover.AxisLength = axisLength;

            // Set AxisRadius and AxisArrowRadius based on axis length
            _modelMover.AxisRadius      = axisLength / 30;
            _modelMover.AxisArrowRadius = _modelMover.AxisRadius * 3;

            UpdatedShownAxes();


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

#if !USE_GENERIC_MODEL3D
                _startMovePosition   = _selectedBoxModel.CenterPosition;
                _modelMover.Position = _startMovePosition;
#else
                // When the move starts we create a new TranslateTransform3D that will be used to move the model.
                _currentTranslateTransform3D = new TranslateTransform3D();

                // The new TranslateTransform3D is added to existing transformations on the object (if they exist)

                var currentTransform = _selectedBoxModel.Transform;

                if (currentTransform == null)
                {
                    _selectedBoxModel.Transform = _currentTranslateTransform3D;
                }
                else
                {
                    // transformation already exist

                    // Check if we already have Transform3DGroup
                    var currentTransformGroup = currentTransform as Transform3DGroup;
                    if (currentTransformGroup == null)
                    {
                        // Create new Transform3DGroup and add existing Transformation to the new Group
                        currentTransformGroup = new Transform3DGroup();
                        currentTransformGroup.Children.Add(_selectedBoxModel.Transform);

                        _selectedBoxModel.Transform = currentTransformGroup;
                    }

                    currentTransformGroup.Children.Add(_currentTranslateTransform3D);
                }

                // Move the ModelMover to current model center
                _startMovePosition   = GetSelectedModelCenter();
                _modelMover.Position = _startMovePosition;
#endif
            };

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

                var newCenterPosition = _startMovePosition + e.MoveVector3D;

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

#if !USE_GENERIC_MODEL3D
                _selectedBoxModel.CenterPosition = newCenterPosition;
                _modelMover.Position             = newCenterPosition;
#else
                // When model is moved we get the updated MoveVector3D
                // We use MoveVector3D to change the _currentTranslateTransform3D that is used on the currently selected model and on the ModelMover object
                _currentTranslateTransform3D.OffsetX = moveVector3D.X;
                _currentTranslateTransform3D.OffsetY = moveVector3D.Y;
                _currentTranslateTransform3D.OffsetZ = moveVector3D.Z;

                _modelMover.Position = newCenterPosition;
#endif

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

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


            // Add ModelMover to Viewport3D
            // We need to insert it before other objects so that the transparent objects are correctly visible (transparent objects must be shown after other objects)
            MainViewport.Children.Insert(0, _modelMover);
        }
Example #23
0
        private void DrawSomeModels()
        {
            myViewport.Name = "myViewport";
            ModelVisual3D myModelVisual = new ModelVisual3D();

            //Define lights and cameras
            myPCamera.FarPlaneDistance  = 20;
            myPCamera.NearPlaneDistance = 0;
            myPCamera.FieldOfView       = 50;
            myPCamera.Position          = new Point3D(-5, 2, 3);
            myPCamera.LookDirection     = new Vector3D(5, -2, -3);
            myPCamera.UpDirection       = new Vector3D(0, 1, 0);

            myDLight.Color     = Colors.White;
            myDLight.Direction = new Vector3D(-3, -4, -5);

            myAmbLight.Color = Colors.White;

            //set Geometry property of MeshGeometry3D
            side2.Geometry = side2Plane;
            side6.Geometry = side6Plane;
            side1.Geometry = side1Plane;
            side3.Geometry = side3Plane;
            side4.Geometry = side4Plane;
            side5.Geometry = side5Plane;

            //create translations
            //<Snippet3DOverview3DN19>
            TranslateTransform3D cube2Translation = new TranslateTransform3D(new Vector3D(2, 0, 0));
            //</Snippet3DOverview3DN19>
            TranslateTransform3D cube3Translation = new TranslateTransform3D(new Vector3D(4, 0, 0));
            //<Snippet3DOverview3DN1>
            //Define a rotation
            RotateTransform3D myRotateTransform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), 1));
            //</Snippet3DOverview3DN1>
            //<Snippet3DOverview3DN2>
            //Define an animation for the rotation
            DoubleAnimation myAnimation = new DoubleAnimation();

            myAnimation.From           = 1;
            myAnimation.To             = 361;
            myAnimation.Duration       = new Duration(TimeSpan.FromMilliseconds(5000));
            myAnimation.RepeatBehavior = RepeatBehavior.Forever;
            //</Snippet3DOverview3DN2>

            //Define another animation
            //<Snippet3DOverview3DN3>
            Vector3DAnimation myVectorAnimation = new Vector3DAnimation(new Vector3D(-1, -1, -1), new Duration(TimeSpan.FromMilliseconds(5000)));

            myVectorAnimation.RepeatBehavior = RepeatBehavior.Forever;
            //</Snippet3DOverview3DN3>


            myRotateTransform.Rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, myAnimation);
            //<Snippet3DOverview3DN4>
            myRotateTransform.Rotation.BeginAnimation(AxisAngleRotation3D.AxisProperty, myVectorAnimation);
            //</Snippet3DOverview3DN4>
            //<Snippet3DOverview3DN5>
            //Add transformation to the model
            cube1TransformGroup.Children.Add(myRotateTransform);
            //</Snippet3DOverview3DN5>

            cube2TransformGroup.Children.Add(myRotateTransform);
            cube2TransformGroup.Children.Add(cube2Translation);

            cube3TransformGroup.Children.Add(myRotateTransform);
            cube3TransformGroup.Children.Add(cube3Translation);

            allModelsTransformGroup.Children.Add(myRotateTransform);

            cubeModel_1.Children.Add(side1);
            cubeModel_1.Children.Add(side2);
            cubeModel_1.Children.Add(side3);
            cubeModel_1.Children.Add(side4);
            cubeModel_1.Children.Add(side5);
            cubeModel_1.Children.Add(side6);
            cubeModel_1.Transform = cube1TransformGroup;

            cubeModel_2.Children.Add(side1);
            cubeModel_2.Children.Add(side2);
            cubeModel_2.Children.Add(side3);
            cubeModel_2.Children.Add(side4);
            cubeModel_2.Children.Add(side5);
            cubeModel_2.Children.Add(side6);
            cubeModel_2.Transform = cube2TransformGroup;

            cubeModel_3.Children.Add(side1);
            cubeModel_3.Children.Add(side2);
            cubeModel_3.Children.Add(side3);
            cubeModel_3.Children.Add(side4);
            cubeModel_3.Children.Add(side5);
            cubeModel_3.Children.Add(side6);
            cubeModel_3.Transform = cube3TransformGroup;

            allModels.Transform = allModelsTransformGroup;
            allModels.Children.Add(cubeModel_3);
            allModels.Children.Add(cubeModel_2);
            allModels.Children.Add(cubeModel_1);

            allModels.Children.Add(myAmbLight);

            myViewport.Camera     = myPCamera;
            myModelVisual.Content = allModels;
            myViewport.Children.Add(myModelVisual);

            mainWindow.Content = myViewport;
        }
Example #24
0
        protected override Size ArrangeOverride(Size finalSize)
        {
            var rect = new Rect(new Point(), finalSize);

            this.viewport3D.Arrange(rect);

            if (this.Children.Count == 0)
            {
                return(finalSize);
            }

            // Record the current furthest object.
            // As we process the items, record the new furthest object.
            // Did they change? If so, we need to resort.
            var furthestItem          = this.viewport3D.Children.OfType <Viewport2DVisual3D>().First();
            var furthestItemTransform = furthestItem.GetTransform3D <TranslateTransform3D>();
            var furthestDepth         = furthestItemTransform == null ? 0d : furthestItemTransform.OffsetZ;

            bool depthSortRequired = false;

            // Calculate the spacing between each item.
            var itemSpacing = this.ellipseCircumference / this.Children.Count;

            this.ellipseRect = new Rect(this.EllipseCentreX, this.EllipseCentreY, this.EllipseWidth, this.EllipseHeight);

            foreach (var kvp in this.elementModelMap)
            {
                var child   = kvp.Value;
                var element = kvp.Key;

                // We want the item as a FrameworkElement so that we can get its height and width.
                var i = this.Children.IndexOf(element);

                element.Arrange(new Rect(new Point(0, 0), finalSize));

                // Work out how far around the ellipse we are
                double theta = TWO_PI * ((i * itemSpacing) * this.ellipseCircumferenceReciprocal);

                // Offset so the ellipse starts at the top.
                theta -= HALF_PI;

                // Now to calculate the point on the edge of the ellipse for the current rotation.
                Point p = MathHelper.GetPointOnEllipse(ellipseRect, theta);

                // We now have the x and the y values of the target point on an ellipse in 2D.
                // We need to rotate this position by the same amount that the ellipse has been
                // rotated so that we get the correct 3D position on the ellipse
                var rotatedPoint = MathHelper.RotatePoint3D(new Point3D(p.X, p.Y, 0d), -this.EllipseRotationX, this.EllipseRotationY, this.EllipseRotationZ);

                // Create a 3D translation transformation so that the button appears in the correct place.
                var translate = new TranslateTransform3D(rotatedPoint.X, rotatedPoint.Y, rotatedPoint.Z);

                if (rotatedPoint.Z <= furthestDepth && child != furthestItem)
                {
                    depthSortRequired = true;
                }

                // Add the new translation in to the transform group.
                child.AssertTransform3D <TranslateTransform3D>(translate);
            }

            if (this.TransparencySupportRequired && depthSortRequired)
            {
                this.DepthSortChildren();
            }

            return(finalSize);
        }
Example #25
0
        private void kinect_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            using (SkeletonFrame skelFrame = e.OpenSkeletonFrame())
            {
                if (skelFrame != null && masterSettings.kinectOptionsList.Count > kinectID && (masterKinectSettings.mergeSkeletons || masterKinectSettings.sendRawSkeletons))
                {
                    DateTime   now       = DateTime.UtcNow;
                    Skeleton[] skeletons = new Skeleton[skelFrame.SkeletonArrayLength];
                    skelFrame.CopySkeletonDataTo(skeletons);


                    EigenWrapper.Matrix predAccel = new EigenWrapper.Matrix(3, 1);
                    predAccel[2, 0] = 1;
                    if (accelFilterStarted)
                    {
                        predAccel = accelerationFilter.PredictAndDiscard(0);
                    }

                    if (interactStream != null)
                    {
                        Vector4 filteredAccel = new Vector4();
                        filteredAccel.W = 0;
                        filteredAccel.X = (float)predAccel[0, 0];
                        filteredAccel.Y = (float)predAccel[1, 0];
                        filteredAccel.Z = (float)predAccel[2, 0];
                        interactStream.ProcessSkeleton(skeletons, filteredAccel, skelFrame.Timestamp);

                        System.Diagnostics.Trace.WriteLine("[" + filteredAccel.X + ", " + filteredAccel.Y + ", " + filteredAccel.Z + "]");
                    }

                    //Generate the transformation matrix for the skeletons
                    double               kinectYaw                  = masterKinectSettings.kinectYaw;
                    Point3D              kinectPosition             = masterKinectSettings.kinectPosition;
                    Matrix3D             gravityBasedKinectRotation = findRotation(new Vector3D(predAccel[0, 0], predAccel[1, 0], predAccel[2, 0]), new Vector3D(0, -1, 0));
                    AxisAngleRotation3D  yawRotation                = new AxisAngleRotation3D(new Vector3D(0, 1, 0), -kinectYaw);
                    RotateTransform3D    tempTrans                  = new RotateTransform3D(yawRotation);
                    TranslateTransform3D transTrans                 = new TranslateTransform3D((Vector3D)kinectPosition);
                    Matrix3D             masterMatrix               = Matrix3D.Multiply(Matrix3D.Multiply(tempTrans.Value, gravityBasedKinectRotation), transTrans.Value);
                    skeletonTransformation = masterMatrix;

                    //Convert from Kinect v1 skeletons to KVR skeletons
                    KinectBase.KinectSkeleton[] kvrSkeletons = new KinectBase.KinectSkeleton[skeletons.Length];
                    for (int i = 0; i < kvrSkeletons.Length; i++)
                    {
                        //Set the tracking ID numbers for the hand grab data
                        int grabID = -1;
                        for (int j = 0; j < skeletonHandGrabData.Count; j++)
                        {
                            if (skeletonHandGrabData[j].skeletonTrackingID == skeletons[i].TrackingId)
                            {
                                grabID = j;
                                break;
                            }
                        }
                        if (grabID < 0)
                        {
                            skeletonHandGrabData.Add(new HandGrabInfo(skeletons[i].TrackingId));
                            grabID = skeletonHandGrabData.Count - 1;
                        }

                        kvrSkeletons[i]          = new KinectBase.KinectSkeleton();
                        kvrSkeletons[i].Position = new Point3D(skeletons[i].Position.X, skeletons[i].Position.Y, skeletons[i].Position.Z);
                        kvrSkeletons[i].SkeletonTrackingState = convertTrackingState(skeletons[i].TrackingState);
                        kvrSkeletons[i].TrackingId            = skeletons[i].TrackingId;
                        //kvrSkeletons[i].utcSampleTime = DateTime.UtcNow;
                        kvrSkeletons[i].sourceKinectID = kinectID;

                        for (int j = 0; j < skeletons[i].Joints.Count; j++)
                        {
                            KinectBase.Joint newJoint = new KinectBase.Joint();
                            newJoint.Confidence = KinectBase.TrackingConfidence.Unknown; //The Kinect 1 doesn't support the confidence property
                            newJoint.JointType  = convertJointType(skeletons[i].Joints[(JointType)j].JointType);
                            Vector4 tempQuat = skeletons[i].BoneOrientations[(JointType)j].AbsoluteRotation.Quaternion;
                            newJoint.Orientation = new Quaternion(tempQuat.X, tempQuat.Y, tempQuat.Z, tempQuat.W);
                            SkeletonPoint tempPos = skeletons[i].Joints[(JointType)j].Position;
                            newJoint.Position      = new Point3D(tempPos.X, tempPos.Y, tempPos.Z);
                            newJoint.TrackingState = convertTrackingState(skeletons[i].Joints[(JointType)j].TrackingState);
                            newJoint.utcTime       = now;
                            kvrSkeletons[i].skeleton[newJoint.JointType] = newJoint; //Skeleton doesn't need to be initialized because it is done in the KinectSkeleton constructor
                        }

                        //Get the hand states from the hand grab data array
                        kvrSkeletons[i].rightHandClosed = skeletonHandGrabData[grabID].rightHandClosed;
                        kvrSkeletons[i].leftHandClosed  = skeletonHandGrabData[grabID].leftHandClosed;
                    }

                    //Add the skeleton data to the event handler and throw the event
                    KinectBase.SkeletonEventArgs skelE = new KinectBase.SkeletonEventArgs();
                    skelE.skeletons = kvrSkeletons;
                    skelE.kinectID  = kinectID;

                    OnSkeletonChanged(skelE);
                }
            }
        }
        // Define the model.
        private void DefineModel(Model3DGroup group)
        {
            // Make the initial surface.
            int numX = 40;
            int numZ = 40;

            Point3D[,] surface = G3.InitSurface(0, numX, -3, 3, numZ, -3, 3);

            // Add some craters.
            AddCrater(surface, -1, 0, 1.5, 0.3);
            AddCrater(surface, 1.6, -1.5, 0.5, 0.4);
            AddCrater(surface, 1.5, 1.5, 0.75, 0.3);
            AddCrater(surface, 0.5, -0.6, 1.25, 0.1);

            // Add some relatively large-scale randomness to random points.
            Random rand = new Random(0);

            for (int i = 0; i < 10; i++)
            {
                int ix = rand.Next(0, numX);
                int iz = rand.Next(0, numZ);
                surface[ix, iz].Y += rand.NextDouble(-0.1, 0.1);
            }

            // Fractalize.
            surface = G3.FractalizeSurface(surface, 2, 1, -0.05, 0.05);

            // Translate to center better.
            TranslateTransform3D trans = new TranslateTransform3D(0, 1, 0);

            numX = surface.GetUpperBound(0) + 1;
            numZ = surface.GetUpperBound(1) + 1;
            for (int ix = 0; ix < numX; ix++)
            {
                for (int iz = 0; iz < numZ; iz++)
                {
                    surface[ix, iz] = trans.Transform(surface[ix, iz]);
                }
            }

            // Make the mesh.
            MeshGeometry3D mesh1 = new MeshGeometry3D();

            mesh1.AddSurface(surface);

            // Apply a height map.
            double minY = surface[0, 0].Y;
            double maxY = minY;

            foreach (Point3D point in surface)
            {
                if (minY > point.Y)
                {
                    minY = point.Y;
                }
                if (maxY < point.Y)
                {
                    maxY = point.Y;
                }
            }
            mesh1.ApplyHeightMap(0, 1, minY, maxY);

            GradientStopCollection stops = new GradientStopCollection();

            stops.Add(new GradientStop(Colors.Gray, 0));
            stops.Add(new GradientStop(Colors.LightGray, 0.25));
            stops.Add(new GradientStop(Colors.LightGray, 0.75));
            stops.Add(new GradientStop(Colors.White, 1));
            LinearGradientBrush brush =
                new LinearGradientBrush(stops, new Point(0, 0), new Point(1, 1));

            group.Children.Add(mesh1.MakeModel(brush));
        }
Example #27
0
 public static Vector3D GetVector(TranslateTransform3D transform)
 {
     return(new Vector3D(transform.OffsetX, transform.OffsetY, transform.OffsetZ));
 }
Example #28
0
        private void Create3D()
        {
            //定义网格
            MeshGeometry3D mesh = new MeshGeometry3D();

            //设置 MeshGeometry3D 的顶点位置的集合。Positions属性指定的点表示构成三维网格的三角形的顶点。
            //环绕顺序(指定构成网格每个三角形的 Position 的顺序)确定了给定面是正面还是背面。
            //正面三角形以逆时针顺序环绕;背面三角形以顺时针顺序环绕。
            //定义8个三维空间点
            mesh.Positions.Add(new Point3D(-10, -10, 10));
            mesh.Positions.Add(new Point3D(10, -10, 10));
            mesh.Positions.Add(new Point3D(10, 10, 10));
            mesh.Positions.Add(new Point3D(-10, 10, 10));

            mesh.Positions.Add(new Point3D(-10, -10, -10));
            mesh.Positions.Add(new Point3D(10, -10, -10));
            mesh.Positions.Add(new Point3D(10, 10, -10));
            mesh.Positions.Add(new Point3D(-10, 10, -10));

            //TriangleIndices:获取或设置 MeshGeometry3D 的三角形索引的集合。(组成3D可视形状)
            //对于给定的三维网格而言,指定三角形的顶点位置的顺序确定了此三角形面是正面还是背面。
            //Windows Presentation Foundation三维实现采用逆时针环绕顺序;也就是说,当从网格的正面看时,应以逆时针顺序指定用于确定正面网格三角形的位置的点。
            //对 TriangleIndices 属性的设置为可选操作。 如果不指定索引,则以非索引的方式绘制三角形。 每个组的三个位置将成为一个三角形。
            // 前面 逆时针从0号点开始,又回到0号点,组成2个三角形
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(0);

            // 背面
            mesh.TriangleIndices.Add(6);
            mesh.TriangleIndices.Add(5);
            mesh.TriangleIndices.Add(4);
            mesh.TriangleIndices.Add(4);
            mesh.TriangleIndices.Add(7);
            mesh.TriangleIndices.Add(6);

            // 右面
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(5);
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(5);
            mesh.TriangleIndices.Add(6);
            mesh.TriangleIndices.Add(2);

            // 上面
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(6);
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(6);
            mesh.TriangleIndices.Add(7);

            // 底面
            mesh.TriangleIndices.Add(5);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(4);
            mesh.TriangleIndices.Add(5);

            // 左面
            mesh.TriangleIndices.Add(4);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(7);
            mesh.TriangleIndices.Add(4);

            //父元素对象
            World = new ModelVisual3D();          //
            // 创建三维几何图形
            GeometryModel3D m3DGeometry = new GeometryModel3D();

            m3DGeometry.Geometry = mesh;
            //漫射材料
            m3DGeometry.Material = new DiffuseMaterial(Brushes.Red);
            ModelVisual3D box01 = new ModelVisual3D();

            box01.Content = m3DGeometry;

            //环境光元素设置
            ModelVisual3D ambientlight = new ModelVisual3D();          //
            AmbientLight  abl          = new AmbientLight();

            abl.Color            = Colors.Gray;
            ambientlight.Content = abl;                              //

            ModelVisual3D    directionallight = new ModelVisual3D(); //
            DirectionalLight dl = new DirectionalLight();

            dl.Color                 = Colors.White;
            dl.Direction             = new Vector3D(0, 0, -1);
            directionallight.Content = dl;

            //定义三维变换
            Transform3DGroup     traneform3dgroup = new Transform3DGroup();      //
            TranslateTransform3D tlt3d            = new TranslateTransform3D();

            tlt3d.OffsetX = 0;
            tlt3d.OffsetY = 0;
            tlt3d.OffsetZ = 0;
            traneform3dgroup.Children.Add(tlt3d);
            //尺寸大小变换设置
            ScaleTransform3D st3d = new ScaleTransform3D();

            st3d.CenterX = 0;
            st3d.CenterY = 0;
            st3d.CenterZ = 0;
            //缩小
            st3d.ScaleX = 1;
            st3d.ScaleY = 1;
            st3d.ScaleZ = 1;
            traneform3dgroup.Children.Add(st3d);
            //旋转变换设置
            RotateTransform3D rtf3d = new RotateTransform3D();

            rtf3d.CenterX = 0;
            rtf3d.CenterY = 0;
            rtf3d.CenterZ = 0;
            //设置绕指定轴进行指定角度的三维旋转
            AxisAngleRotation3D aar = new AxisAngleRotation3D();

            aar.Angle = angle;
            //旋转轴X分量、Y分量和Z分量组成的矢量
            aar.Axis       = new Vector3D(vX, vY, vZ);
            rtf3d.Rotation = aar;
            traneform3dgroup.Children.Add(rtf3d);
            World.Transform = traneform3dgroup;          //
            //环境光线加入3D模型组合体
            World.Children.Add(ambientlight);
            //定向光线加入3D模型组合体
            World.Children.Add(directionallight);
            World.Children.Add(box01);            //
            //三维变换组中的子变换数
            transforms = traneform3dgroup.Children.Count;
            //赋予3D控件
            this.viewport3d.Children.Add(World);
        }
Example #29
0
        public Vector3D ForwardKinematics(double[] angles)
        {
            FB = new Transform3DGroup();
            T  = new TranslateTransform3D(-2500, 0, 0);
            FB.Children.Add(T);

            F1 = new Transform3DGroup();
            T  = new TranslateTransform3D(0, 0, 0);
            R  = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[0].rotAxisX, joints[0].rotAxisY, joints[0].rotAxisZ), angles[0]), new Point3D(joints[0].rotPointX, joints[0].rotPointY, joints[0].rotPointZ));
            F1.Children.Add(R);
            F1.Children.Add(T);
            F1.Children.Add(FB);

            F2 = new Transform3DGroup();
            T  = new TranslateTransform3D(0, 0, 0);
            R  = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[1].rotAxisX, joints[1].rotAxisY, joints[1].rotAxisZ), angles[1]), new Point3D(joints[1].rotPointX, joints[1].rotPointY, joints[1].rotPointZ));
            F2.Children.Add(T);
            F2.Children.Add(R);
            F2.Children.Add(F1);

            F3 = new Transform3DGroup();
            T  = new TranslateTransform3D(0, 0, 0);
            R  = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[2].rotAxisX, joints[2].rotAxisY, joints[2].rotAxisZ), angles[2]), new Point3D(joints[2].rotPointX, joints[2].rotPointY, joints[2].rotPointZ));
            F3.Children.Add(T);
            F3.Children.Add(R);
            F3.Children.Add(F2);

            F4 = new Transform3DGroup();
            T  = new TranslateTransform3D(0, 0, 0);
            R  = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[3].rotAxisX, joints[3].rotAxisY, joints[3].rotAxisZ), angles[3]), new Point3D(joints[3].rotPointX, joints[3].rotPointY, joints[3].rotPointZ));
            F4.Children.Add(T);
            F4.Children.Add(R);
            F4.Children.Add(F3);

            F5 = new Transform3DGroup();
            T  = new TranslateTransform3D(0, 0, 0);
            R  = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[4].rotAxisX, joints[4].rotAxisY, joints[4].rotAxisZ), angles[4]), new Point3D(joints[4].rotPointX, joints[4].rotPointY, joints[4].rotPointZ));
            F5.Children.Add(T);
            F5.Children.Add(R);
            F5.Children.Add(F4);

            F6L = new Transform3DGroup();
            T   = new TranslateTransform3D(0, 0, 0);
            R   = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[5].rotAxisX, joints[5].rotAxisY, joints[5].rotAxisZ), angles[5]), new Point3D(joints[5].rotPointX, joints[5].rotPointY, joints[5].rotPointZ));
            F6L.Children.Add(T);
            F6L.Children.Add(R);
            F6L.Children.Add(F5);

            F6R = new Transform3DGroup();
            T   = new TranslateTransform3D(0, 0, 0);
            R   = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(joints[6].rotAxisX, joints[6].rotAxisY, joints[6].rotAxisZ), -angles[5]), new Point3D(joints[6].rotPointX, joints[6].rotPointY, joints[6].rotPointZ));
            F6R.Children.Add(T);
            F6R.Children.Add(R);
            F6R.Children.Add(F5);

            F7 = new Transform3DGroup();
            T  = new TranslateTransform3D(168, -2854, 3772);
            F7.Children.Add(T);
            F7.Children.Add(F5);

            FO1 = new Transform3DGroup();
            if (Boxs[0].g == 1)
            {
                FO1.Children.Add(Boxs[0].R);
                FO1.Children.Add(F7);
                FO1.Children.Add(new TranslateTransform3D(0, 0, -joints[8].model.Bounds.SizeZ + 150));
            }
            else
            {
                FO1.Children.Add(Boxs[0].R);
                FO1.Children.Add(Boxs[0].T);
            }

            FO2 = new Transform3DGroup();
            if (Boxs[1].g == 1)
            {
                FO2.Children.Add(Boxs[1].R);
                FO2.Children.Add(F7);
                FO2.Children.Add(new TranslateTransform3D(0, 0, -joints[9].model.Bounds.SizeZ + 150));
            }
            else
            {
                FO2.Children.Add(Boxs[1].R);
                FO2.Children.Add(Boxs[1].T);
            }

            FO3 = new Transform3DGroup();
            if (Boxs[2].g == 1)
            {
                FO3.Children.Add(Boxs[2].R);
                FO3.Children.Add(F7);
                FO3.Children.Add(new TranslateTransform3D(0, 0, -joints[10].model.Bounds.SizeZ + 150));
            }
            else
            {
                FO3.Children.Add(Boxs[2].R);
                FO3.Children.Add(Boxs[2].T);
            }

            FO4 = new Transform3DGroup();
            if (Boxs[3].g == 1)
            {
                FO4.Children.Add(Boxs[3].R);
                FO4.Children.Add(F7);
                FO4.Children.Add(new TranslateTransform3D(0, 0, -joints[11].model.Bounds.SizeZ + 150));
            }
            else
            {
                FO4.Children.Add(Boxs[3].R);
                FO4.Children.Add(Boxs[3].T);
            }

            joints[0].model.Transform  = F1;
            joints[1].model.Transform  = F2;
            joints[2].model.Transform  = F3;
            joints[3].model.Transform  = F4;
            joints[4].model.Transform  = F5;
            joints[5].model.Transform  = F6L;
            joints[6].model.Transform  = F6R;
            joints[7].model.Transform  = FB;
            joints[8].model.Transform  = FO1;
            joints[9].model.Transform  = FO2;
            joints[10].model.Transform = FO3;
            joints[11].model.Transform = FO4;
            joints[12].model.Transform = F7;

            return(new Vector3D(joints[12].model.Bounds.Location.X, joints[12].model.Bounds.Location.Y, joints[12].model.Bounds.Location.Z));
        }
Example #30
0
        /// <summary>
        /// Creates the visual representation for an edge.
        /// </summary>
        /// <param name="edge">The edge.</param>
        /// <param name="graphProvider">The <see cref="IGraphProvider"/>.</param>
        /// <param name="translateTransform1">The <see cref="TranslateTransform3D"/> of the visual element representing the first node of the edge.</param>
        /// <param name="translateTransform2">The <see cref="TranslateTransform3D"/> of the visual element representing the second node of the edge.</param>
        /// <returns>The visual representation for an edge.</returns>
        public static UIElement3D CreateVisual(this Edge <NodeData, EdgeData> edge, IGraphProvider graphProvider, TranslateTransform3D translateTransform1, TranslateTransform3D translateTransform2)
        {
            if (edge.Data == null)
            {
                edge.Data = new EdgeData();
            }

            if (edge.FirstNode == edge.SecondNode)
            {
                return(new SelfEdgeUIElement(graphProvider, edge, translateTransform1));
            }
            else
            {
                return(new RegularEdgeUIElement(graphProvider, edge, translateTransform1, translateTransform2));
            }
        }