Ejemplo n.º 1
0
        private void RebuildCustom()
        {
            try
            {
                pnlCustomError.Visibility = Visibility.Collapsed;

                #region Fix the row numbers

                for (int cntr = 0; cntr < _customRows.Count; cntr++)
                {
                    ((TextBlock)_customRows[cntr].Item2.Children[0]).Text = (cntr + 1).ToString();
                }

                txtCustomInsertIndex.Text = (_customRows.Count + 1).ToString();

                #endregion

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

                #region Parse the rows

                for (int cntr = 0; cntr < _customRows.Count; cntr++)
                {
                    StackPanel panel = _customRows[cntr].Item2;

                    // Distance
                    double distance = double.Parse(((TextBox)panel.Children[2]).Text);

                    switch (_customRows[cntr].Item1)
                    {
                    case "Poly":
                        TubeRingRegularPolygon poly = new TubeRingRegularPolygon(distance, false,
                                                                                 double.Parse(((TextBox)panel.Children[4]).Text),
                                                                                 double.Parse(((TextBox)panel.Children[6]).Text),
                                                                                 ((CheckBox)panel.Children[7]).IsChecked.Value);

                        rings.Add(poly);
                        break;

                    case "Point":
                        TubeRingPoint point = new TubeRingPoint(distance, false);

                        rings.Add(point);
                        break;

                    case "Dome":
                        TubeRingDome dome = new TubeRingDome(distance, false,
                                                             int.Parse(((TextBox)panel.Children[4]).Text));

                        rings.Add(dome);
                        break;

                    default:
                        throw new ApplicationException("Unknown type: " + _customRows[cntr].Item1);
                    }
                }

                #endregion

                MeshGeometry3D mesh = UtilityWPF.GetMultiRingedTube(int.Parse(txtNumSides.Text), rings, chkSoftSides.IsChecked.Value, true);

                // Material
                MaterialGroup material = new MaterialGroup();

                Color color = UtilityWPF.ColorFromHex(txtDiffuse.Text);
                material.Children.Add(new DiffuseMaterial(new SolidColorBrush(color)));

                if (chkSpecular.IsChecked.Value)
                {
                    color = UtilityWPF.ColorFromHex(txtSpecular.Text);
                    double power = double.Parse(txtSpecularPower.Text);

                    material.Children.Add(new SpecularMaterial(new SolidColorBrush(color), power));
                }

                if (chkEmissive.IsChecked.Value)
                {
                    color = UtilityWPF.ColorFromHex(txtEmissive.Text);
                    material.Children.Add(new EmissiveMaterial(new SolidColorBrush(color)));
                }

                // Geometry Model
                GeometryModel3D geometry = new GeometryModel3D();
                geometry.Material     = material;
                geometry.BackMaterial = material;

                geometry.Geometry = mesh;

                // Model Visual
                ModelVisual3D visual = new ModelVisual3D();
                visual.Content = geometry;

                // Store it
                SetCurrentVisual(visual);
            }
            catch (Exception ex)
            {
                pnlCustomError.Visibility = Visibility.Visible;
                lblCustomError.Text       = ex.Message;
            }
        }
Ejemplo n.º 2
0
        private void Load3DImages()
        {
            Model3DGroup  myModel3DGroup  = new Model3DGroup();
            ModelVisual3D myModelVisual3D = new ModelVisual3D();

            AmbientLight light = new AmbientLight(Color.FromRgb(96, 96, 96));

            myModel3DGroup.Children.Add(light);

            /*PointLight light2 = new PointLight(Colors.White, new Point3D(0, 0, 0.3));
             * myModel3DGroup.Children.Add(light2);
             * Point3DAnimation daLight = new Point3DAnimation(new Point3D(-10, 0, 0.3), new Point3D(10, 0, 0.3), TimeSpan.FromMilliseconds(25000).Duration());
             * light2.BeginAnimation(PointLight.PositionProperty, daLight);*/

            SpotLight light3 = new SpotLight(Colors.Red, new Point3D(0, 0, 10), new Vector3D(0, 0, -1), 90, 0);

            myModel3DGroup.Children.Add(light3);
            Vector3DAnimation daLight = new Vector3DAnimation(new Vector3D(-1, 0, -0.3), new Vector3D(1, 0, -0.3), TimeSpan.FromMilliseconds(15000).Duration());

            daLight.RepeatBehavior = RepeatBehavior.Forever;
            daLight.AutoReverse    = true;
            light3.BeginAnimation(SpotLight.DirectionProperty, daLight);

            /*ColorAnimation colorAnimation = new ColorAnimation(Colors.Red, Color.FromRgb(0, 0, 255), TimeSpan.FromSeconds(10).Duration());
             * colorAnimation.RepeatBehavior = RepeatBehavior.Forever;
             * colorAnimation.AutoReverse = true;
             * light3.BeginAnimation(SpotLight.ColorProperty, colorAnimation);*/

            myModelVisual3D.Content = myModel3DGroup;
            this.ImageWall3D.Children.Add(myModelVisual3D);

            allFiles = dataBase.GetAllFrontCovers(true);

            if (allFiles.Length == 0)
            {
                return;
            }

            // Shuffle
            allFiles = allFiles.OrderBy(file => random.Next()).ToArray();

            int    imageIndex = 0;
            double xPosStart  = -(double)imagesHorizontal / 2.0 - 31.415;
            double xPos       = xPosStart;
            double yPos       = (double)imagesVertical / 2.0;

            int xIndex = 0;
            int yIndex = 0;

            double centerX = 0;
            double centerZ = 20;
            double radius  = 20;

            List <BitmapImage> thumbnails = new List <BitmapImage>();

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += delegate
            {
                for (int i = 0; i < imagesHorizontal * imagesVertical; i++)
                {
                    if (imageIndex >= allFiles.Length)
                    {
                        imageIndex = 0;
                    }

                    BitmapImage bi = ImageLoader.GetThumbnailImage(allFiles[imageIndex]);

                    if (bi == null)
                    {
                        i--;
                        imageIndex++;
                        continue;
                    }

                    thumbnails.Add(bi);

                    imageIndex++;
                }
            };
            bw.RunWorkerCompleted += delegate
            {
                imageIndex = 0;
                for (int i = 0; i < imagesHorizontal * imagesVertical; i++)
                {
                    double circleXPos  = xPos / 20;
                    double circleXPos2 = xPos / 20 + 0.048;

                    double x1 = centerX + radius * Math.Cos(circleXPos);
                    double z1 = centerZ + radius * Math.Sin(circleXPos);

                    double x2 = centerX + radius * Math.Cos(circleXPos2);
                    double z2 = centerZ + radius * Math.Sin(circleXPos2);

                    Point3D leftTop     = new Point3D(x1, yPos, z1);
                    Point3D rightTop    = new Point3D(x2, yPos, z2);
                    Point3D leftBottom  = new Point3D(x1, yPos - 0.9, z1);
                    Point3D rightBottom = new Point3D(x2, yPos - 0.9, z2);

                    /*                Point3D leftTop = new Point3D(xPos, yPos, 0);
                     * Point3D rightTop = new Point3D(xPos+0.9, yPos, 0);
                     * Point3D leftBottom = new Point3D(xPos, yPos-0.9, 0);
                     * Point3D rightBottom = new Point3D(xPos+0.9, yPos-0.9, 0);*/
                    BitmapImage bi = thumbnails[imageIndex];

                    DiffuseMaterial material = new DiffuseMaterial(new ImageBrush(bi));

                    GeometryModel3D coverPlate = Create3DRectangle(leftTop, rightTop, leftBottom, rightBottom, material);

                    myModel3DGroup.Children.Add(coverPlate);

                    Transform3DGroup transformGroup = new Transform3DGroup();

                    TranslateTransform3D trans = new TranslateTransform3D();

                    DoubleAnimation daZ = new DoubleAnimation(30, 0, TimeSpan.FromMilliseconds(random.NextDouble() * 3000.0 + 5000.0).Duration());

                    daZ.EasingFunction = new PowerEase()
                    {
                        EasingMode = EasingMode.EaseInOut
                    };
                    trans.BeginAnimation(TranslateTransform3D.OffsetZProperty, daZ);

                    transformGroup.Children.Add(trans);

                    coverPlate.Transform = transformGroup;

                    xPos += 1;
                    xIndex++;

                    if (xIndex >= imagesHorizontal)
                    {
                        xIndex = 0;
                        xPos   = xPosStart;

                        yIndex++;
                        yPos -= 1;
                    }

                    imageIndex++;
                    if (imageIndex >= thumbnails.Count)
                    {
                        imageIndex = 0;
                    }
                }
            };

            bw.RunWorkerAsync();
        }
Ejemplo n.º 3
0
        private FrameworkElement CreateVisualChild()
        {
            MeshGeometry3D simpleQuad = new MeshGeometry3D()
            {
                Positions          = new Point3DCollection(_mesh),
                TextureCoordinates = new PointCollection(_texCoords),
                TriangleIndices    = new Int32Collection(_indices)
            };

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

            frontMaterial.SetValue(Viewport2DVisual3D.IsVisualHostMaterialProperty, true);

            VisualBrush vb = new VisualBrush(_logicalChild);

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

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

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

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

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

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

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

            UpdateRotation();

            return(_viewport3d);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates the model/geometry for a unit sphere centered at the origin.
        /// </summary>
        /// <param name="thetaSteps">The number of "around" steps to use when creating the sphere mesh</param>
        /// <param name="phiSteps">The number of "top to bottom" steps to use when creating the sphere mesh</param>
        /// <param name="material">A material to use when texturing the sphere</param>
        public static ModelVisual3D GenerateUnitSphere(int thetaSteps, int phiSteps, Material material)
        {
            if (thetaSteps < 3)
            {
                throw new ArgumentException("Must give at least three theta steps");
            }
            if (phiSteps < 3)
            {
                throw new ArgumentException("Must give at least three phi steps");
            }

            const double radius = 0.5; // always building a unit sphere.
            double       x, y, z;
            double       theta, phi;
            double       tPercent, pPercent;
            int          totalPoints = thetaSteps * phiSteps;

            MeshGeometry3D mesh = new MeshGeometry3D();

            // add all the points
            for (int tStep = 0; tStep <= thetaSteps; tStep++)
            {
                for (int pStep = 0; pStep < phiSteps; pStep++)
                {
                    tPercent = (double)tStep / (double)thetaSteps;
                    theta    = 2.0 * Math.PI * tPercent;
                    pPercent = (double)pStep / (double)(phiSteps - 1);
                    phi      = Math.PI * pPercent;
                    x        = radius * Math.Cos(theta) * Math.Sin(phi);
                    y        = radius * Math.Cos(phi);
                    z        = radius * Math.Sin(theta) * Math.Sin(phi);

                    mesh.Positions.Add(new Point3D(x, y, z));
                    mesh.Normals.Add(new Vector3D(x, y, z));
                    mesh.TextureCoordinates.Add(new Point(tPercent, pPercent));
                }
            }

            // go back over all the points and add triangles
            for (int tStep = 0; tStep < thetaSteps; tStep++)
            {
                for (int pStep = 0; pStep < phiSteps - 1; pStep++)
                {
                    int topLeft  = pStep + tStep * phiSteps;
                    int botLeft  = topLeft + 1;
                    int topRight = topLeft + phiSteps;
                    int botRight = topRight + 1;

                    mesh.TriangleIndices.Add(botLeft);
                    mesh.TriangleIndices.Add(topLeft);
                    mesh.TriangleIndices.Add(botRight);

                    mesh.TriangleIndices.Add(botRight);
                    mesh.TriangleIndices.Add(topLeft);
                    mesh.TriangleIndices.Add(topRight);
                }
            }

            GeometryModel3D model  = new GeometryModel3D(mesh, material);
            ModelVisual3D   sphere = new ModelVisual3D();

            sphere.Content = model;
            return(sphere);
        }
Ejemplo n.º 5
0
        protected override void BeginTransition3D(TransitionElement transitionElement, ContentPresenter oldContent, ContentPresenter newContent, Viewport3D viewport)
        {
            int  xparticles = 15, yparticles = 15;
            Size size = transitionElement.RenderSize;

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

            MeshGeometry3D mesh       = CreateMesh(new Point3D(), new Vector3D(size.Width, 0, 0), new Vector3D(0, size.Height, 0), xparticles - 1, yparticles - 1, new Rect(0, 0, 1, 1));
            Brush          cloneBrush = CreateBrush(transitionElement, oldContent);
            Material       clone      = new DiffuseMaterial(cloneBrush);

            double ustep = size.Width / (xparticles - 1), vstep = size.Height / (yparticles - 1);

            Point3DCollection points = mesh.Positions;

            Random rand = new Random();

            // add some random movement to the z order
            for (int i = 0; i < points.Count; i++)
            {
                points[i] += 0.1 * ustep * (rand.NextDouble() * 2 - 1) * new Vector3D(0, 0, 1);
            }

            Point3DCollection oldPoints = points.Clone();

            Vector3D        acceleration = new Vector3D(0, 700, 0); //gravity
            double          timeStep     = 1.0 / 60.0;
            DispatcherTimer timer        = new DispatcherTimer();

            timer.Interval = TimeSpan.FromSeconds(timeStep);
            bool   fading        = false;
            double time          = 0;
            double slideVelocity = size.Width / 2.0;
            double windScale     = 30 * size.Width * size.Height;

            timer.Tick += delegate
            {
                time = time + timeStep;
                Point   mousePos   = Mouse.GetPosition(viewport);
                Point3D mousePos3D = new Point3D(mousePos.X, mousePos.Y, -10);

                // Cloth physics based on work of Thomas Jakobsen http://www.teknikus.dk/tj/gdc2001.htm
                for (int i = 0; i < oldPoints.Count; i++)
                {
                    Point3D  currentPoint = points[i];
                    Vector3D wind         = new Vector3D(0, 0, windScale / (mousePos3D - currentPoint).LengthSquared);
                    Point3D  newPoint     = currentPoint + (currentPoint - oldPoints[i]) + timeStep * timeStep * (acceleration + wind);

                    if (newPoint.Y > size.Height)
                    {
                        newPoint.Y = size.Height;
                    }

                    oldPoints[i] = newPoint;
                }

                //for (int j = 0; j < 5; j++)
                for (int i = oldPoints.Count - 1; i > 0; i--)
                {
                    // constrain with point to the left
                    if (i > yparticles)
                    {
                        Constrain(oldPoints, i, i - yparticles, ustep);
                    }
                    // constrain with point to the top
                    if (i % yparticles != 0)
                    {
                        Constrain(oldPoints, i, i - 1, vstep);
                    }
                }

                // slide the top row of points to the left
                for (int i = 0; i < xparticles; i += 1)
                {
                    oldPoints[i * yparticles] = new Point3D(Math.Max(0, i * ustep - slideVelocity * time * i / (xparticles - 1)), 0, 0);
                }

                if (!fading && points[points.Count - yparticles].X < size.Width / 2)
                {
                    fading = true;
                    DoubleAnimation da = new DoubleAnimation(0, new Duration(TimeSpan.FromSeconds(1.5)));
                    da.Completed += delegate
                    {
                        timer.Stop();
                        EndTransition(transitionElement, oldContent, newContent);
                    };
                    cloneBrush.BeginAnimation(Brush.OpacityProperty, da);
                }

                // Swap position arrays
                mesh.Positions = oldPoints;
                oldPoints      = points;
                points         = mesh.Positions;
            };
            timer.Start();


            GeometryModel3D geo = new GeometryModel3D(mesh, clone);

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

            model.Content = geo;
            viewport.Children.Add(model);
        }
Ejemplo n.º 6
0
        void Create1()
        {
            int w = 256;
            int h = 256;

            var hm    = new double[w * h];
            var idmap = new byte[w * h];

            using (var br = new BinaryReader(File.OpenRead("data.raw")))
            {
                for (int i = 0; i < hm.Length; ++i)
                {
                    hm[i] = br.ReadDouble();
                }
                for (int i = 0; i < idmap.Length; ++i)
                {
                    idmap[i] = br.ReadByte();
                }
            }

            var gm3d = new GeometryModel3D();

            //gm3d.Material = new DiffuseMaterial(Brushes.Green);

            gm3d.Material = new DiffuseMaterial(new ImageBrush(new BitmapImage(new Uri(@"C:\\Users\\Tomba\\Work\\dwarrowdelf\\Client\\Client\\debgrad.png"))));

            MeshGeometry3D geom = new MeshGeometry3D();

            var points        = new Point3DCollection(w * h);
            var textureCoords = new PointCollection(w * h);

            for (int y = 0; y < h; ++y)
            {
                for (int x = 0; x < w; ++x)
                {
                    var z = hm[y * w + x];

                    points.Add(new Point3D(x, y, z));

                    switch (idmap[y * w + x])
                    {
                    case 0:
                        textureCoords.Add(new Point(0, 0));
                        break;

                    case 1:
                        textureCoords.Add(new Point(1, 1));
                        break;
                    }
                    //textureCoords.Add(new Point(0, 1));
                    //textureCoords.Add(new Point(1, 0));
                }
            }

            geom.Positions          = points;
            geom.TextureCoordinates = textureCoords;

            var indices = new Int32Collection((w - 1) * (h - 1) * 6);

            for (int y = 0; y < h - 1; ++y)
            {
                for (int x = 0; x < w - 1; ++x)
                {
                    indices.Add(y * w + x);
                    indices.Add(y * w + x + 1);
                    indices.Add((y + 1) * w + x);

                    indices.Add(y * w + x + 1);
                    indices.Add((y + 1) * w + x + 1);
                    indices.Add((y + 1) * w + x);
                }
            }
            geom.TriangleIndices = indices;

            gm3d.Geometry = geom;

            gm3d.Transform = new TranslateTransform3D(-w / 2, -h / 2, 0);

            ModelVisual3D model = new ModelVisual3D();

            model.Content = gm3d;
            this.viewPort.Children.Add(model);
        }
Ejemplo n.º 7
0
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Figure out the ratios and mass of this body
                ConvexBody3D.CollisionShape shape;
                double ratioX, ratioY, ratioZ, mass;
                GetRatiosMass(out shape, out ratioX, out ratioY, out ratioZ, out mass);

                #region WPF Model

                // Material
                MaterialGroup materials = new MaterialGroup();
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.GetRandomColor(64, 192))));
                materials.Children.Add(new SpecularMaterial(Brushes.White, 100d));

                // Geometry Model
                GeometryModel3D geometry = new GeometryModel3D();
                geometry.Material     = materials;
                geometry.BackMaterial = materials;

                switch (shape)
                {
                case ConvexBody3D.CollisionShape.Cube:
                    geometry.Geometry = UtilityWPF.GetCube(new Point3D(-ratioX, -ratioY, -ratioZ), new Point3D(ratioX, ratioY, ratioZ));
                    break;

                case ConvexBody3D.CollisionShape.Sphere:
                    geometry.Geometry = UtilityWPF.GetSphere_LatLon(5, ratioX, ratioY, ratioZ);
                    //geometry.Geometry = UtilityWPF.GetTorus(30, 10, ratioX * .2, ratioX);    //
                    break;

                case ConvexBody3D.CollisionShape.Capsule:
                case ConvexBody3D.CollisionShape.ChamferCylinder:
                case ConvexBody3D.CollisionShape.Cone:
                case ConvexBody3D.CollisionShape.Cylinder:
                default:
                    throw new ApplicationException("Unknown ConvexBody3D.CollisionShape: " + shape.ToString());
                }

                // Transform
                Transform3DGroup transform = new Transform3DGroup();            // rotate needs to be added before translate
                transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(Math3D.GetRandomVector_Spherical(10), Math1D.GetNearZeroValue(360d))));
                transform.Children.Add(new TranslateTransform3D(Math3D.GetRandomVector(CREATEOBJECTBOUNDRY)));

                // Model Visual
                ModelVisual3D model = new ModelVisual3D();
                model.Content   = geometry;
                model.Transform = transform;

                #endregion

                // Add to the viewport
                _viewport.Children.Add(model);

                // Make a physics body that represents this shape
                ConvexBody3D body = new ConvexBody3D(_world, model);

                body.Mass = Convert.ToSingle(mass);

                body.LinearDamping  = .01f;
                body.AngularDamping = new Vector3D(.01f, .01f, .01f);

                body.ApplyForce += new BodyForceEventHandler(Body_ApplyForce);

                _bodies.Add(body);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 8
0
        public XbimScene <WpfMeshGeometry3D, WpfMaterial> BuildScene(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <IPersistEntity> isolateInstances = null, List <IPersistEntity> hideInstances = null, List <Type> excludeTypes = null)
        {
            var excludedTypes   = model.DefaultExclusions(excludeTypes);
            var tmpOpaquesGroup = new Model3DGroup();
            var retScene        = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model);


            if (_model.Instances == null || !_model.Instances.Any())
            {
                return(retScene);
            }

            // define colours
            var colours = new Dictionary <LayerGroup, XbimColour>();

            colours.Add(LayerGroup.Green, new XbimColour("Green", 0.0, 1.0, 0.0, 0.5));
            colours.Add(LayerGroup.Red, new XbimColour("Red", 1.0, 0.0, 0.0, 0.5));
            colours.Add(LayerGroup.Amber, new XbimColour("Amber", .5, 0.5, .5, .8)); // actually grey

            // prepare meshes
            //

            var meshes = new List <WpfMeshGeometry3D>(); // this list gets added to the scene at the end.

            // this dictionary holds the list of meshes that are currently used, as they are filled (in size),
            // new ones get replaced
            //
            var meshDic = new Dictionary <LayerGroup, WpfMeshGeometry3D>();

            foreach (var group in colours.Keys)
            {
                var newItem = PrepareMesh(colours[group]);
                meshDic.Add(group, newItem);
                meshes.Add(newItem);
            }

            foreach (var mesh in meshes)
            {
                mesh.WpfModel.SetValue(FrameworkElement.TagProperty, mesh);
                mesh.BeginUpdate();
                tmpOpaquesGroup.Children.Add(mesh);
            }

            using (var geomStore = model.GeometryStore)
            {
                using (var geomReader = geomStore.BeginRead())
                {
                    var shapeInstances = geomReader.ShapeInstances
                                         .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded
                                                &&
                                                !excludedTypes.Contains(s.IfcTypeId));
                    foreach (var shapeInstance in shapeInstances)
                    {
                        var ent = _model.Instances[shapeInstance.IfcProductLabel];
                        var grp = GetLayerGroup(ent);
                        if (grp == LayerGroup.Null)
                        {
                            continue;
                        }
                        if (!UseAmber && grp == LayerGroup.Amber)
                        {
                            continue;
                        }

                        WpfMeshGeometry3D targetMergeMesh;
                        meshDic.TryGetValue(grp, out targetMergeMesh);

                        if (targetMergeMesh == null)
                        {
                            continue;
                        }

                        // replace target mesh beyond suggested size
                        // https://docs.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/maximize-wpf-3d-performance
                        //
                        if (targetMergeMesh.PositionCount > 20000
                            ||
                            targetMergeMesh.TriangleIndexCount > 60000
                            )
                        {
                            // end current mesh
                            targetMergeMesh.EndUpdate();

                            // prepare new one and add to the list
                            var replace = PrepareMesh(colours[grp]);
                            meshes.Add(replace);

                            // swap mesh in dicionary and for this loop
                            meshDic[grp]    = replace;
                            targetMergeMesh = replace;

                            // prepare in output
                            replace.WpfModel.SetValue(FrameworkElement.TagProperty, replace);
                            replace.BeginUpdate();
                            tmpOpaquesGroup.Children.Add(replace);
                        }

                        IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                        if (shapeGeom.Format == (byte)XbimGeometryType.PolyhedronBinary)
                        {
                            var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation,
                                                                  modelTransform);
                            targetMergeMesh.Add(
                                shapeGeom.ShapeData,
                                shapeInstance.IfcTypeId,
                                shapeInstance.IfcProductLabel,
                                shapeInstance.InstanceLabel, transform,
                                (short)model.UserDefinedId);
                        }
                    }
                }
            }
            foreach (var mesh in meshDic.Values)
            {
                mesh.EndUpdate();
            }
            if (!tmpOpaquesGroup.Children.Any())
            {
                return(retScene);
            }
            var mv = new ModelVisual3D {
                Content = tmpOpaquesGroup
            };

            opaqueShapes.Children.Add(mv);
            return(retScene);
        }
 private void Window_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.W)
     {
         is_pressed_W = true;
     }
     if (e.Key == Key.S)
     {
         is_pressed_S = true;
     }
     if (e.Key == Key.A)
     {
         is_pressed_A = true;
     }
     if (e.Key == Key.D)
     {
         is_pressed_D = true;
     }
     if (e.Key == Key.LeftShift)
     {
         is_pressed_LeftShift = true;
     }
     if (e.Key == Key.Space)
     {
         is_pressed_Space = true;
     }
     if (e.Key == Key.R)
     {
         mainViewport.Children.Clear();
         Model3DGroup  myModel3DGroup  = new Model3DGroup();
         ModelVisual3D myModelVisual3D = new ModelVisual3D();
         PointLight    light           = new PointLight(Colors.White, new Point3D(0, 5, 0));
         myModel3DGroup.Children.Add(light);
         myModelVisual3D.Content = myModel3DGroup;
         mainViewport.Children.Add(myModelVisual3D);
         setup_vectors((int)field_size, (int)field_size);
         window.Title = "Регенерация...";
         for (double x = 0; x < field_size - 1; x += cube_size)
         {
             for (double y = 0; y < field_size - 1; y += cube_size)
             {// Вызываем функцию для генерации значения
                 double height = get_perlin_noise(x, y);
                 if (height < -0.2)
                 {
                     drawCubeByOnePoint(new Point3D(x, height, y), cube_size, Colors.Blue, mainViewport);
                 }
                 else if ((height >= -0.2) && (height <= -0.1))
                 {
                     drawCubeByOnePoint(new Point3D(x, height, y), cube_size, Colors.Yellow, mainViewport);
                 }
                 else if ((height >= -0.1) && (height <= 0))
                 {
                     drawCubeByOnePoint(new Point3D(x, height, y), cube_size, Colors.GreenYellow, mainViewport);
                 }
                 else if ((height >= 0) && (height <= 0.3))
                 {
                     drawCubeByOnePoint(new Point3D(x, height, y), cube_size, Colors.LimeGreen, mainViewport);
                 }
                 else
                 {
                     drawCubeByOnePoint(new Point3D(x, height, y), cube_size, Colors.Green, mainViewport);
                 }
             }
         }
         window.Title = "Регенерация завершена!";
         Thread.Sleep(2000);
         window.Title = "Введение в 3D";
     }
 }
        private void CreateSceneObjects()
        {
            // NOTE:
            // It is recommended to use meter as basic unit for all 3D objects used by VR.

            var rootVisual3D = new ModelVisual3D();

            var wireGridVisual3D = new WireGridVisual3D()
            {
                CenterPosition   = new Point3D(0, 0, 0),
                Size             = new Size(3, 3), // 3 x 3 meters
                WidthCellsCount  = 10,
                HeightCellsCount = 10,
                LineColor        = Colors.Gray,
                LineThickness    = 2
            };

            rootVisual3D.Children.Add(wireGridVisual3D);


            double centerX      = 0;
            double centerZ      = 0;
            double circleRadius = 1;

            var boxMaterial    = new DiffuseMaterial(Brushes.Gray);
            var sphereMaterial = new MaterialGroup();

            sphereMaterial.Children.Add(new DiffuseMaterial(Brushes.Silver));
            sphereMaterial.Children.Add(new SpecularMaterial(Brushes.White, 16));

            for (int a = 0; a < 360; a += 36)
            {
                double rad = SharpDX.MathUtil.DegreesToRadians(a);
                double x   = Math.Sin(rad) * circleRadius + centerX;
                double z   = Math.Cos(rad) * circleRadius + centerZ;

                var boxVisual3D = new BoxVisual3D()
                {
                    CenterPosition = new Point3D(x, 0.3, z),
                    Size           = new Size3D(0.2, 0.6, 0.2),
                    Material       = boxMaterial
                };

                var sphereVisual3D = new SphereVisual3D()
                {
                    CenterPosition = new Point3D(x, 0.75, z),
                    Radius         = 0.15,
                    Material       = sphereMaterial
                };

                rootVisual3D.Children.Add(boxVisual3D);
                rootVisual3D.Children.Add(sphereVisual3D);
            }

            MainViewport.Children.Clear();
            MainViewport.Children.Add(rootVisual3D);

            Camera1.Heading  = 25;
            Camera1.Attitude = -20;
            Camera1.Distance = 4; // 3 meters

            Camera1.Refresh();
        }
Ejemplo n.º 11
0
        public LightVisual3D(object modelVisual3D)
        {
            ModelVisual3D mv = modelVisual3D as ModelVisual3D;

            Children.Add(mv);
        }
Ejemplo n.º 12
0
 private void Add(Model3D model, ModelVisual3D visual)
 {
     visual.Children.Add(new ModelVisual3D {
         Content = model
     });
 }
Ejemplo n.º 13
0
 private void Clear(ModelVisual3D visual)
 {
     visual.Children.Clear();
 }
Ejemplo n.º 14
0
        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            // cubit.Model.Freeze();
            // cubit.Material.Freeze();
            var cuboidGeometry = cubit.Model.Geometry as MeshGeometry3D;

            var vis = new ModelVisual3D();

            bool allInOneGeometry = true;

            MeshBuilder builder = null;

            if (allInOneGeometry)
            {
                builder = new MeshBuilder();
            }

            int countAll      = 0;
            int countModelled = 0;

            for (int i = 0; i < nvert; i++)
            {
                double m  = nside - i * (double)nside / nvert;
                var    mx = (int)m;
                Debug.WriteLine(i + ": " + mx);
                for (int j = 0; j <= mx; j++)
                {
                    for (int k = 0; k <= mx; k++)
                    {
                        countAll++;

                        // only adding blocks on the outside...
                        if (j > 0 && j < mx - 1 && i > 0 && i < nvert - 1 && k > 0 && k < mx - 1)
                        {
                            continue;
                        }

                        countModelled++;

                        var center = new Point3D(a * (j - (double)mx / 2), a * (k - (double)mx / 2), (i + 0.5) * a);

                        if (allInOneGeometry)
                        {
                            builder.AddBox(center, a * b, a * b, a * b);
                        }
                        else
                        {
                            // add a new visual for each cubit, but reuse the geometry
                            var transform = new TranslateTransform3D(center.ToVector3D());
                            var c         = new ModelVisual3D
                            {
                                Content =
                                    new GeometryModel3D
                                {
                                    Geometry  = cuboidGeometry,
                                    Material  = cubit.Material,
                                    Transform = transform
                                }
                            };
                            vis.Children.Add(c);
                        }
                    }
                }
            }

            if (allInOneGeometry)
            {
                var c = new ModelVisual3D
                {
                    Content =
                        new GeometryModel3D
                    {
                        Geometry = builder.ToMesh(),
                        Material = cubit.Material
                    }
                };
                view1.Children.Add(c);
            }
            else
            {
                view1.Children.Add(vis);
            }

            var mg        = cubit.Model.Geometry as MeshGeometry3D;
            int ntri      = mg.TriangleIndices.Count / 3;
            int ntriTotal = ntri * countModelled;

            if (allInOneGeometry)
            {
                ntriTotal = builder.TriangleIndices.Count / 3;
            }

            Title = "Mini Pyramid, total " + countAll + " cubits, rendered with " + countModelled + " cubits / " + ntriTotal +
                    " triangles.";

            view1.LookAt(new Point3D(0, 0, a * nvert / 2), new Vector3D(-70, -60, -100), 0);
        }
        private void CreateScene()
        {
            // Create material with 10 x 10 numbers grid
            var imageBrush = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/Resources/10x10-texture.png")));

            var material = new DiffuseMaterial(imageBrush);
            //var material = new DiffuseMaterial(Brushes.Silver);


            // Create box with 10 x 10 x 10 cells
            var boxVisual3D = new BoxVisual3D()
            {
                UseCachedMeshGeometry3D = false, // This will generate a new MeshGeometry3D for this BoxVisual3D,
                FreezeMeshGeometry3D    = false, // This will allow us to change the TextureCoordinates
                CenterPosition          = new Point3D(-150, 0, -50),
                Size        = new Size3D(60, 60, 60),
                XCellsCount = 10,
                YCellsCount = 10,
                ZCellsCount = 10,
                Material    = material,
            };

            MainViewport.Children.Add(boxVisual3D);


            var cylinderVisual3D = new CylinderVisual3D()
            {
                BottomCenterPosition = new Point3D(-50, -30, -50),
                Radius   = 30,
                Height   = 60,
                Segments = 10,
                IsSmooth = false,
                Material = material
            };

            MainViewport.Children.Add(cylinderVisual3D);


            var sphereVisual3D = new SphereVisual3D()
            {
                UseCachedMeshGeometry3D = false, // This will generate a new MeshGeometry3D for this BoxVisual3D,
                FreezeMeshGeometry3D    = false, // This will allow us to change the TextureCoordinates
                CenterPosition          = new Point3D(50, 0, -50),
                Radius   = 30,
                Material = material
            };

            MainViewport.Children.Add(sphereVisual3D);


            // Add dragon model
            string fileName         = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\ObjFiles\\dragon_vrip_res3.obj");
            var    objModelVisual3D = new ObjModelVisual3D()
            {
                Source          = new Uri(fileName, UriKind.Absolute),
                SizeX           = 70,
                Position        = new Point3D(-150, 0, 100),
                PositionType    = ObjModelVisual3D.VisualPositionType.Center,
                DefaultMaterial = material,
            };

            Ab3d.Utilities.ModelUtils.ChangeMaterial(objModelVisual3D.Content, material, newBackMaterial: null);

            MainViewport.Children.Add(objModelVisual3D);


            // Add simple extruded shape
            var extrudePositions = new Point[]
            {
                new Point(-1, 54),
                new Point(13, 35),
                new Point(8, 32),
                new Point(18, 13),
                new Point(11, 9),
                new Point(23, -13),
                new Point(6, -14),
                new Point(6, -29),
                new Point(-8, -30),
                new Point(-7, -13),
                new Point(-25, -9),
                new Point(-12, 9),
                new Point(-25, 16),
                new Point(-8, 31),
                new Point(-16, 38)
            };

            var extrudedMesh = Mesh3DFactory.CreateExtrudedMeshGeometry(positions: extrudePositions.ToList(),
                                                                        isSmooth: false,
                                                                        modelOffset: new Vector3D(-50, -15, 100),
                                                                        extrudeVector: new Vector3D(0, 30, 0),
                                                                        shapeYVector: new Vector3D(0, 0, -1),
                                                                        textureCoordinatesGenerationType: ExtrudeTextureCoordinatesGenerationType.AddAdditionalPositions);

            var geometryModel3D = new GeometryModel3D(extrudedMesh, material);

            var modelVisual3D = new ModelVisual3D();

            modelVisual3D.Content = geometryModel3D;

            MainViewport.Children.Add(modelVisual3D);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// This version uses the new Geometry representation
        /// </summary>
        /// <param name="model"></param>
        /// <param name="context"></param>
        /// <param name="exclude">List of type to exclude, by default excplict openings and spaces are excluded if exclude = null</param>
        /// <returns></returns>
        private void BuildScene(Xbim3DModelContext context)
        {
            //get a list of all the unique styles
            Dictionary <int, WpfMaterial>       styles          = new Dictionary <int, WpfMaterial>();
            Dictionary <int, MeshGeometry3D>    shapeGeometries = new Dictionary <int, MeshGeometry3D>();
            Dictionary <int, WpfMeshGeometry3D> meshSets        = new Dictionary <int, WpfMeshGeometry3D>();
            Model3DGroup opaques      = new Model3DGroup();
            Model3DGroup transparents = new Model3DGroup();

            foreach (var shapeGeom in context.ShapeGeometries())
            {
                MeshGeometry3D wpfMesh = new MeshGeometry3D();
                wpfMesh.SetValue(TagProperty, shapeGeom); //don't read the geometry into the mesh yet as we do not know where the instance is located
                shapeGeometries.Add(shapeGeom.ShapeLabel, wpfMesh);
            }


            foreach (var style in context.SurfaceStyles())
            {
                WpfMaterial wpfMaterial = new WpfMaterial();
                wpfMaterial.CreateMaterial(style);
                styles.Add(style.DefinedObjectId, wpfMaterial);
                WpfMeshGeometry3D mg = new WpfMeshGeometry3D(wpfMaterial, wpfMaterial);
                meshSets.Add(style.DefinedObjectId, mg);
                if (style.IsTransparent)
                {
                    transparents.Children.Add(mg);
                }
                else
                {
                    opaques.Children.Add(mg);
                }
            }

            ////if (!styles.Any()) return ; //this should always have something unless the model is empty
            ////double metre = model.ModelFactors.OneMetre;
            ////XbimMatrix3D wcsTransform = XbimMatrix3D.CreateTranslation(_modelTranslation) * XbimMatrix3D.CreateScale((float)(1 / metre));

            ////foreach (var shapeInstance in context.ShapeInstances()
            ////        .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded &&
            ////            !typeof(IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) &&
            ////            !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))))
            ////{
            ////    int styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1;

            ////    //GET THE ACTUAL GEOMETRY
            ////    MeshGeometry3D wpfMesh;
            ////    //see if we have already read it
            ////    if (shapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh))
            ////    {
            ////        GeometryModel3D mg = new GeometryModel3D(wpfMesh, styles[styleId]);
            ////        mg.SetValue(TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId));
            ////        mg.BackMaterial = mg.Material;
            ////        mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform).ToMatrixTransform3D();
            ////        if (styles[styleId].IsTransparent)
            ////            transparents.Children.Add(mg);
            ////        else
            ////            opaques.Children.Add(mg);
            ////    }
            ////    else //we need to get the shape geometry
            ////    {
            ////        XbimShapeGeometry shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
            ////        if (shapeGeom.ReferenceCount > 1) //only store if we are going to use again
            ////        {
            ////            wpfMesh = new MeshGeometry3D();
            ////            wpfMesh.Read(shapeGeom.ShapeData);
            ////            shapeGeometries.Add(shapeInstance.ShapeGeometryLabel, wpfMesh);
            ////            GeometryModel3D mg = new GeometryModel3D(wpfMesh, styles[styleId]);
            ////            mg.SetValue(TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId));
            ////            mg.BackMaterial = mg.Material;
            ////            mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform).ToMatrixTransform3D();
            ////            if (styles[styleId].IsTransparent)
            ////                transparents.Children.Add(mg);
            ////            else
            ////                opaques.Children.Add(mg);
            ////        }
            ////        else //it is a one off, merge it with shapes of a similar material
            ////        {
            ////            WpfMeshGeometry3D mg = meshSets[styleId];
            ////            mg.Add(shapeGeom.ShapeData,
            ////                shapeInstance.IfcTypeId,
            ////                shapeInstance.IfcProductLabel,
            ////                shapeInstance.InstanceLabel,
            ////                XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform), 0);
            ////        }
            ////    }

            ////}

            if (opaques.Children.Any())
            {
                ModelVisual3D mv = new ModelVisual3D();
                mv.Content = opaques;
                Opaques.Children.Add(mv);
                if (_modelBounds.IsEmpty)
                {
                    _modelBounds = mv.Content.Bounds.ToXbimRect3D();
                }
                else
                {
                    _modelBounds.Union(mv.Content.Bounds.ToXbimRect3D());
                }
            }
            if (transparents.Children.Any())
            {
                ModelVisual3D mv = new ModelVisual3D();
                mv.Content = transparents;
                Transparents.Children.Add(mv);
                if (_modelBounds.IsEmpty)
                {
                    _modelBounds = mv.Content.Bounds.ToXbimRect3D();
                }
                else
                {
                    _modelBounds.Union(mv.Content.Bounds.ToXbimRect3D());
                }
            }
        }
 private void GenerateTextureCoordinates(ModelVisual3D visual3D)
 {
     GenerateTextureCoordinates(visual3D.Content);
 }
Ejemplo n.º 18
0
 public TerrainVisual3D()
 {
     visualChild = new ModelVisual3D();
     Children.Add(visualChild);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Create a face of the cube
        /// </summary>
        /// <param name="f">The face that needs to be created</param>
        /// <param name="m">Materal to be applied to the face</param>
        private void createFace(CubeFace f, Material m)
        {
            Point3D p0 = new Point3D();
            Point3D p1 = new Point3D();
            Point3D p2 = new Point3D();
            Point3D p3 = new Point3D();

            switch (f)
            {
            case CubeFace.F:
                /**
                 *  /--------/
                 * 0-------3 |
                 * |       | |
                 * |       | /
                 * 1-------2/
                 */
                p0.X = origin.X;
                p0.Y = origin.Y + edge_len;
                p0.Z = origin.Z + edge_len;

                p1.X = origin.X;
                p1.Y = origin.Y;
                p1.Z = origin.Z + edge_len;

                p2.X = origin.X + edge_len;
                p2.Y = origin.Y;
                p2.Z = origin.Z + edge_len;

                p3.X = origin.X + edge_len;
                p3.Y = origin.Y + edge_len;
                p3.Z = origin.Z + edge_len;
                break;

            case CubeFace.R:
                /**
                 *  /--------3
                 * /-------0 |
                 * |       | |
                 * |       | 2
                 * |-------1/
                 */
                p0.X = origin.X + edge_len;
                p0.Y = origin.Y + edge_len;
                p0.Z = origin.Z + edge_len;

                p1.X = origin.X + edge_len;
                p1.Y = origin.Y;
                p1.Z = origin.Z + edge_len;

                p2.X = origin.X + edge_len;
                p2.Y = origin.Y;
                p2.Z = origin.Z;

                p3.X = origin.X + edge_len;
                p3.Y = origin.Y + edge_len;
                p3.Z = origin.Z;
                break;

            case CubeFace.B:
                /**
                 *  3--------0
                 * /-------/ |
                 * | |     | |
                 * | 2 ----|-1
                 * |-------|/
                 */
                p0.X = origin.X + edge_len;
                p0.Y = origin.Y + edge_len;
                p0.Z = origin.Z;

                p1.X = origin.X + edge_len;
                p1.Y = origin.Y;
                p1.Z = origin.Z;

                p2 = origin;

                p3.X = origin.X;
                p3.Y = origin.Y + edge_len;
                p3.Z = origin.Z;
                break;

            case CubeFace.L:
                /**
                 *  0--------/
                 * 3-------/ |
                 * | |     | |
                 * | 1 ----|-/
                 * 2-------|/
                 */
                p0.X = origin.X;
                p0.Y = origin.Y + edge_len;
                p0.Z = origin.Z;

                p1 = origin;

                p2.X = origin.X;
                p2.Y = origin.Y;
                p2.Z = origin.Z + edge_len;

                p3.X = origin.X;
                p3.Y = origin.Y + edge_len;
                p3.Z = origin.Z + edge_len;
                break;

            case CubeFace.U:
                /**
                 *  0--------3
                 * 1-------2 |
                 * |       | |
                 * |       | |
                 * |-------|/
                 */
                p0.X = origin.X;
                p0.Y = origin.Y + edge_len;
                p0.Z = origin.Z;

                p1.X = origin.X;
                p1.Y = origin.Y + edge_len;
                p1.Z = origin.Z + edge_len;

                p2.X = origin.X + edge_len;
                p2.Y = origin.Y + edge_len;
                p2.Z = origin.Z + edge_len;

                p3.X = origin.X + edge_len;
                p3.Y = origin.Y + edge_len;
                p3.Z = origin.Z;
                break;

            case CubeFace.D:
                /**
                 *  /--------/
                 * /-------/ |
                 * | |     | |
                 * | 0 ----|-1
                 * 3-------|2
                 */
                p0 = origin;

                p1.X = origin.X + edge_len;
                p1.Y = origin.Y;
                p1.Z = origin.Z;

                p2.X = origin.X + edge_len;
                p2.Y = origin.Y;
                p2.Z = origin.Z + edge_len;

                p3.X = origin.X;
                p3.Y = origin.Y;
                p3.Z = origin.Z + edge_len;
                break;
            }

            ModelVisual3D r1 = new ModelVisual3D();
            ModelVisual3D r2 = new ModelVisual3D();

            r1.Content = Helpers.createTriangleModel(p0, p1, p2, m);
            r2.Content = Helpers.createTriangleModel(p0, p2, p3, m);

            this.Children.Add(r1);
            this.Children.Add(r2);
        }
Ejemplo n.º 20
0
        void Create2()
        {
            int w = 256;
            int h = 256;

            var hm    = new double[w * h];
            var idmap = new byte[w * h];

            using (var br = new BinaryReader(File.OpenRead("data.raw")))
            {
                for (int i = 0; i < hm.Length; ++i)
                {
                    hm[i] = br.ReadDouble();
                }
                for (int i = 0; i < idmap.Length; ++i)
                {
                    idmap[i] = br.ReadByte();
                }
            }

            var gm3d = new GeometryModel3D();

            //gm3d.Material = new DiffuseMaterial(Brushes.Green);
            gm3d.Material = new DiffuseMaterial(new ImageBrush(new BitmapImage(new Uri(@"C:\\Users\\Tomba\\Work\\dwarrowdelf\\Client\\Client\\debgrad.png"))));

            MeshGeometry3D geom = new MeshGeometry3D();

            var points        = new Point3DCollection(w * h);
            var textureCoords = new PointCollection(w * h);
            var indices       = new Int32Collection((w - 1) * (h - 1) * 6);

            for (int y = 0; y < h - 1; ++y)
            {
                for (int x = 0; x < w - 1; ++x)
                {
                    Func <int, int, Point3D> f = (_x, _y) => new Point3D(_x, _y, hm[_y * w + _x] * 3);

                    var tl = f(x, y);
                    var tr = f(x + 1, y);
                    var bl = f(x, y + 1);
                    var br = f(x + 1, y + 1);

                    Func <Point3D, Point> tc = (p) =>
                    {
                        switch (idmap[(int)(p.Y) * w + (int)(p.X)])
                        {
                        case 0:
                            return(new Point(0, 0));

                        case 1:
                            return(new Point(1, 1));
                        }
                        throw new Exception();
                    };

                    points.Add(tl);
                    points.Add(tr);
                    points.Add(bl);

                    textureCoords.Add(tc(tl));
                    textureCoords.Add(tc(tr));
                    textureCoords.Add(tc(bl));

                    points.Add(br);
                    points.Add(bl);
                    points.Add(tr);

                    textureCoords.Add(tc(br));
                    textureCoords.Add(tc(bl));
                    textureCoords.Add(tc(tr));
                }
            }

            geom.Positions          = points;
            geom.TextureCoordinates = textureCoords;

            gm3d.Geometry = geom;

            gm3d.Transform = new TranslateTransform3D(-w / 2, -h / 2, 0);

            ModelVisual3D model = new ModelVisual3D();

            model.Content = gm3d;
            this.viewPort.Children.Add(model);
        }
        private ModelVisual3D GetToolModel(Tool tool)
        {
            ModelVisual3D mv = null;

            MachineElementViewModel modelFactory(string s) => new MachineElementViewModel()
            {
                Name = s
            };

            switch (tool.ToolType)
            {
            case ToolType.None:
                break;

            case ToolType.Base:
                break;

            case ToolType.Simple:
                mv = ToolsMeshHelper.GetSimpleModel(tool, Position, Direction, modelFactory);
                break;

            case ToolType.TwoSection:
                mv = ToolsMeshHelper.GetTwoSectionModel(tool, Position, Direction, modelFactory);
                break;

            case ToolType.Pointed:
                mv = ToolsMeshHelper.GetPointedModel(tool, Position, Direction, modelFactory);
                break;

            case ToolType.Disk:
                mv = ToolsMeshHelper.GetDiskModel(tool, Position, Direction, modelFactory);
                break;

            case ToolType.BullNoseConcave:
                break;

            case ToolType.BullNoseConvex:
                break;

            case ToolType.Composed:
                break;

            case ToolType.Countersink:
                mv = ToolsMeshHelper.GetCountersinkModel(tool, Position, Direction, modelFactory);
                break;

            case ToolType.DiskOnCone:
                mv = ToolsMeshHelper.GetDiskOnConeModel(tool, Position, Direction, modelFactory);
                break;

            case ToolType.AngularTransmissionImpl:
                mv = ToolsMeshHelper.GetAngolarTransmissionModell(tool, Position, Direction, modelFactory);
                break;

            default:
                break;
            }

            if (mv == null)
            {
                throw new NotImplementedException();
            }

            if (mv is MachineElementViewModel mevm)
            {
                mevm.Name = tool.Name;
            }

            return(mv);
        }
Ejemplo n.º 22
0
        XbimScene <WpfMeshGeometry3D, WpfMaterial> ILayerStyler.BuildScene(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <Type> exclude)
        {
            var excludedTypes   = model.DefaultExclusions(exclude);
            var tmpOpaquesGroup = new Model3DGroup();
            var retScene        = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model);
            var meshes          = new List <WpfMeshGeometry3D>();

            if (_discriminator == null)
            {
                _discriminator = new VisualDiscriminator(_window.Doc);
            }

            if (_model.Instances == null || !_model.Instances.Any())
            {
                return(retScene);
            }

            var red   = PrepareMesh(_colourFail); meshes.Add(red);
            var green = PrepareMesh(_colourPass); meshes.Add(green);
            var blue  = PrepareMesh(_colourNa); meshes.Add(blue);
            var amber = PrepareMesh(_colourWarning); meshes.Add(amber);

            foreach (var mesh in meshes)
            {
                mesh.WpfModel.SetValue(FrameworkElement.TagProperty, mesh);
                mesh.BeginUpdate();
                tmpOpaquesGroup.Children.Add(mesh);
            }

            using (var geomStore = model.GeometryStore)
            {
                using (var geomReader = geomStore.BeginRead())
                {
                    var shapeInstances = geomReader.ShapeInstances
                                         .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded
                                                &&
                                                !excludedTypes.Contains(s.IfcTypeId));
                    foreach (var shapeInstance in shapeInstances)
                    {
                        var ent = _model.Instances[shapeInstance.IfcProductLabel];
                        var grp = _discriminator.GetLayerGroup(ent);

                        if (grp == VisualDiscriminator.LayerGroup.Null)
                        {
                            continue;
                        }
                        if (!UseBlue && grp == VisualDiscriminator.LayerGroup.Blue)
                        {
                            continue;
                        }
                        if (!UseAmber && grp == VisualDiscriminator.LayerGroup.Amber)
                        {
                            continue;
                        }

                        WpfMeshGeometry3D targetMergeMesh = null;

                        switch (grp)
                        {
                        case VisualDiscriminator.LayerGroup.Red:
                            targetMergeMesh = red;
                            break;

                        case VisualDiscriminator.LayerGroup.Green:
                            targetMergeMesh = green;
                            break;

                        case VisualDiscriminator.LayerGroup.Blue:
                            targetMergeMesh = blue;
                            break;

                        case VisualDiscriminator.LayerGroup.Amber:
                            targetMergeMesh = amber;
                            break;
                        }
                        if (targetMergeMesh == null)
                        {
                            continue;
                        }

                        IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                        if (shapeGeom.Format == (byte)XbimGeometryType.PolyhedronBinary)
                        {
                            var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation,
                                                                  modelTransform);
                            targetMergeMesh.Add(
                                shapeGeom.ShapeData,
                                shapeInstance.IfcTypeId,
                                shapeInstance.IfcProductLabel,
                                shapeInstance.InstanceLabel, transform,
                                (short)model.UserDefinedId);
                        }
                    }
                }
            }
            foreach (var mesh in meshes)
            {
                mesh.EndUpdate();
            }
            if (!tmpOpaquesGroup.Children.Any())
            {
                return(retScene);
            }
            var mv = new ModelVisual3D {
                Content = tmpOpaquesGroup
            };

            opaqueShapes.Children.Add(mv);
            // no transparents are present
            //if (tmpTransparentsGroup.Children.Any())
            //{
            //    var mv = new ModelVisual3D { Content = tmpTransparentsGroup };
            //    transparentShapes.Children.Add(mv);
            //}
            return(retScene);
        }
Ejemplo n.º 23
0
        public TreasureBox(Point3D position, double mass, double hitPoints, int materialID, World world, DamageProps damageMultipliers, object[] containedTreasureDNA = null)
        {
            const double RADIUS = .75d / 2d;
            const double HEIGHT = 1.5d;

            const double RING_Z1 = (HEIGHT / 2d) * .5d;     // this is distance from the end cap
            const double RING_Z2 = (HEIGHT / 2d) - RING_Z1; // this one is distance from the origin

            const double RINGRADIUS_INNER = RADIUS * .5d;
            const double RINGRADIUS_OUTER = RADIUS * 1.05d;
            const double RINGHEIGHT       = HEIGHT * .05d;

            const int DOMESEGMENTS     = 3;
            const int CYLINDERSEGMENTS = 8;
            const int RINGSEGMENTS     = 8;

            #region WPF Model

            Model3DGroup geometries = new Model3DGroup();

            #region Barrel

            // Material
            MaterialGroup material = new MaterialGroup();
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("413D34"))));
            material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("60C5CAA7")), 2d));// .25d));

            // Geometry Model
            GeometryModel3D geometry = new GeometryModel3D();
            geometry.Material     = material;
            geometry.BackMaterial = material;

            List <TubeRingBase> rings = new List <TubeRingBase>();
            rings.Add(new TubeRingDome(0d, false, DOMESEGMENTS));
            rings.Add(new TubeRingRegularPolygon(RING_Z1, false, RADIUS, RADIUS, false));
            rings.Add(new TubeRingRegularPolygon(HEIGHT - (RING_Z1 * 2), false, RADIUS, RADIUS, false));
            rings.Add(new TubeRingDome(RING_Z1, false, DOMESEGMENTS));
            geometry.Geometry = UtilityWPF.GetMultiRingedTube(CYLINDERSEGMENTS, rings, true, true);

            geometries.Children.Add(geometry);

            #endregion

            #region Rings

            // Material
            material = new MaterialGroup();
            //material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("736E56"))));
            //material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("B0EEF2CE")), .8d));
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("CCBF81"))));
            material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("B0D9D78D")), 8));// .8d));

            // Ring 1
            // Geometry Model
            geometry              = new GeometryModel3D();
            geometry.Material     = material;
            geometry.BackMaterial = material;
            geometry.Geometry     = UtilityWPF.GetRing(RINGSEGMENTS, RINGRADIUS_INNER, RINGRADIUS_OUTER, RINGHEIGHT, new TranslateTransform3D(0, 0, -RING_Z2), false);

            geometries.Children.Add(geometry);

            // Ring 2
            // Geometry Model
            geometry              = new GeometryModel3D();
            geometry.Material     = material;
            geometry.BackMaterial = material;
            geometry.Geometry     = UtilityWPF.GetRing(RINGSEGMENTS, RINGRADIUS_INNER, RINGRADIUS_OUTER, RINGHEIGHT, new TranslateTransform3D(0, 0, RING_Z2), false);

            geometries.Children.Add(geometry);

            // Ring 3
            // Geometry Model
            geometry              = new GeometryModel3D();
            geometry.Material     = material;
            geometry.BackMaterial = material;
            geometry.Geometry     = UtilityWPF.GetRing(RINGSEGMENTS, RINGRADIUS_INNER, RINGRADIUS_OUTER, RINGHEIGHT);

            geometries.Children.Add(geometry);

            #endregion

            geometries.Transform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), 90));     // make this go along x instead of z

            this.Model = geometries;

            // Model Visual
            ModelVisual3D visual = new ModelVisual3D();        // this is the expensive one, so as few of these should be made as possible
            visual.Content = this.Model;

            #endregion

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            //transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 0, 1), 90)));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            using (CollisionHull hull = CollisionHull.CreateCylinder(world, 0, RADIUS, HEIGHT, null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { visual });
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping   = 1d;
                this.PhysicsBody.AngularDamping  = new Vector3D(.01d, .01d, .01d);

                //this.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
            }

            #endregion

            _sensorVisionPoints = GetSensorVisionPoints_Model(RADIUS, HEIGHT);

            this.Radius = Math.Sqrt((RADIUS * RADIUS) + ((HEIGHT / 2d) * (HEIGHT / 2d)));

            this.ReceiveDamageMultipliers = damageMultipliers ?? new DamageProps();

            this.HitPoints = new Container()
            {
                QuantityMax = hitPoints, QuantityCurrent = hitPoints
            };

            this.ContainedTreasureDNA = containedTreasureDNA;

            this.CreationTime = DateTime.UtcNow;
        }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
0
        private Body GetJointBodyPairSprtBody(CollisionShapeType bodyType, Point3D centerPoint, RotateTransform3D rotation, Color color)
        {
            #region WPF Model (plus collision hull)

            // Material
            MaterialGroup materials = new MaterialGroup();
            materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(color)));
            materials.Children.Add(new SpecularMaterial(Brushes.White, 100d));

            // Geometry Model
            GeometryModel3D geometry = new GeometryModel3D();
            geometry.Material     = materials;
            geometry.BackMaterial = materials;

            CollisionHull hull = null;
            switch (bodyType)
            {
            case CollisionShapeType.Box:
                geometry.Geometry = UtilityWPF.GetCube_IndependentFaces(new Point3D(-1, -1, -1d), new Point3D(1d, 1d, 1d));
                hull = CollisionHull.CreateBox(_world, 0, new Vector3D(2d, 2d, 2d), null);
                break;

            case CollisionShapeType.Sphere:
                geometry.Geometry = UtilityWPF.GetSphere_LatLon(5, 1d, 1d, 1d);
                hull = CollisionHull.CreateSphere(_world, 0, new Vector3D(1d, 1d, 1d), null);
                break;

            case CollisionShapeType.Cylinder:
                geometry.Geometry = UtilityWPF.GetCylinder_AlongX(20, 1d, 2d);
                hull = CollisionHull.CreateCylinder(_world, 0, 1d, 2d, null);
                break;

            case CollisionShapeType.Cone:
                geometry.Geometry = UtilityWPF.GetCone_AlongX(20, 1d, 2d);
                hull = CollisionHull.CreateCone(_world, 0, 1d, 2d, null);
                break;

            case CollisionShapeType.Capsule:
            case CollisionShapeType.ChamferCylinder:
                throw new ApplicationException("finish this");

            default:
                throw new ApplicationException("Unknown ConvexBody3D.CollisionShape: " + bodyType.ToString());
            }

            // Transform
            Transform3DGroup transform = new Transform3DGroup();                // rotate needs to be added before translate
            transform.Children.Add(rotation);
            transform.Children.Add(new TranslateTransform3D(centerPoint.ToVector()));

            // Model Visual
            ModelVisual3D model = new ModelVisual3D();
            model.Content   = geometry;
            model.Transform = transform;

            // Add to the viewport
            _viewport.Children.Add(model);

            #endregion

            #region Physics Body

            // Make a physics body that represents this shape
            Body body = new Body(hull, transform.Value, 1d, new Visual3D[] { model });          // being lazy with mass, but since size is fixed, it won't be too noticable
            hull.Dispose();
            body.Velocity = Math3D.GetRandomVector_Circular(1d);

            //body.LinearDamping = .01f;
            //body.AngularDamping = new Vector3D(.01f, .01f, .01f);

            body.ApplyForceAndTorque += new EventHandler <BodyApplyForceAndTorqueArgs>(Body_ApplyForceAndTorque);

            // This will be done later
            //_bodySets.Add(body);

            #endregion

            // Exit Function
            return(body);
        }
Ejemplo n.º 26
0
        private void SetCurrentVisual(Visual3D visual)
        {
            if (_currentVisuals != null)
            {
                _viewport.Children.RemoveAll(_currentVisuals);
                _currentVisuals = null;
            }

            List <Visual3D> visuals = new List <Visual3D>();

            if (chkShowNormals.IsChecked.Value)
            {
                #region Show normals

                ModelVisual3D visualCast = visual as ModelVisual3D;
                if (visualCast != null)
                {
                    GeometryModel3D modelCast = visualCast.Content as GeometryModel3D;
                    if (modelCast != null)
                    {
                        MeshGeometry3D geometryCast = modelCast.Geometry as MeshGeometry3D;
                        if (geometryCast != null)
                        {
                            // Mesh point normals
                            if (geometryCast.Positions.Count == geometryCast.Normals.Count)
                            {
                                ScreenSpaceLines3D lines = new ScreenSpaceLines3D();
                                lines.Color     = Colors.HotPink;
                                lines.Thickness = 1d;

                                for (int cntr = 0; cntr < geometryCast.Positions.Count; cntr++)
                                {
                                    lines.AddLine(geometryCast.Positions[cntr], geometryCast.Positions[cntr] + geometryCast.Normals[cntr]);
                                }

                                visuals.Add(lines);
                            }

                            // Triangle normals
                            bool hadTriangle = false;

                            ScreenSpaceLines3D lines2 = new ScreenSpaceLines3D();
                            lines2.Color     = Colors.Gold;
                            lines2.Thickness = 1d;

                            foreach (ITriangle triangle in UtilityWPF.GetTrianglesFromMesh(geometryCast))
                            {
                                hadTriangle = true;
                                lines2.AddLine(triangle.GetCenterPoint(), triangle.GetCenterPoint() + triangle.NormalUnit);
                            }

                            if (hadTriangle)
                            {
                                visuals.Add(lines2);
                            }
                        }
                    }
                }

                #endregion
            }

            visuals.Add(visual);

            _currentVisuals = visuals.ToArray();
            _viewport.Children.AddRange(_currentVisuals);
        }
Ejemplo n.º 27
0
        private void addSimple1_AddBody(object sender, AddBodyArgs e)
        {
            try
            {
                #region WPF Model (plus collision hull)

                // Material
                MaterialGroup materials = new MaterialGroup();
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.GetRandomColor(64, 192))));
                materials.Children.Add(new SpecularMaterial(Brushes.White, 100d));

                // Geometry Model
                GeometryModel3D geometry = new GeometryModel3D();
                geometry.Material     = materials;
                geometry.BackMaterial = materials;

                CollisionHull hull = null;
                switch (e.CollisionShape)
                {
                case CollisionShapeType.Box:
                    Vector3D halfSize = e.Size / 2d;
                    geometry.Geometry = UtilityWPF.GetCube_IndependentFaces(new Point3D(-halfSize.X, -halfSize.Y, -halfSize.Z), new Point3D(halfSize.X, halfSize.Y, halfSize.Z));
                    hull = CollisionHull.CreateBox(_world, 0, e.Size, null);
                    break;

                case CollisionShapeType.Sphere:
                    geometry.Geometry = UtilityWPF.GetSphere_LatLon(5, e.Size.X, e.Size.Y, e.Size.Z);
                    hull = CollisionHull.CreateSphere(_world, 0, e.Size, null);
                    break;

                case CollisionShapeType.Cylinder:
                    geometry.Geometry = UtilityWPF.GetCylinder_AlongX(20, e.Radius, e.Height);
                    hull = CollisionHull.CreateCylinder(_world, 0, e.Radius, e.Height, null);
                    break;

                case CollisionShapeType.Cone:
                    geometry.Geometry = UtilityWPF.GetCone_AlongX(20, e.Radius, e.Height);
                    hull = CollisionHull.CreateCone(_world, 0, e.Radius, e.Height, null);
                    break;

                case CollisionShapeType.Capsule:
                case CollisionShapeType.ChamferCylinder:
                    MessageBox.Show("finish this");
                    return;

                default:
                    throw new ApplicationException("Unknown ConvexBody3D.CollisionShape: " + e.CollisionShape.ToString());
                }

                // Transform
                Transform3DGroup transform = new Transform3DGroup();            // rotate needs to be added before translate
                transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(Math3D.GetRandomVector_Spherical(10), Math1D.GetNearZeroValue(360d))));
                transform.Children.Add(new TranslateTransform3D(Math3D.GetRandomVector_Spherical(CREATEOBJECTBOUNDRY)));

                // Model Visual
                ModelVisual3D model = new ModelVisual3D();
                model.Content   = geometry;
                model.Transform = transform;

                // Add to the viewport
                _viewport.Children.Add(model);

                #endregion

                #region Physics Body

                // Make a physics body that represents this shape
                Body body = new Body(hull, transform.Value, e.Mass, new Visual3D[] { model });
                hull.Dispose();
                body.Velocity = Math3D.GetRandomVector_Circular(1d);

                //body.LinearDamping = .01f;
                //body.AngularDamping = new Vector3D(.01f, .01f, .01f);

                body.ApplyForceAndTorque += new EventHandler <BodyApplyForceAndTorqueArgs>(Body_ApplyForceAndTorque);

                Body[] bodySet = new Body[] { body };
                _bodySets.Add(bodySet);

                #endregion

                BodiesAdded(bodySet);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 28
0
        private void setup3D()
        {
            PerspectiveCamera camera = new PerspectiveCamera(
                new Point3D(0, 0, 3.73), //position
                new Vector3D(0, 0, -1),  //lookDirection
                new Vector3D(0, 1, 0),   //upDirection
                30                       //FOV
                );

            WrappedElement.Camera = camera;

            Model3DGroup everything = new Model3DGroup();

            Model3DGroup     lights     = new Model3DGroup();
            DirectionalLight whiteLight = new DirectionalLight(Colors.White, new Vector3D(0, 0, -1));

            lights.Children.Add(whiteLight);

            everything.Children.Add(lights);

            ModelVisual3D model = new ModelVisual3D();

            double tileSizeX = 2.0 / c_xCount;
            double startX    = -((double)c_xCount) / 2 * tileSizeX + tileSizeX / 2;
            double startY    = -((double)c_yCount) / 2 * tileSizeX + tileSizeX / 2;

            int index;

            Size tileTextureSize = new Size(1.0 / c_xCount, 1.0 / c_yCount);

            //so, tiles are numbers, left-to-right (ascending x), bottom-to-top (ascending y)
            for (int y = 0; y < c_yCount; y++)
            {
                for (int x = 0; x < c_xCount; x++)
                {
                    index = y * c_xCount + x;

                    Rect backTextureCoordinates = new Rect(
                        x * tileTextureSize.Width,

                        // this will give you a headache. Exists since we are going
                        // from bottom bottomLeft of 3D space (negative Y is down),
                        // but texture coor are negative Y is up
                        1 - y * tileTextureSize.Height - tileTextureSize.Height,

                        tileTextureSize.Width, tileTextureSize.Height);

                    m_tiles[index] = new FlipTile(
                        getMaterial(index),
                        new Size(tileSizeX, tileSizeX),
                        new Point(startX + x * tileSizeX, startY + y * tileSizeX),
                        m_backMaterial,
                        backTextureCoordinates);

                    m_tiles[index].Click += (sender, args) => tileClicked((FlipTile)sender);

                    WrappedElement.Children.Add(m_tiles[index]);
                }
            }

            model.Content = everything;

            WrappedElement.Children.Add(model);

            //start the per-frame tick for the physics
            m_listener.StartListening();
        }
Ejemplo n.º 29
0
        public ProjectDocument(LayoutDocumentPane layPane, ModellingTreeNodeProject projectNode)
        {
            layDoc       = new LayoutDocument();
            layDoc.Title = projectNode.Name;
            layPane.Children.Add(layDoc);
            this.projectNode = projectNode;

            layDoc.CanClose         = false;
            layDoc.CanFloat         = false;
            layDoc.IsActiveChanged += ActiveDocChanged;

            viewPort = new Viewport3D();
            grid     = new Grid();
            grid.Children.Add(viewPort);
            layDoc.Content = grid;

            SolidColorBrush b = new SolidColorBrush(Colors.DarkSeaGreen);

            grid.Background = b;

            OrthographicCamera camera = new OrthographicCamera();

            camera.Position      = new Point3D(0.0f, 0.0f, 100f);
            camera.LookDirection = new Vector3D(0.0f, 0.0f, -1.0f);
            camera.UpDirection   = new Vector3D(0.0f, 1.0f, 0.0f);
            camera.Width         = 300;
            viewPort.Camera      = camera;

            DirectionalLight light       = new DirectionalLight(Colors.White, new Vector3D(-1.0f, -1.0f, -1.0f));
            ModelVisual3D    modelvisual = new ModelVisual3D();

            modelvisual.Content = light;
            viewPort.Children.Add(modelvisual);

            projectNode.DrawableObjectCreated += OnDrawableObjectCreated;
            projectNode.DrawableObjectRemoved += OnDrawableObjectRemoved;

            //ModelVisual3D mv = new ModelVisual3D();
            //Model3DGroup mg = new Model3DGroup();
            //mv.Content = mg;
            //viewPort.Children.Add(mv);

            //TubeIncline tube = new TubeIncline();

            //tube.StartVector = new LinearMath.Vector(3);
            //tube.EndVector = new LinearMath.Vector(3);

            //tube.StartNormal = new LinearMath.Vector(3);
            //tube.EndNormal = new LinearMath.Vector(3);

            //tube.StartVector[0] = -100.0;
            //tube.StartVector[1] = 0.0;

            //tube.EndVector[0] = 100.0;
            //tube.EndVector[1] = 0.0;

            //LinearMath.Vector v = new LinearMath.Vector(3);
            //v[0] = 1.0;
            //v[1] = 1.0;
            //v.normalize();

            //tube.StartNormal[0] = 1.0;
            //tube.StartNormal[1] = 0.0;

            //tube.EndNormal[0] = v[0];
            //tube.EndNormal[1] = v[1];

            //tube.r = 20;
            //tube.color = Colors.Blue;
            //mg.Children.Add(tube.model);

            grid.MouseWheel += OnMouseWheel;
            grid.MouseDown  += OnMouseDown;
            grid.MouseMove  += OnMouseMove;
            grid.MouseUp    += OnMouseUp;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Shows the sample of surface.
        /// </summary>
        /// <param name="model3D">A WebMech.Web.Model3DData that specifies
        /// data object of 3D model with basic statistic data and list of 3D points.</param>
        public void ShowSample(Model3DData model3D)
        {
            Clear();
            ClearCamera();

            Model3DGroup surface = new Model3DGroup();
            Point3D[] points = GetSurfacePoints(model3D);
            for (int y = 0; y < (surfaceSize * (surfaceSize - 1)); y += surfaceSize)
            {
                for (int x = 0; x < (surfaceSize - 1); x++)
                {
                    surface.Children.Add(
                        CreateTriangleModel(
                                points[x + y + surfaceSize],
                                points[x + y],
                                points[x + y + 1])
                    );
                    surface.Children.Add(
                        CreateTriangleModel(
                                points[x + y + surfaceSize],
                                points[x + y + 1],
                                points[x + y + surfaceSize + 1])
                    );
                }
            }
            ModelVisual3D model = new ModelVisual3D();
            model.Content = surface;
            mainViewport.Children.Add(model);
        }
Ejemplo n.º 31
0
        private void DrawTrajectory(int t_id, Color color, string direction, ModelVisual3D model)
        {
            //find trajectory id of last inserted trajectory

            if (tds.trajectories.Count == 0)
            {
                return;
            }

            //int t_id = Globals.ds.trajectories[Globals.ds.trajectories.Count - 1].t_id;

            TrajectoryDbDataSet.pointsRow[] pointsRows = (TrajectoryDbDataSet.pointsRow[])tds.points.Select("t_id = " + t_id);

            if (pointsRows.Count() < 30 && pointsRows.Count() > 2)
            {
                Point3D firstPoint = new Point3D((float)pointsRows[0].X, (float)pointsRows[0].Y, (float)pointsRows[0].Z);

                Point3DCollection pointCollection = new Point3DCollection();

                for (int i = 1; i < pointsRows.Length; i++)
                {
                    TrajectoryDbDataSet.pointsRow currentRow;
                    TrajectoryDbDataSet.pointsRow lastRow;

                    try
                    {
                        currentRow = pointsRows[i];
                        lastRow    = pointsRows[i - 1];
                    }
                    catch (Exception e)
                    {
                        return;
                    }

                    pointCollection.Add(new Point3D(currentRow.X, currentRow.Y, currentRow.Z));
                }


                if (direction.Equals("R"))
                {
                    arrow = Petzold.Media2D.ArrowEnds.End;
                }
                else if (direction.Equals("L"))
                {
                    arrow = Petzold.Media2D.ArrowEnds.Start;
                }
                else
                {
                    arrow = Petzold.Media2D.ArrowEnds.None;
                }

                WirePolyline wl = new WirePolyline()
                {
                    Points    = pointCollection,
                    Thickness = 1,
                    Rounding  = 1,
                    Color     = color,
                    ArrowEnds = Petzold.Media2D.ArrowEnds.End
                };

                model.Children.Add(wl);
                model.Transform = new Transform3DGroup();
            }
        }