コード例 #1
0
ファイル: FlipTile.cs プロジェクト: hungdluit/bot
        public FlipTile(DiffuseMaterial frontMaterial,
            Size size, Point center, Material backMaterial, Rect backTextureCoordinates)
        {
            m_locationDesired = new Point3D(center.X, center.Y, 0);
            m_locationCurrent = new Point3D(0, 0, Util.Rnd.NextDouble() * 10 - 20);
            m_size = size;

            Point3D topLeft = new Point3D(-size.Width / 2, size.Height / 2, 0);
            Point3D topRight = new Point3D(size.Width / 2, size.Height / 2, 0);
            Point3D bottomLeft = new Point3D(-size.Width / 2, -size.Height / 2, 0);
            Point3D bottomRight = new Point3D(size.Width / 2, -size.Height / 2, 0);

            m_frontMaterial = frontMaterial;

            Model3DGroup quad = new Model3DGroup();
            quad.Children.Add(
                CreateTile(
                    frontMaterial,
                    backMaterial,
                    m_borderMaterial,
                    new Size3D(size.Width, size.Height, .01),
                    backTextureCoordinates));

            Transform3DGroup group = new Transform3DGroup();

            group.Children.Add(new RotateTransform3D(m_verticalFlipRotation));
            group.Children.Add(new RotateTransform3D(m_quaternionRotation3D));

            group.Children.Add(m_scaleTransform);
            group.Children.Add(m_translate);

            quad.Transform = group;

            this.Visual3DModel = quad;
        }
コード例 #2
0
ファイル: TileData.cs プロジェクト: liuxr/wpfumprototype
        public void Setup3DItem(Model3DGroup targetGroup, DiffuseMaterial diffuseMaterialBrushPair,
            Size size, Point center, Material backMaterial, Rect backTextureCoordinates)
        {
            _locationDesired = new Point3D(center.X, center.Y, 0);
            _locationCurrent = new Point3D(0, 0, Rnd.NextDouble() * 10 - 20);
            _size = size;

            Point3D topLeft = new Point3D(-size.Width / 2, size.Height / 2, 0);
            Point3D topRight = new Point3D(size.Width / 2, size.Height / 2, 0);
            Point3D bottomLeft = new Point3D(-size.Width / 2, -size.Height / 2, 0);
            Point3D bottomRight = new Point3D(size.Width / 2, -size.Height / 2, 0);

            DiffuseMaterial = diffuseMaterialBrushPair;

            _quad.Children.Add(
                CreateTile(
                    diffuseMaterialBrushPair,
                    backMaterial,
                    _borderMaterial,
                    new Size3D(size.Width, size.Height, .01),
                    backTextureCoordinates));

            Transform3DGroup group = new Transform3DGroup();

            group.Children.Add(new RotateTransform3D(_verticalFlipRotation));
            group.Children.Add(new RotateTransform3D(this._quaternionRotation3D));

            group.Children.Add(_scaleTransform);
            group.Children.Add(_translate);

            _quad.Transform = group;

            targetGroup.Children.Add(_quad);
        }
コード例 #3
0
ファイル: CubeBuilder.cs プロジェクト: dingxinbei/OLdBck
        static CubeBuilder()
        {
            quadMesh = new MeshGeometry3D();
            quadMesh.Positions.Add(new Point3D(-0.5, 0.5, 0));
            quadMesh.Positions.Add(new Point3D(-0.5, -0.5, 0));
            quadMesh.Positions.Add(new Point3D(0.5, -0.5, 0));
            quadMesh.Positions.Add(new Point3D(0.5, 0.5, 0));

            quadMesh.TextureCoordinates.Add(new Point(0, 0));
            quadMesh.TextureCoordinates.Add(new Point(0, 1));
            quadMesh.TextureCoordinates.Add(new Point(1, 1));
            quadMesh.TextureCoordinates.Add(new Point(1, 0));

            quadMesh.Normals.Add(new Vector3D(0, 0, 1));
            quadMesh.Normals.Add(new Vector3D(0, 0, 1));
            quadMesh.Normals.Add(new Vector3D(0, 0, 1));
            quadMesh.Normals.Add(new Vector3D(0, 0, 1));

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

            visualHostMaterial = new DiffuseMaterial(
                new SolidColorBrush(Colors.White));
            visualHostMaterial.SetValue(
                Viewport2DVisual3D.IsVisualHostMaterialProperty, true);
        }
コード例 #4
0
ファイル: Predator.cs プロジェクト: XiBeichuan/hydronumerics
        static Predator()
        {
            var egg = new MeshBuilder();
            egg.AddPyramid(new Point3D(0, 0, 0), 0.2, 0.4);
            eggGeometry = egg.ToMesh();

            var child = new MeshBuilder();
            child.AddBox(new Point3D(0, 0, 0.5), 1, 1, 1);
            child.AddSphere(new Point3D(0.2, 0.2, 1), 0.2, 12, 24);
            child.AddSphere(new Point3D(0.2, -0.2, 1), 0.2, 12, 24);
            childGeometry = child.ToMesh();

            var creature = new MeshBuilder();
            creature.AddBox(new Point3D(0, 0, 0.5), 1, 1, 1);
            creature.AddCone(new Point3D(0.2, 0.2, 1), new Vector3D(0, 0, 1), 0.16, 0.04, 0.3, false, true, 12);
            creature.AddCone(new Point3D(0.2, -0.2, 1), new Vector3D(0, 0, 1), 0.16, 0.04, 0.3, false, true, 12);
            creatureGeometry = creature.ToMesh();

            var coffin = new MeshBuilder();
            coffin.AddCylinder(new Point3D(0, 0, 0), new Point3D(0, 0, 0.25), 1, 12);
            deadGeometry = coffin.ToMesh();

            maleMaterial = MaterialHelper.CreateMaterial(Brushes.Navy);
            femaleMaterial = MaterialHelper.CreateMaterial(Brushes.Violet);
            eggMaterial = MaterialHelper.CreateMaterial(Brushes.AntiqueWhite);
            deadMaterial = MaterialHelper.CreateMaterial(Brushes.Black);

        }
コード例 #5
0
ファイル: Creature.cs プロジェクト: XiBeichuan/hydronumerics
        static Creature()
        {
            var egg = new MeshBuilder();
            egg.AddSphere(new Point3D(0, 0, 0.2), 0.2, 24, 12);
            eggGeometry = egg.ToMesh();

            var child = new MeshBuilder();
            child.AddSphere(new Point3D(0, 0, 1), 1, 24, 12);
            child.AddSphere(new Point3D(1, 0, 1), 0.5, 24, 12);
            child.AddSphere(new Point3D(1.5, 0.2, 1), 0.1, 24, 12);
            child.AddSphere(new Point3D(1.5, -0.2, 1), 0.1, 24, 12);
            childGeometry = child.ToMesh();

            var creature = new MeshBuilder();
            creature.AddSphere(new Point3D(0, 0, 1), 1, 24, 12);
            creature.AddSphere(new Point3D(0, 0, 2), 0.5, 24, 12);
            creature.AddSphere(new Point3D(0.5, 0.2, 2), 0.1, 24, 12);
            creature.AddSphere(new Point3D(0.5, -0.2, 2), 0.1, 24, 12);
            creatureGeometry = creature.ToMesh();

            var coffin = new MeshBuilder();
            coffin.AddBox(new Point3D(0, 0, 0.25), 1, 1, 1);
            deadGeometry = coffin.ToMesh();

            maleMaterial = MaterialHelper.CreateMaterial(Brushes.Blue);
            femaleMaterial = MaterialHelper.CreateMaterial(Brushes.IndianRed);
            eggMaterial = MaterialHelper.CreateMaterial(Brushes.AntiqueWhite);
            deadMaterial = MaterialHelper.CreateMaterial(Brushes.Black);

        }
コード例 #6
0
 private static void LoadMaterial(SystemMaterial[] materials, Scene scene, string path)
 {
     for (int i = 0; i < scene.MaterialCount; ++i)
     {
         materials[i] = ConvertMaterial(scene.Materials[i], path);
     }
 }
コード例 #7
0
        public static GeometryModel3D CreateNormalizedCube(Material material)
        {
            MeshGeometry3D geometry = new MeshGeometry3D();

            var farPoint = new Point3D(-0.5, -0.5, -0.5);
            var nearPoint = new Point3D(0.5, 0.5, 0.5);

            var cube = new Model3DGroup();
            var p0 = new Point3D(farPoint.X, farPoint.Y, farPoint.Z);
            var p1 = new Point3D(nearPoint.X, farPoint.Y, farPoint.Z);
            var p2 = new Point3D(nearPoint.X, farPoint.Y, nearPoint.Z);
            var p3 = new Point3D(farPoint.X, farPoint.Y, nearPoint.Z);
            var p4 = new Point3D(farPoint.X, nearPoint.Y, farPoint.Z);
            var p5 = new Point3D(nearPoint.X, nearPoint.Y, farPoint.Z);
            var p6 = new Point3D(nearPoint.X, nearPoint.Y, nearPoint.Z);
            var p7 = new Point3D(farPoint.X, nearPoint.Y, nearPoint.Z);
            int startIndex = 0;
            startIndex = AddTriangleFace(geometry, p3, p2, p6, startIndex);
            startIndex = AddTriangleFace(geometry, p3, p6, p7, startIndex);
            startIndex = AddTriangleFace(geometry, p2, p1, p5, startIndex);
            startIndex = AddTriangleFace(geometry, p2, p5, p6, startIndex);
            startIndex = AddTriangleFace(geometry, p1, p0, p4, startIndex);
            startIndex = AddTriangleFace(geometry, p1, p4, p5, startIndex);
            startIndex = AddTriangleFace(geometry, p0, p3, p7, startIndex);
            startIndex = AddTriangleFace(geometry, p0, p7, p4, startIndex);
            startIndex = AddTriangleFace(geometry, p7, p6, p5, startIndex);
            startIndex = AddTriangleFace(geometry, p7, p5, p4, startIndex);
            startIndex = AddTriangleFace(geometry, p2, p3, p0, startIndex);
            startIndex = AddTriangleFace(geometry, p2, p0, p1, startIndex);

            return new GeometryModel3D(geometry, material);
        }
コード例 #8
0
        public FrustumCullingSample()
        {
            InitializeComponent();

            _fullyVisibleMaterial = new DiffuseMaterial(Brushes.Green);
            _fullyVisibleMaterial.Freeze(); // Freezing material will speed up initialization of objects

            _partiallyVisibleMaterial = new DiffuseMaterial(Brushes.Orange);
            _partiallyVisibleMaterial.Freeze();

            _hiddenMaterial = new DiffuseMaterial(Brushes.Red);
            _hiddenMaterial.Freeze();


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


            this.Camera1.CameraChanged += delegate(object sender, CameraChangedRoutedEventArgs args)
            {
                UpdateVisibleBoxes();
            };

            this.SizeChanged += delegate(object sender, SizeChangedEventArgs args)
            {
                UpdateVisibleBoxes();
            };


            CreateSceneObjects();
        }
コード例 #9
0
 private void LoadMeshes(GeometryModel3D[] meshes, Scene scene, SystemMaterial[] materials)
 {
      for (int i = 0; i < scene.MeshCount; ++i)
     {
         meshes[i] = this.ConvertMesh(scene.Meshes[i], materials);
     }
 }
コード例 #10
0
        private Model3D Display3d(string model)
        {
            Model3D device = null;

            try
            {
                //Adding a gesture here
                viewPort3d.RotateGesture = new MouseGesture(MouseAction.RightClick);

                //Import 3D model file
                ModelImporter import = new ModelImporter();
                System.Windows.Media.Media3D.Material mat = MaterialHelper.CreateMaterial(
                    new SolidColorBrush(Color.FromRgb(255, 255, 255)));
                import.DefaultMaterial = mat;
                //Load the 3D model file
                device = import.Load(model);

                ////Stream stream = new MemoryStream(Properties.Resources.Mouse_Maze);
                //Stream stream = new FileStream(model, FileMode.Open);
                //var reader = new HelixToolkit.Wpf.StLReader();
                //reader.DefaultMaterial = mat;
                //Model3DGroup MazeModel = reader.Read(stream);
                ////Properties.Resources.
            }
            catch (Exception e)
            {
                // Handle exception in case can not file 3D model
                MessageBox.Show("Exception Error : " + e.StackTrace);
            }
            return(device);
        }
コード例 #11
0
ファイル: Helpers.cs プロジェクト: paulbarbu/magic-cube
        public static MyModelVisual3D createRectangleModel(Point3D[] p, Material m, string tag, bool up=true)
        {
            MyModelVisual3D rect = new MyModelVisual3D();

            rect.Children.Add(createRectangleModel(p, m, tag, up));

            return rect;
        }
コード例 #12
0
ファイル: CubePrimitive.cs プロジェクト: OurDemoGroup/Samples
        /// <summary>
        /// Constructs a new cube primitive, with the specified size.
        /// </summary>
        public CubePrimitive(Material material, float size)
        {
            // A cube has six faces, each one pointing in a different direction.
            Vector3D[] normals =
            {
                new Vector3D(0, 0, 1),
                new Vector3D(0, 0, -1),
                new Vector3D(1, 0, 0),
                new Vector3D(-1, 0, 0),
                new Vector3D(0, 1, 0),
                new Vector3D(0, -1, 0),
            };

            // Create each face in turn.
            foreach (Vector3D normal in normals)
            {
                // Get two vectors perpendicular to the face normal and to each other.
                Vector3D side1 = new Vector3D(normal.Y, normal.Z, normal.X);
                Vector3D side2 = Vector3D.CrossProduct(normal, side1);

                // Six indices (two triangles) per face.
                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 1);
                AddIndex(CurrentVertex + 2);

                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 2);
                AddIndex(CurrentVertex + 3);

                // Four vertices per face.
                Vector3D vertex = (normal - side1 - side2) * size / 2;
                Point3D vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                AddVertex(vertexPoint, normal);
                AddTextureCoordinates(new System.Windows.Point(0,0));

                vertex = (normal - side1 + side2) * size / 2;
                vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                AddVertex(vertexPoint, normal);
                AddTextureCoordinates(new System.Windows.Point(0, 1));

                vertex = (normal + side1 + side2) * size / 2;
                vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                AddVertex(vertexPoint, normal);
                AddTextureCoordinates(new System.Windows.Point(1, 0));

                vertex = (normal + side1 - side2) * size / 2;
                vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                AddVertex(vertexPoint, normal);
                AddTextureCoordinates(new System.Windows.Point(1, 1));
            }

            InitializePrimitive(material);
        }
コード例 #13
0
 public void InitMove(Ray3D ray)
 {
     Vector3D t = Vector3D.CrossProduct(ray.Direction, Direction);
     Vector3D n = Vector3D.CrossProduct(Direction, t);
     var intersection=ray.PlaneIntersection(Origin, n);
     if (!intersection.HasValue)
         return;
     _mouseDownPoint = intersection.Value;
     _lastMousePoint = _mouseDownPoint;
     originalMaterial = Material;
     Fill = Brushes.Yellow;
     isMoving = true;
 }
コード例 #14
0
        private void EnsureLeftControllerMesh()
        {
            // Controller mash is get from: ovr_sdk_win_1.17.0_public\OculusSDK\Samples\OculusWorldDemo\Assets\Tuscany\LeftController.xml
            // This model is also used to render the right controller. It is only flipped on x axis (see OculusWorldDemoApp::RenderControllers)
            _leftControllerMesh = (MeshGeometry3D)this.FindResource("LeftTouchController");

            if (_leftControllerMesh == null)
            {
                throw new Exception("Cannot find the LeftTouchController MeshGeometry3D - it is defined in the App.xaml");
            }

            // We also create the material here
            _controllerMaterial = new DiffuseMaterial(new SolidColorBrush(Color.FromRgb(20, 20, 20))); // Almost back Diffuse material
        }
コード例 #15
0
        // SURFACES, MESH

        public static Model3D RhinotoHelixMesh(Rhino.Geometry.Mesh mesh, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup = new Model3DGroup();

            var meshBuilder      = new MeshBuilder(false, false);
            var meshBuilderEdges = new MeshBuilder(false, false);

            // Triangulate to avoid planarity issues
            mesh.Faces.ConvertQuadsToTriangles();
            mesh.Faces.CullDegenerateFaces();
            Point3f[]      vertices = mesh.Vertices.ToPoint3fArray();
            List <Point3D> vs       = new List <Point3D>();
            //foreach (Point3d pt in vertices)
            //{
            //    vs.Add(RhinoToHelixPoint(pt));

            //}



            Point3f pt1 = new Point3f();
            Point3f pt2 = new Point3f();
            Point3f pt3 = new Point3f();
            Point3f pt4 = new Point3f();

            for (int i = 0; i < mesh.Faces.Count(); i++)
            {
                if (mesh.Faces.GetFaceVertices(i, out pt1, out pt2, out pt3, out pt4))
                {
                    Point3f pt1clone = new Point3f(pt1.X, pt1.Y, pt1.Z);
                    Point3f pt2clone = new Point3f(pt2.X, pt2.Y, pt2.Z);
                    Point3f pt3clone = new Point3f(pt3.X, pt3.Y, pt3.Z);
                    vs.Add(RhinoToHelixPoint(pt1clone));
                    vs.Add(RhinoToHelixPoint(pt2clone));
                    vs.Add(RhinoToHelixPoint(pt3clone));
                }
            }
            meshBuilder.AddTriangles(vs);
            var meshHelix      = meshBuilder.ToMesh(true);
            var meshHelixLines = meshBuilderEdges.ToMesh(true);

            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = meshHelix, Material = MaterialHelper.CreateMaterial(Colors.Gray), BackMaterial = MaterialHelper.CreateMaterial(Colors.Gray)
            });
            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = meshHelixLines, Material = mat, BackMaterial = mat
            });
            return(modelGroup);
        }
コード例 #16
0
        public static GeometryModel3D CreateNormalizedCylinder(Material material, int numSegments)
        {
            MeshGeometry3D geometry = new MeshGeometry3D();

            double radius = 0.5;
            double depth = 1;
            double minusDepthHalf = -depth / 2;
            var nearCircle = new CircleAssitor();
            var farCircle = new CircleAssitor();

            var twoPi = Math.PI * 2;
            var firstPass = true;

            double x;
            double y;

            double increment = twoPi / numSegments;
            int startIndex = 0;
            for (double i = 0; i < twoPi + increment; i = i + increment)
            {
                x = (radius * Math.Cos(i));
                y = (-radius * Math.Sin(i));

                farCircle.CurrentTriangle.P0 = new Point3D(0, 0, minusDepthHalf);
                farCircle.CurrentTriangle.P1 = farCircle.LastPoint;
                farCircle.CurrentTriangle.P2 = new Point3D(x, y, minusDepthHalf);

                nearCircle.CurrentTriangle = farCircle.CurrentTriangle.Clone(depth, true);

                if (!firstPass)
                {
                    startIndex = AddTriangleFace(geometry, farCircle.CurrentTriangle, startIndex);
                    startIndex = AddTriangleFace(geometry, nearCircle.CurrentTriangle, startIndex);

                    startIndex = AddTriangleFace(geometry, farCircle.CurrentTriangle.P2, farCircle.CurrentTriangle.P1, nearCircle.CurrentTriangle.P2, startIndex);
                    startIndex = AddTriangleFace(geometry, nearCircle.CurrentTriangle.P2, nearCircle.CurrentTriangle.P1, farCircle.CurrentTriangle.P2, startIndex);
                }
                else
                {
                    farCircle.FirstPoint = farCircle.CurrentTriangle.P1;
                    nearCircle.FirstPoint = nearCircle.CurrentTriangle.P1;
                    firstPass = false;
                }
                farCircle.LastPoint = farCircle.CurrentTriangle.P2;
                nearCircle.LastPoint = nearCircle.CurrentTriangle.P2;
            }

            return new GeometryModel3D(geometry, material);
        }
コード例 #17
0
        private void ManuallyRefreshMaterial(System.Windows.Media.Media3D.Material wpfMaterialToUpdate)
        {
            if (MainDXViewportView.DXScene == null) // Using WPF 3D rendering
            {
                return;
            }

            // GetUsedDXMaterial returns the DXEngine's material that is used to show the wpfMaterialToUpdate
            var usedDXMaterial = wpfMaterialToUpdate.GetUsedDXMaterial(MainDXViewportView.DXScene.DXDevice);

            if (usedDXMaterial != null)
            {
                usedDXMaterial.Refresh(); // Regenerate the textures from VisualBrush
            }
        }
コード例 #18
0
        private void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                SetDefaultClouds();
                return;
            }

            var image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = new MemoryStream(e.Result);
            image.EndInit();

            Clouds = MaterialHelper.CreateImageMaterial(image, 0.5);
        }
コード例 #19
0
ファイル: Cube.cs プロジェクト: paulbarbu/magic-cube
        /// <summary>
        /// Cube constructor
        /// </summary>
        /// <param name="o">The origin of the cube, this will always be the far-lower-left corner</param>
        /// <param name="len">The length of the edge</param>
        /// <param name="f">This parameter allows the use of different materials on the cube's faces</param>
        /// <param name="defaultMaterial">The material to be applied on the faces 
        /// that are not included in the previous parameter.
        /// This defaults to a solid black diffuse material
        /// </param>
        public Cube(Point3D o, double len, Dictionary<CubeFace, Material> f, HashSet<Move> possibleMoves, Material defaultMaterial=null)
        {
            this.origin = o;
            this.edge_len = len;
            this.faces = f;
            this.possibleMoves = possibleMoves;

            if(defaultMaterial != null){
                this.defaultMaterial = defaultMaterial;
            }

            this.Transform = this.rotations;

            createCube();
        }
コード例 #20
0
        private void ChangeMaterial(IEnumerable<Model3D> models, Material material)
        {
            if (models == null)
            {
                return;
            }

            foreach (var model in models)
            {
                var geometryModel = model as GeometryModel3D;
                if (geometryModel != null)
                {
                    geometryModel.Material = geometryModel.BackMaterial = material;
                }
            }
        }
コード例 #21
0
        /// <summary>
        /// 改变材质(颜色)
        /// </summary>
        /// <param name="models"></param>
        /// <param name="material"></param>
        private void ChangeMaterial(IEnumerable <Model3D> models, System.Windows.Media.Media3D.Material material)
        {
            if (models == null)
            {
                return;
            }

            foreach (var model in models)
            {
                var geometryModel = model as System.Windows.Media.Media3D.GeometryModel3D;
                if (geometryModel != null)
                {
                    geometryModel.Material = geometryModel.BackMaterial = material;
                }
            }
        }
コード例 #22
0
        internal void sample(Material material)
        {
            ///*
            GeometryModel3D bigCubeModel = GeometryGenerator.CreateBraceModel(1);
            bigCubeModel.Material = material;
            
            this.Content = bigCubeModel;

            //Transform3DGroup transformGroup = new Transform3DGroup();
            //transformGroup.Children.Add(scaleBrace());
            //transformGroup.Children.Add(locateBrace());            
            //this.Transform = transformGroup;

            scaleBrace();
            locateBrace();
        }
コード例 #23
0
        private static Model3DGroup GetModel_IronSteel(WeaponSpikeBallDNA dna, WeaponSpikeBallDNA finalDNA, WeaponMaterialCache materials)
        {
            Model3DGroup retVal = new Model3DGroup();
            var          from   = dna.KeyValues;
            var          to     = finalDNA.KeyValues;

            double spikeLength = WeaponDNA.GetKeyValue("spikeLen", from, to, dna.Radius * StaticRandom.NextDouble(1.3d, 1.8d));
            double ballRadius  = spikeLength * .6d;

            #region Spikes

            System.Windows.Media.Media3D.Material material = materials.Spike_Steel;     // the property get returns a slightly random color

            GeometryModel3D geometry = new GeometryModel3D();

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

            double[]          radii     = new double[] { spikeLength, ballRadius *WeaponDNA.GetKeyValue("spikeRadMult", from, to, StaticRandom.NextDouble(.7, .87)) };
            TriangleIndexed[] triangles = UtilityWPF.GetIcosahedron(radii);

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(triangles);

            retVal.Children.Add(geometry);

            #endregion

            #region Ball

            material = materials.Ball_Iron;     // the property get returns a slightly random color

            geometry = new GeometryModel3D();

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

            triangles = UtilityWPF.GetIcosahedron(ballRadius, 1);

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(triangles);

            retVal.Children.Add(geometry);

            #endregion

            return(retVal);
        }
コード例 #24
0
ファイル: Helpers.cs プロジェクト: paulbarbu/magic-cube
        public static Model3DGroup createRectangleModel(Point3D[] p, Material m, bool up=true)
        {
            if (p.Length != 4) {
                return null;
            }

            Model3DGroup rect = new Model3DGroup();

            if (up) {
                rect.Children.Add(createTriangleModel(p[0], p[1], p[2], m));
                rect.Children.Add(createTriangleModel(p[0], p[2], p[3], m));
            }
            else {
                rect.Children.Add(createTriangleModel(p[0], p[2], p[1], m));
                rect.Children.Add(createTriangleModel(p[0], p[3], p[2], m));
            }

            return rect;
        }
コード例 #25
0
 private void ExportMaterial(string matName, Material material, Material backMaterial)
 {
     mwriter.WriteLine(String.Format("newmtl {0}", matName));
     var dm = material as DiffuseMaterial;
     var sm = material as SpecularMaterial;
     var mg = material as MaterialGroup;
     if (mg != null)
     {
         foreach (var m in mg.Children)
         {
             if (m is DiffuseMaterial)
                 dm = m as DiffuseMaterial;
             if (m is SpecularMaterial)
                 sm = m as SpecularMaterial;
         }
     }
     if (dm != null)
     {
         mwriter.WriteLine(String.Format("Ka {0}", ToColorString(dm.AmbientColor)));
         var scb = dm.Brush as SolidColorBrush;
         if (scb != null)
         {
             mwriter.WriteLine(String.Format("Kd {0}", ToColorString(scb.Color)));
             mwriter.WriteLine(String.Format(CultureInfo.InvariantCulture, "d {0:F4}", scb.Color.A / 255.0));
         }
         else
         {
             var textureFilename = matName + ".png";
             var texturePath = Path.Combine(directory, textureFilename);
             // create .png bitmap file for the brush
             RenderBrush(texturePath, dm.Brush, 1024, 1024);
             mwriter.WriteLine(String.Format("map_Ka {0}", textureFilename));
         }
     }
     if (sm != null)
     {
         var scb = sm.Brush as SolidColorBrush;
         if (scb != null)
             mwriter.WriteLine(String.Format("Ks {0}", ToColorString(scb.Color)));
         // todo: Shininess conversion to SpecularPower?
         mwriter.WriteLine(String.Format(CultureInfo.InvariantCulture, "Ns {0:F4}", sm.SpecularPower));
     }
 }
コード例 #26
0
ファイル: WpfMaterial.cs プロジェクト: bnaand/xBim-Toolkit
 public void CreateMaterial(XbimTexture texture)
 {
     if (texture.ColourMap.Count > 1)
     {
         Material = new MaterialGroup();
         _Description = "Texture" ;
         foreach (var colour in texture.ColourMap)
         {
             _Description += " " + colour.ToString();
             ((MaterialGroup)Material).Children.Add(CreateMaterial(colour));
         }
     }
     else if(texture.ColourMap.Count == 1)
     {
         XbimColour colour = texture.ColourMap[0];
         Material = CreateMaterial(colour);
         _Description = "Texture " + colour.ToString();
     }
 }
コード例 #27
0
        public MandelbrotMountain()
        {
            solver = new MandelbrotSolver();

            var brush = new LinearGradientBrush();
            brush.StartPoint = new Point(0, 0);
            brush.EndPoint = new Point(1, 0);
            brush.GradientStops.Add(new GradientStop(Color.FromRgb(0, 7, 100), 0));
            brush.GradientStops.Add(new GradientStop(Color.FromRgb(32, 107, 203), 0.15));
            brush.GradientStops.Add(new GradientStop(Color.FromRgb(237, 255, 255), 0.42));
            brush.GradientStops.Add(new GradientStop(Color.FromRgb(255, 170, 0), 0.64));
            brush.GradientStops.Add(new GradientStop(Color.FromRgb(0, 0, 0), 0.854));
            //      brush.GradientStops.Add(new GradientStop(Color.FromRgb(0, 7, 100), 1.0));
            gradientMaterial = MaterialHelper.CreateMaterial(brush,null,Brushes.Gray,1.0,200);

            MaxIterations = 32;
            HeightFactor = 0.3;

            Generate();
        }
コード例 #28
0
        public bool Convert(string fileName)
        {
            Scene scene = Session.CurrentSession.CurrentProject.CurrentModel3D.Scene;
            /* Loads materials */
            
            Console.WriteLine(DEBUGmsg[0]);
            SystemMaterial[] materials = new SystemMaterial[scene.MaterialCount];
            string path = String.IsNullOrEmpty(fileName) ? String.Empty : Path.GetDirectoryName(fileName);
            LoadMaterial(materials, scene, path);

            /* Loads meshes */
            Console.WriteLine(DEBUGmsg[1]);
            GeometryModel3D[] meshes = new GeometryModel3D[scene.MeshCount];
            LoadMeshes(meshes, scene, materials);


            // UP: To Model
            // BELOW: In Display3DGridViewModel calls

            /* Loads model */
            Console.WriteLine(DEBUGmsg[2]);
            Model3DGroup model = this.ConvertNode(scene, scene.RootNode, meshes);


            /* Fixes Assimp transformation */
            if (null != model.Transform)
            {
                Transform3DGroup tg = new Transform3DGroup();
                tg.Children.Add(model.Transform);
                tg.Children.Add(new MatrixTransform3D(new Matrix3D(
                    1, 0, 0, 0,
                    0, 0, 1, 0,
                    0, -1, 0, 0,
                    0, 0, 0, 1)));
                model.Transform = tg;
            }

            Session.CurrentSession.ModelVisual.Content = model;
            return true;
        }
コード例 #29
0
        public BraceVisual3D(Material material, TeethVisual3D p)
        {
            if (p != null)
            {
                this.parent = p;
                gc = this.parent.gc;
                tc = this.parent.tc;
                bc = this.parent.bc;
                wc = this.parent.wc;

                Id = p.Id + "_brace" + p.Children.Count.ToString("00") + "." + p.Parent.Parent.patient.Id; ;

                if (model == null) model = new Brace();
                model.Id = Id;
                model.Location = (IsOuterBrace ? Smile.OUTERBRACE : Smile.INNERBRACE);

                //sample(material);
                //BindingOperations.SetBinding(this, TransformProperty, new Binding("TargetTransform") { Source = this });
                //BindingOperations.SetBinding(this.Manipulator,CombinedManipulator.TargetTransformProperty,new Binding("TargetTransform") { Source = this });

            }
        }
コード例 #30
0
        private void SetGeometry(string model)
        {
            Model3DGroup device = null;

            try
            {
                //Import 3D model file
                ModelImporter import = new ModelImporter();
                System.Windows.Media.Media3D.Material mat = MaterialHelper.CreateMaterial(
                    //new SolidColorBrush(Colors.SaddleBrown));
                    new SolidColorBrush(Colors.Pink));
                import.DefaultMaterial = mat;
                //Load the 3D model file
                device = import.Load(model);
            }
            catch (Exception e)
            {
                // Handle exception in case can not file 3D model
                MessageBox.Show("Exception Error : " + e.StackTrace);
            }
            Visual3DModel = device;
        }
コード例 #31
0
        /// <summary>
        /// Constructs a new cylinder primitive,
        /// with the specified size and tessellation level.
        /// </summary>
        public CylinderPrimitive(Material material,
                                 float height, float diameter, int tessellation)
        {
            if (tessellation < 3)
                throw new ArgumentOutOfRangeException("tessellation");

            height /= 2;
            float radius = diameter / 2;
            Vector3D down = new Vector3D(0, -1, 0);
            Vector3D up = new Vector3D(0, 1, 0);

            // Create a ring of triangles around the outside of the cylinder.
            for (int i = 0; i < tessellation; i++)
            {
                Vector3D normal = GetCircleVector(i, tessellation);
                Vector3D vertex = normal * radius + up * height;
                Point3D vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                AddVertex(vertexPoint, normal);

                vertex = normal * radius + down * height;
                vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                AddVertex(vertexPoint, normal);

                AddIndex(i * 2);
                AddIndex(i * 2 + 1);
                AddIndex((i * 2 + 2) % (tessellation * 2));

                AddIndex(i * 2 + 1);
                AddIndex((i * 2 + 3) % (tessellation * 2));
                AddIndex((i * 2 + 2) % (tessellation * 2));
            }

            // Create flat triangle fan caps to seal the top and bottom.
            CreateCap(tessellation, height, radius, up);
            CreateCap(tessellation, height, radius, down);

            InitializePrimitive(material);
        }
コード例 #32
0
        public static Model3D RhinotoHelixBrep(Brep brep, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup  = new Model3DGroup();
            var meshBuilder = new MeshBuilder(false, false);

            var jaggedAndFaster   = MeshingParameters.Coarse;
            var smoothAndSlower   = MeshingParameters.Smooth;
            var defaultMeshParams = MeshingParameters.Default;
            var verysmooth        = MeshingParameters.Smooth;

            verysmooth.MaximumEdgeLength = 5;
            var minimal = MeshingParameters.Minimal;

            var meshes = Mesh.CreateFromBrep(brep, verysmooth);

            if (meshes != null && meshes.Length != 0)
            {
                foreach (Mesh m in meshes)
                {
                    modelGroup.Children.Add(RhinotoHelixMesh(m, mat));
                }
            }
            return(modelGroup);
        }
コード例 #33
0
ファイル: WpfMaterial.cs プロジェクト: tnesser/XbimWindowsUI
 public void CreateMaterial(XbimTexture texture)
 {
     
     if (texture.ColourMap.Count > 1)
     {
         _material = new MaterialGroup();
         _description = "Texture" ; 
         bool transparent = true;
         foreach (var colour in texture.ColourMap)
         {
             if (!colour.IsTransparent) transparent = false; //only transparent if everything is transparent
             _description += " " + colour;
             ((MaterialGroup)_material).Children.Add(MaterialFromColour(colour));
         }
         IsTransparent = transparent;
     }
     else if(texture.ColourMap.Count == 1)
     {
         XbimColour colour = texture.ColourMap[0];
         _material = MaterialFromColour(colour);
         _description = "Texture " + colour;
         IsTransparent = colour.IsTransparent;
     }
 }
コード例 #34
0
 public GeometryModel3D MakeGeometryModel(Geometry3D geom, Material mat)
 {
     return new GeometryModel3D(geom, mat);
 }
コード例 #35
0
ファイル: ABModel3D.cs プロジェクト: carlhuth/GenXSource
        public ModelVisual3D[] ToAvalonObj()
        {
            // convert geometry
            if (MaterialIndices == null)
            {
                MeshGeometry3D geometry = new MeshGeometry3D();
                // geometry
                if (Geometry.Vertices != null)
                {
                    geometry.Positions = new Point3DCollection(Geometry.Vertices.Length);
                    for (int vertex = 0; vertex < Geometry.Vertices.Length; vertex++)
                    {
                        Vector3 position = Geometry.Vertices[vertex];
                        geometry.Positions.Add(new Point3D(position.X, position.Y, position.Z));
                    }
                }
                // normals
                if (Geometry.Normals != null)
                {
                    geometry.Normals = new Vector3DCollection(Geometry.Normals.Length);
                    for (int nIdx = 0; nIdx < Geometry.Normals.Length; nIdx++)
                    {
                        Vector3 normal = Geometry.Normals[nIdx];
                        geometry.Normals.Add(new Vector3D(normal.X, normal.Y, normal.Z));
                    }
                }
                // tex coords
                if (Geometry.TexCoords != null)
                {
                    geometry.TextureCoordinates = new PointCollection(Geometry.TexCoords.Length);
                    for (int tcIdx = 0; tcIdx < Geometry.TexCoords.Length; tcIdx++)
                    {
                        Vector2 texCoord = Geometry.TexCoords[tcIdx];
                        geometry.TextureCoordinates.Add(new System.Windows.Point(texCoord.X, texCoord.Y));
                    }
                }

                // triangle indices
                if (Geometry.PrimIndices != null)
                {
                    geometry.TriangleIndices = new Int32Collection(Geometry.PrimIndices.Length);
                    for (int tIdx = 0; tIdx < Geometry.PrimIndices.Length; tIdx++)
                    {
                        geometry.TriangleIndices.Add(Geometry.PrimIndices[tIdx]);
                    }
                }

                // material
                System.Windows.Media.Media3D.Material material = null;
                if (Materials != null)
                {
                    if (Materials[0].TextureName != null)
                    {
                        ImageBrush ib = new ImageBrush();
                        ib.ImageSource = new BitmapImage(new Uri(Materials[0].TextureName));
                        material       = new DiffuseMaterial(ib);
                    }
                    else
                    {
                        material = new DiffuseMaterial(new SolidColorBrush(System.Windows.Media.Color.FromArgb(Materials[0].Diffuse.A, Materials[0].Diffuse.R, Materials[0].Diffuse.G, Materials[0].Diffuse.B)));
                    }
                }
                ModelVisual3D model = new ModelVisual3D();
                model.Content = new GeometryModel3D(geometry, material);
                return(new ModelVisual3D[] { model });
            }
            else
            {
                // break up by material indices
                ModelVisual3D[] models      = new ModelVisual3D[MaterialIndices.Length];
                int[]           vertIdxRefs = new int[Geometry.Vertices.Length];
                int[]           modelVerts  = new int[Geometry.Vertices.Length];
                int             vertIdx     = 0;
                for (int mIdx = 0; mIdx < MaterialIndices.Length; mIdx++)
                {
                    // wipe ref index
                    for (int idxRef = 0; idxRef < vertIdxRefs.Length; idxRef++)
                    {
                        vertIdxRefs[idxRef] = -1;
                    }

                    MeshGeometry3D geometry = new MeshGeometry3D();
                    // refactor verticies
                    for (int i = 0; i < MaterialIndices[mIdx].Indices.Length; i++)
                    {
                        // check for existing ref
                        int index = MaterialIndices[mIdx].Indices[i];
                        if (vertIdxRefs[index] == -1)
                        {
                            vertIdxRefs[index]    = vertIdx;
                            modelVerts[vertIdx++] = index;
                        }
                        geometry.TriangleIndices.Add(vertIdxRefs[index]);
                    }

                    // write verts
                    geometry.Positions = new Point3DCollection(vertIdx);
                    for (int vertex = 0; vertex < vertIdx; vertex++)
                    {
                        Vector3 position = Geometry.Vertices[modelVerts[vertex]];
                        geometry.Positions.Add(new Point3D(position.X, position.Y, position.Z));
                    }
                    // normals
                    if (Geometry.Normals != null)
                    {
                        geometry.Normals = new Vector3DCollection(vertIdx);
                        for (int nIdx = 0; nIdx < vertIdx; nIdx++)
                        {
                            Vector3 normal = Geometry.Normals[modelVerts[nIdx]];
                            geometry.Normals.Add(new Vector3D(normal.X, normal.Y, normal.Z));
                        }
                    }
                    // tex coords
                    if (Geometry.TexCoords != null)
                    {
                        geometry.TextureCoordinates = new PointCollection(vertIdx);
                        for (int tcIdx = 0; tcIdx < vertIdx; tcIdx++)
                        {
                            Vector2 texCoord = Geometry.TexCoords[modelVerts[tcIdx]];
                            geometry.TextureCoordinates.Add(new System.Windows.Point(texCoord.X, texCoord.Y));
                        }
                    }

                    System.Windows.Media.Media3D.Material material = null;
                    if (MaterialIndices[mIdx].Material.TextureName != null)
                    {
                        ImageBrush ib = new ImageBrush();
                        ib.ImageSource = new BitmapImage(new Uri(MaterialIndices[mIdx].Material.TextureName));
                        material       = new DiffuseMaterial(ib);
                    }
                    else
                    {
                        ABColorARGB clr = MaterialIndices[mIdx].Material.Diffuse;
                        material = new DiffuseMaterial(new SolidColorBrush(System.Windows.Media.Color.FromArgb(clr.A, clr.R,
                                                                                                               clr.G, clr.B)));
                    }

                    models[mIdx]         = new ModelVisual3D();
                    models[mIdx].Content = new GeometryModel3D(geometry, material);
                }
                return(models);
            }
        }
コード例 #36
0
        // set of curves
        public static Model3D RhinoToHelixCurves(List <Curve> dcurves, double diameter, int resolution, int resolutiontube, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup  = new Model3DGroup();
            var meshBuilder = new MeshBuilder(false, false);

            foreach (Curve c in dcurves)
            {
                int curvedegree = c.Degree;
                if (curvedegree == 1)
                {
                    modelGroup.Children.Add(RhinoToHelixLine(c, diameter, resolutiontube, mat));
                }
                else if (c.IsPolyline())
                {
                    Polyline poly = new Polyline();
                    c.TryGetPolyline(out poly);
                    modelGroup.Children.Add(RhinoToHelixPolyline(poly, diameter, resolutiontube, mat));
                }
                else
                {
                    modelGroup.Children.Add(RhinoToHelixCurve(c, diameter, resolution, resolutiontube, mat));
                }
            }
            return(modelGroup);
        }
コード例 #37
0
        public static Model3D DrawLines(List <Line> lines, double diameter, int resolutiontube, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup  = new Model3DGroup();
            var meshBuilder = new MeshBuilder(false, false);


            foreach (Line l in lines)
            {
                meshBuilder.AddCylinder(RhinoToHelixPoint(l.From), RhinoToHelixPoint(l.To), diameter, resolutiontube); // resolution hard-coded, section parameter = radius
            }
            var mesh      = meshBuilder.ToMesh(true);
            var CMaterial = MaterialHelper.CreateMaterial(Colors.Gray);

            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = mesh, Material = CMaterial, BackMaterial = CMaterial
            });

            // Assign modelGroup to model to draw
            return(modelGroup);
        }
コード例 #38
0
        private static GeometryModel3D GetModel_WoodIron_Ring_Band(double ballRadius, double z, System.Windows.Media.Media3D.Material material, TriangleIndexed[] ball, SortedList <string, double> from, SortedList <string, double> to, string prefix)
        {
            const double ENLARGE = 1.04d;

            GeometryModel3D retVal = new GeometryModel3D();

            retVal.Material     = material;
            retVal.BackMaterial = material;

            double bandHeight     = WeaponDNA.GetKeyValue(prefix + "Height", from, to, StaticRandom.NextPercent(ballRadius * .15, .5));
            double bandHeightHalf = bandHeight / 2d;

            // Slice the hull at the top and bottom band z's
            Point3D[] slice1 = Math3D.GetIntersection_Hull_Plane(ball, new Triangle(new Point3D(0, 0, z - bandHeightHalf), new Point3D(1, 0, z - bandHeightHalf), new Point3D(0, 1, z - bandHeightHalf)));
            Point3D[] slice2 = Math3D.GetIntersection_Hull_Plane(ball, new Triangle(new Point3D(0, 0, z + bandHeightHalf), new Point3D(1, 0, z + bandHeightHalf), new Point3D(0, 1, z + bandHeightHalf)));

            // Enlarge those polygons xy, leave z alone
            slice1 = slice1.Select(o => new Point3D(o.X * ENLARGE, o.Y * ENLARGE, o.Z)).ToArray();
            slice2 = slice2.Select(o => new Point3D(o.X * ENLARGE, o.Y * ENLARGE, o.Z)).ToArray();

            // Now turn those two polygons into a 3d hull
            TriangleIndexed[] band = Math3D.GetConvexHull(UtilityCore.Iterate(slice1, slice2).ToArray());

            retVal.Geometry = UtilityWPF.GetMeshFromTriangles(band);

            return(retVal);
        }
コード例 #39
0
        /// <summary>
        /// Determines whether any part of the specified material is transparent.
        /// </summary>
        /// <param name="material">
        /// The material.
        /// </param>
        /// <returns>
        /// <c>true</c> if the specified material is transparent; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsTransparent(Material material)
        {
            var g = material as MaterialGroup;
            if (g != null)
            {
                if (g.Children.Any(IsTransparent))
                {
                    return true;
                }
            }

            var dm = material as DiffuseMaterial;
            if (dm != null)
            {
                if (IsTransparent(dm.Brush))
                {
                    return true;
                }

                if (dm.Color.A < 255)
                {
                    return true;
                }
            }

            return false;
        }
コード例 #40
0
        // general curve
        public static Model3D RhinoToHelixCurve(Rhino.Geometry.Curve curve, double diameter, int resolution, int resolutiontube, System.Windows.Media.Media3D.Material mat)
        {
            int curvedegree = curve.Degree;
            var modelGroup  = new Model3DGroup();

            Console.WriteLine("BS");

            if (curve.IsLinear()) // if line-like curve
            {
                Console.WriteLine("blabla");
                return(RhinoToHelixLine(curve, diameter, resolutiontube, mat));
            }

            else
            {
                var meshBuilder = new MeshBuilder(false, false);

                //Point3d[] pts = new Point3d[resolution];
                List <Point3D> path = new List <Point3D>();
                //curve.DivideByCount(resolution, true, out pts);
                path.Add(RhinoToHelixPoint(curve.PointAtEnd));
                path.Add(RhinoToHelixPoint(curve.PointAtStart));
                //foreach (Point3d pt in pts)
                //{
                //    path.Add(RhinoToHelixPoint(pt));
                //}
                meshBuilder.AddTube(path, diameter, resolutiontube, false);
                var meshHelix = meshBuilder.ToMesh(true);
                modelGroup.Children.Add(new GeometryModel3D {
                    Geometry = meshHelix, Material = mat, BackMaterial = mat
                });
            }
            return(modelGroup);
        }
コード例 #41
0
        private GeometryModel3D AddStandardModel(MeshGeometry3D mesh, Point3D position, System.Windows.Media.Media3D.Material wpfMaterial)
        {
            var model3D = new GeometryModel3D(mesh, wpfMaterial);

            model3D.Transform = new TranslateTransform3D(position.X, position.Y, position.Z);

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

            MainViewport.Children.Add(modelVisual3D);

            return(model3D);
        }
コード例 #42
0
        // polyline
        public static Model3D RhinoToHelixPolyline(Rhino.Geometry.Polyline poly, double diameter, int resolutiontube, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup  = new Model3DGroup();
            var meshBuilder = new MeshBuilder(false, false);

            Line[]         lines = poly.GetSegments();
            List <Point3D> path  = new List <Point3D>();

            foreach (Line l in lines)
            {
                path.Add(RhinoToHelixPoint(l.To));
            }
            path.Add(RhinoToHelixPoint(lines[0].From));

            meshBuilder.AddTube(path, diameter, resolutiontube, true);
            var meshHelix = meshBuilder.ToMesh(true);

            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = meshHelix, Material = mat, BackMaterial = mat
            });
            return(modelGroup);
        }
コード例 #43
0
ファイル: ModelGenerator.cs プロジェクト: q4a/SparkIV
        internal static ModelNode GenerateModel(Drawable drawable, TextureFile[] textures)
        {
            var random = new Random();

            var materials = new Material[drawable.Materials.Count];

            for (int i = 0; i < materials.Length; i++)
            {
                Brush brush =
                    new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, (byte)random.Next(0, 255),
                                                                            (byte)random.Next(0, 255),
                                                                            (byte)random.Next(0, 255)));

                var drawableMat = drawable.Materials[i];
                var texture     = drawableMat.Parameters[(int)ParamNameHash.Texture] as MaterialParamTexture;
                if (texture != null)
                {
                    // 1. Try looking in the embedded texture file (if any)
                    var textureObj = FindTexture(drawable.AttachedTexture, texture.TextureName);

                    // 2. Try looking in any attached external texture dictionaries
                    if (textureObj == null)
                    {
                        foreach (var file in textures)
                        {
                            textureObj = FindTexture(file, texture.TextureName);
                            if (textureObj != null)
                            {
                                break;
                            }
                        }
                    }

                    // Generate a brush if we were successful
                    if (textureObj != null)
                    {
                        var bitmap = textureObj.Decode() as Bitmap;

                        var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                            bitmap.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());

                        // For memory leak work around
                        bitmapSource.Freeze();

                        brush = new ImageBrush(bitmapSource);
                        (brush as ImageBrush).ViewportUnits = BrushMappingMode.Absolute;
                        (brush as ImageBrush).TileMode      = TileMode.Tile;

                        bitmap.Dispose();
                    }
                }

                materials[i] = new DiffuseMaterial(brush);
            }

            var drawableModelGroup = new Model3DGroup();
            var drawableModelNode  = new ModelNode {
                DataModel = drawable, Model3D = drawableModelGroup, Name = "Drawable", NoCount = true
            };

            foreach (var model in drawable.Models)
            {
                var modelGroup = new Model3DGroup();

                var modelNode = new ModelNode {
                    DataModel = model, Model3D = modelGroup, Name = "Model"
                };
                drawableModelNode.Children.Add(modelNode);

                foreach (var geometry in model.Geometries)
                {
                    var geometryIndex = 0;
                    var geometryGroup = new Model3DGroup();

                    var geometryNode = new ModelNode {
                        DataModel = geometry, Model3D = geometryGroup, Name = "Geometry"
                    };
                    modelNode.Children.Add(geometryNode);

                    foreach (var mesh in geometry.Meshes)
                    {
                        var mesh3D = new MeshGeometry3D();

                        var meshNode = new ModelNode {
                            DataModel = mesh, Model3D = null, Name = "Mesh"
                        };
                        geometryNode.Children.Add(meshNode);

                        Data.Vertex[] vertices = mesh.DecodeVertexData();
                        foreach (var vertex in vertices)
                        {
                            mesh3D.Positions.Add(new Point3D(vertex.Position.X, vertex.Position.Y, vertex.Position.Z));
                            if (mesh.VertexHasNormal)
                            {
                                mesh3D.Normals.Add(new Vector3D(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z));
                            }

                            if (mesh.VertexHasTexture)
                            {
                                mesh3D.TextureCoordinates.Add(new Point(vertex.TextureCoordinates[0].X, vertex.TextureCoordinates[0].Y));
                            }
                        }

                        ushort[] indices = mesh.DecodeIndexData();
                        for (int i = 0; i < mesh.FaceCount; i++)
                        {
                            mesh3D.TriangleIndices.Add(indices[i * 3 + 0]);
                            mesh3D.TriangleIndices.Add(indices[i * 3 + 1]);
                            mesh3D.TriangleIndices.Add(indices[i * 3 + 2]);
                        }

                        var material = materials[geometry.Meshes[geometryIndex].MaterialIndex];
                        var model3D  = new GeometryModel3D(mesh3D, material);

                        geometryGroup.Children.Add(model3D);
                        meshNode.Model3D = model3D;

                        geometryIndex++;
                    }
                    modelGroup.Children.Add(geometryGroup);
                }
                drawableModelGroup.Children.Add(modelGroup);
            }
            return(drawableModelNode);
        }
コード例 #44
0
ファイル: TrackBall.cs プロジェクト: charlierix/AsteroidMiner
        private static bool OrbitGetObjectDistance_IsTransparent_Material(Material material)
        {
            if (material is MaterialGroup)
            {
                #region MaterialGroup

                // Recurse
                foreach (Material childMaterial in ((MaterialGroup)material).Children)
                {
                    if (!OrbitGetObjectDistance_IsTransparent_Material(childMaterial))
                    {
                        return false;
                    }
                }

                #endregion
            }
            else if (material is DiffuseMaterial)
            {
                #region DiffuseMaterial

                DiffuseMaterial materialCast1 = (DiffuseMaterial)material;

                if (materialCast1.Brush == null)
                {
                    if (!UtilityWPF.IsTransparent(materialCast1.AmbientColor))		// this was all white when the brush was set.  Not sure what that means
                    {
                        return false;
                    }
                }
                else
                {
                    if (!UtilityWPF.IsTransparent(materialCast1.Brush))
                    {
                        return false;
                    }
                }

                // I don't think I want to include with this one
                //if (!UtilityWPF.IsTransparent(materialCast1.Color))
                //{
                //    return true;
                //}

                #endregion
            }
            else if (material is SpecularMaterial)
            {
                #region SpecularMaterial

                SpecularMaterial materialCast2 = (SpecularMaterial)material;

                if (!UtilityWPF.IsTransparent(materialCast2.Brush))
                {
                    return false;
                }

                #endregion
            }
            else if (material is EmissiveMaterial)
            {
                #region EmissiveMaterial

                EmissiveMaterial materialCast3 = (EmissiveMaterial)material;

                if (materialCast3.Brush == null)
                {
                    if (!UtilityWPF.IsTransparent(materialCast3.Color))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!UtilityWPF.IsTransparent(materialCast3.Brush))
                    {
                        return false;
                    }
                }

                #endregion
            }

            // It is transparent
            return true;
        }
コード例 #45
0
ファイル: ObjExporter.cs プロジェクト: BEEden/Diplomarbeit
        /// <summary>
        /// The export material.
        /// </summary>
        /// <param name="matName">
        /// The mat name.
        /// </param>
        /// <param name="material">
        /// The material.
        /// </param>
        /// <param name="backMaterial">
        /// The back material.
        /// </param>
        private void ExportMaterial(string matName, Material material, Material backMaterial)
        {
            this.mwriter.WriteLine(string.Format("newmtl {0}", matName));
            var dm = material as DiffuseMaterial;
            var sm = material as SpecularMaterial;
            var mg = material as MaterialGroup;
            if (mg != null)
            {
                foreach (var m in mg.Children)
                {
                    if (m is DiffuseMaterial)
                    {
                        dm = m as DiffuseMaterial;
                    }

                    if (m is SpecularMaterial)
                    {
                        sm = m as SpecularMaterial;
                    }
                }
            }

            if (dm != null)
            {
                var adjustedAmbientColor = dm.AmbientColor.ChangeIntensity(0.2);

                // this.mwriter.WriteLine(string.Format("Ka {0}", this.ToColorString(adjustedAmbientColor)));
                var scb = dm.Brush as SolidColorBrush;
                if (scb != null)
                {
                    this.mwriter.WriteLine(string.Format("Kd {0}", this.ToColorString(scb.Color)));

                    if (this.UseDissolveForTransparency)
                    {
                        // Dissolve factor
                        this.mwriter.WriteLine(
                            string.Format(CultureInfo.InvariantCulture, "d {0:F4}", scb.Color.A / 255.0));
                    }
                    else
                    {
                        // Transparency
                        this.mwriter.WriteLine(
                            string.Format(CultureInfo.InvariantCulture, "Tr {0:F4}", scb.Color.A / 255.0));
                    }
                }
                else
                {
                    var textureFilename = matName + ".png";
                    var texturePath = Path.Combine(this.directory, textureFilename);

                    // create .png bitmap file for the brush
                    RenderBrush(texturePath, dm.Brush, 1024, 1024);
                    this.mwriter.WriteLine(string.Format("map_Ka {0}", textureFilename));
                }
            }

            // Illumination model 1
            // This is a diffuse illumination model using Lambertian shading. The
            // color includes an ambient constant term and a diffuse shading term for
            // each light source.  The formula is
            // color = KaIa + Kd { SUM j=1..ls, (N * Lj)Ij }
            int illum = 1; // Lambertian

            if (sm != null)
            {
                var scb = sm.Brush as SolidColorBrush;
                this.mwriter.WriteLine(
                    string.Format(
                        "Ks {0}", this.ToColorString(scb != null ? scb.Color : Color.FromScRgb(1.0f, 0.2f, 0.2f, 0.2f))));

                // Illumination model 2
                // This is a diffuse and specular illumination model using Lambertian
                // shading and Blinn's interpretation of Phong's specular illumination
                // model (BLIN77).  The color includes an ambient constant term, and a
                // diffuse and specular shading term for each light source.  The formula
                // is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks { SUM j=1..ls, ((H*Hj)^Ns)Ij }
                illum = 2;

                // Specifies the specular exponent for the current material.  This defines the focus of the specular highlight.
                // "exponent" is the value for the specular exponent.  A high exponent results in a tight, concentrated highlight.  Ns values normally range from 0 to 1000.
                this.mwriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "Ns {0:F4}", sm.SpecularPower));
            }

            // roughness
            this.mwriter.WriteLine(string.Format("Ns {0}", 2));

            // Optical density (index of refraction)
            this.mwriter.WriteLine(string.Format("Ni {0}", 1));

            // Transmission filter
            this.mwriter.WriteLine(string.Format("Tf {0} {1} {2}", 1, 1, 1));

            // Illumination model
            // Illumination    Properties that are turned on in the
            // model           Property Editor
            // 0		Color on and Ambient off
            // 1		Color on and Ambient on
            // 2		Highlight on
            // 3		Reflection on and Ray trace on
            // 4		Transparency: Glass on
            // Reflection: Ray trace on
            // 5		Reflection: Fresnel on and Ray trace on
            // 6		Transparency: Refraction on
            // Reflection: Fresnel off and Ray trace on
            // 7		Transparency: Refraction on
            // Reflection: Fresnel on and Ray trace on
            // 8		Reflection on and Ray trace off
            // 9		Transparency: Glass on
            // Reflection: Ray trace off
            // 10		Casts shadows onto invisible surfaces
            this.mwriter.WriteLine(string.Format("illum {0}", illum));
        }
コード例 #46
0
        // LINES, POLYLINES, CURVES

        // simple line
        public static Model3D RhinoToHelixLine(Rhino.Geometry.Curve curve, double diameter, int resolutiontube, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup  = new Model3DGroup();
            var meshBuilder = new MeshBuilder(false, false);
            //Tube path
            List <Point3D> path = new List <Point3D>();

            path.Add(RhinoToHelixPoint(curve.PointAtStart));
            path.Add(RhinoToHelixPoint(curve.PointAtEnd));
            //Helix mesh creation
            meshBuilder.AddTube(path, diameter, resolutiontube, true);
            var meshHelix = meshBuilder.ToMesh(true);

            modelGroup.Children.Add(new GeometryModel3D {
                Geometry = meshHelix, Material = mat, BackMaterial = mat
            });

            return(modelGroup);
        }
コード例 #47
0
        /// <summary>
        /// Constructs a new sphere primitive,
        /// with the specified size and tessellation level.
        /// </summary>
        public SpherePrimitive(Material material,
                               float diameter, int tessellation)
        {
            if (tessellation < 3)
                throw new ArgumentOutOfRangeException("tessellation");

            Vector3D down = new Vector3D(0, -1, 0);
            Vector3D up = new Vector3D(0, 1, 0);

            int verticalSegments = tessellation;
            int horizontalSegments = tessellation * 2;

            float radius = diameter / 2;

            // Start with a single vertex at the bottom of the sphere.
            Vector3D vertex = down * radius;
            Point3D vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
            AddVertex(vertexPoint, down);

            // Create rings of vertices at progressively higher latitudes.
            for (int i = 0; i < verticalSegments - 1; i++)
            {
                float latitude = ((i + 1) * (float)Math.PI /
                                            verticalSegments) - (float)Math.PI / 2.0f;

                float dy = (float)Math.Sin(latitude);
                float dxz = (float)Math.Cos(latitude);

                // Create a single ring of vertices at this latitude.
                for (int j = 0; j < horizontalSegments; j++)
                {
                    float longitude = j * ((float)Math.PI * 2.0f) / horizontalSegments;

                    float dx = (float)Math.Cos(longitude) * dxz;
                    float dz = (float)Math.Sin(longitude) * dxz;

                    Vector3D normal = new Vector3D(dx, dy, dz);
                    vertex = normal * radius;
                    vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
                    AddVertex(vertexPoint, normal);
                }
            }

            // Finish with a single vertex at the top of the sphere.
            vertex = up * radius;
            vertexPoint = new Point3D(vertex.X, vertex.Y, vertex.Z);
            AddVertex(vertexPoint, up);

            // Create a fan connecting the bottom vertex to the bottom latitude ring.
            for (int i = 0; i < horizontalSegments; i++)
            {
                AddIndex(0);
                AddIndex(1 + (i + 1) % horizontalSegments);
                AddIndex(1 + i);
            }

            // Fill the sphere body with triangles joining each pair of latitude rings.
            for (int i = 0; i < verticalSegments - 2; i++)
            {
                for (int j = 0; j < horizontalSegments; j++)
                {
                    int nextI = i + 1;
                    int nextJ = (j + 1) % horizontalSegments;

                    AddIndex(1 + i * horizontalSegments + j);
                    AddIndex(1 + i * horizontalSegments + nextJ);
                    AddIndex(1 + nextI * horizontalSegments + j);

                    AddIndex(1 + i * horizontalSegments + nextJ);
                    AddIndex(1 + nextI * horizontalSegments + nextJ);
                    AddIndex(1 + nextI * horizontalSegments + j);
                }
            }

            // Create a fan connecting the top vertex to the top latitude ring.
            for (int i = 0; i < horizontalSegments; i++)
            {
                AddIndex(CurrentVertex - 1);
                AddIndex(CurrentVertex - 2 - (i + 1) % horizontalSegments);
                AddIndex(CurrentVertex - 2 - i);
            }

            InitializePrimitive(material);
        }
コード例 #48
0
        // Draw diverse geometries in a same model3D
        public static Model3D Draw(List <Curve> dcurves, List <Mesh> dmeshes, List <Brep> dbreps, double diameter, int resolution, int resolutiontube, System.Windows.Media.Media3D.Material mat)
        {
            var modelGroup  = new Model3DGroup();
            var meshBuilder = new MeshBuilder(false, false);

            if (dcurves.Count != 0)
            {
                modelGroup.Children.Add(RhinoToHelixCurves(dcurves, diameter, resolution, resolutiontube, mat));
            }


            if (dmeshes.Count != 0)
            {
                foreach (Mesh m in dmeshes)
                {
                    modelGroup.Children.Add(RhinotoHelixMesh(m, mat));
                }
            }


            if (dbreps.Count != 0)
            {
                foreach (Brep b in dbreps)
                {
                    modelGroup.Children.Add(RhinotoHelixBrep(b, mat));
                }
            }


            var meshHelix = meshBuilder.ToMesh(true);

            return(modelGroup);
        }
コード例 #49
0
 // Updatecurrentmodel
 public void UpdateCurrentModel(List <Line> lines, double diameter, int resolutiontube, System.Windows.Media.Media3D.Material mat)
 {
     this.CurrentModel = RhinoHelixUtilities.DrawLines(lines, diameter, resolutiontube, mat);
 }
コード例 #50
0
        private static Model3DGroup GetModel_WoodIron(WeaponSpikeBallDNA dna, WeaponSpikeBallDNA finalDNA, WeaponMaterialCache materials)
        {
            Model3DGroup retVal = new Model3DGroup();

            Random rand = StaticRandom.GetRandomForThread();
            var    from = dna.KeyValues;
            var    to   = finalDNA.KeyValues;

            double spikeLength = dna.Radius * 1.4d;
            double ballRadius  = dna.Radius * 1d;

            double spikeRadius = dna.Radius * .2;

            #region Ball

            System.Windows.Media.Media3D.Material material = materials.Ball_Wood;     // the property get returns a slightly random color

            GeometryModel3D geometry = new GeometryModel3D();

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

            // Create a convex hull out of semi evenly distibuted points
            int numHullPoints      = Convert.ToInt32(WeaponDNA.GetKeyValue("numHullPoints", from, to, rand.Next(20, 50)));
            TriangleIndexed[] ball = Math3D.GetConvexHull(Math3D.GetRandomVectors_SphericalShell_EvenDist(numHullPoints, ballRadius, .03, 10).Select(o => o.ToPoint()).ToArray());

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles(ball);

            retVal.Children.Add(geometry);

            #endregion

            // These are placed where the rings are, to push spikes away (so that spikes don't poke through the rings)
            List <Vector3D> staticPoints = new List <Vector3D>();

            #region Rings

            material = materials.Spike_Iron;     // the property get returns a slightly random color

            // 0, 1 or 2 rings.  Higher chance of 0 than 2
            int numRings = Convert.ToInt32(WeaponDNA.GetKeyValue("numRings", from, to, Math.Floor(rand.NextPow(2, 2.3))));

            double[] zs = new double[0];

            switch (numRings)
            {
            case 0:
                break;

            case 1:
                zs = new double[] { WeaponDNA.GetKeyValue("ringZ1", from, to, Math1D.GetNearZeroValue(ballRadius * .75)) };
                break;

            case 2:
                double z1 = WeaponDNA.GetKeyValue("ringZ1", from, to, Math1D.GetNearZeroValue(ballRadius * .75));
                double z2 = 0;

                if (from == null || !from.TryGetValue("ringZ2", out z2))
                {
                    do
                    {
                        z2 = Math1D.GetNearZeroValue(ballRadius * .75);
                    } while (Math.Abs(z1 - z2) < ballRadius * .4);

                    to.Add("ringZ2", z2);
                }

                zs = new double[] { z1, z2 };
                break;

            default:
                throw new ApplicationException("Unexpected number of rings: " + numRings.ToString());
            }

            // Build the rings at the z offsets that were calculated above
            for (int cntr = 0; cntr < zs.Length; cntr++)
            {
                retVal.Children.Add(GetModel_WoodIron_Ring_Band(ballRadius, zs[cntr], material, ball, from, to, "ringZ" + cntr.ToString()));

                // Store points at the rings
                double ringRadiusAvg = Math.Sqrt((ballRadius * ballRadius) - (zs[cntr] * zs[cntr]));
                staticPoints.AddRange(Math2D.GetCircle_Cached(7).Select(o => (o.ToVector() * ringRadiusAvg).ToVector3D(zs[cntr])));
            }

            #endregion

            #region Spikes

            Vector3D[] staticPointsArr = staticPoints.Count == 0 ? null : staticPoints.ToArray();
            double[]   staticRepulse   = staticPoints.Count == 0 ? null : Enumerable.Range(0, staticPoints.Count).Select(o => .005d).ToArray();

            int numSpikes = Convert.ToInt32(WeaponDNA.GetKeyValue("numSpikes", from, to, rand.Next(8, 14)));

            Vector3D[] spikeLocations;
            if (from != null && from.ContainsKey("spikeLoc0X"))
            {
                spikeLocations = new Vector3D[numSpikes];

                for (int cntr = 0; cntr < numSpikes; cntr++)
                {
                    string prefix = "spikeLoc" + cntr.ToString();
                    spikeLocations[cntr] = new Vector3D(to[prefix + "X"], to[prefix + "Y"], to[prefix + "Z"]);
                }
            }
            else
            {
                spikeLocations = Math3D.GetRandomVectors_SphericalShell_EvenDist(numSpikes, ballRadius, .03, 10, null, staticPointsArr, staticRepulse);

                for (int cntr = 0; cntr < numSpikes; cntr++)
                {
                    string prefix = "spikeLoc" + cntr.ToString();
                    to.Add(prefix + "X", spikeLocations[cntr].X);
                    to.Add(prefix + "Y", spikeLocations[cntr].Y);
                    to.Add(prefix + "Z", spikeLocations[cntr].Z);
                }
            }

            for (int cntr = 0; cntr < spikeLocations.Length; cntr++)
            {
                material = materials.Spike_Iron;     // the property get returns a slightly random color

                geometry = new GeometryModel3D();

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

                RotateTransform3D transform = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new Vector3D(0, 0, 1), spikeLocations[cntr])));       // the tube builds along z

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

                double spikeRadiusA = WeaponDNA.GetKeyValue("spikeRad" + cntr.ToString(), from, to, rand.NextPercent(spikeRadius, .33));

                rings.Add(new TubeRingRegularPolygon(0, false, spikeRadiusA, spikeRadiusA, false));
                rings.Add(new TubeRingPoint(WeaponDNA.GetKeyValue("spikeLen" + cntr.ToString(), from, to, rand.NextDouble(spikeLength * .9, spikeLength * 1.1)), false));

                int  numSegments = Convert.ToInt32(WeaponDNA.GetKeyValue("spikeSegs" + cntr.ToString(), from, to, rand.Next(3, 6)));
                bool isSoft      = Math1D.IsNearZero(WeaponDNA.GetKeyValue("spikeSoft" + cntr.ToString(), from, to, rand.Next(2)));
                geometry.Geometry = UtilityWPF.GetMultiRingedTube(numSegments, rings, isSoft, false, transform);

                retVal.Children.Add(geometry);
            }

            #endregion

            return(retVal);
        }
 public GeometryModel3D(Geometry3D geometry, Material material)
 {
 }
コード例 #52
0
 public void UpdateCurrentModelAdvanced(List <Curve> curves, List <Mesh> meshes, List <Brep> brep, double diameter, int resolution, int resolutiontube, System.Windows.Media.Media3D.Material mat)
 {
     this.CurrentModel = RhinoHelixUtilities.Draw(curves, meshes, brep, diameter, resolution, resolutiontube, mat);
 }