示例#1
0
        public void SetRaw(string filename)
        {
            byte[] bytes = System.IO.File.ReadAllBytes(filename);
            int    count = 0;

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    var i = BitConverter.ToInt32(bytes, (x + y * width) * 4) / scale;
                    data[count] = (int)(i > depth ? depth : i < 0 ? 0 : i);
                    count++;
                }
            }

            //スカラ量の設定
            using (var da = vtkIntArray.New())
            {
                //IntPtr pIds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * data.Length);
                Marshal.Copy(data, 0, pIds, data.Length);
                da.SetArray((IntPtr)pIds, data.Length, 1);
                pointPoly.GetPointData().SetScalars(da);
                //Marshal.FreeHGlobal(pIds); //解放したらアカン
            }
        }
示例#2
0
        public void ReadDataByLine(string filename)
        {
            try
            {
                var dataStrings = File.ReadAllLines(filename);
                points = vtkPoints.New();
                points.SetNumberOfPoints(dataStrings.Length);

                var colorArray = vtkUnsignedCharArray.New();
                colorArray.SetNumberOfComponents(3);

                for (var i = 0; i < dataStrings.Length; i++)
                {
                    var data = dataStrings[i].Split(' ');

                    if (data.Length < 6)
                    {
                        continue;
                    }

                    points.SetPoint(i, int.Parse(data[0]), int.Parse(data[1]), int.Parse(data[2]));
                    colorArray.InsertNextTuple3(double.Parse(data[3]), double.Parse(data[4]), double.Parse(data[5]));
                }

                PolyData = vtkPolyData.New();
                PolyData.SetPoints(points);
                PolyData.GetPointData().SetScalars(colorArray);
                PolyData.Update();
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#3
0
        public void SetActor(double warpScale)
        {
            //IntPtr pIds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * data.Length);

            //スカラ量の設定
            using (var da = vtkIntArray.New())
                using (var warp = vtkWarpScalar.New())
                    using (var mapper = vtkPolyDataMapper.New())
                    {
                        Marshal.Copy(data, 0, pIds, Size);
                        da.SetArray((IntPtr)pIds, Size, 1);
                        pointPoly.GetPointData().SetScalars(da);
                        //Marshal.FreeHGlobal(pIds); //解放したらアカン

                        warp.SetInput(pointPoly);
                        warp.SetScaleFactor(warpScale);

                        mapper.SetInput(warp.GetPolyDataOutput());
                        //mapper.SetInput(pointPoly);
                        mapper.SetLookupTable(lut);
                        mapper.SetScalarRange(0.0, Depth);
                        mapper.ScalarVisibilityOn();

                        DataActor.SetMapper(mapper);
                        DataActor.GetProperty().SetPointSize(2);

                        RaisePropertyChanged("render");
                    }
        }
示例#4
0
        public static void SaveRectData(string filename, vtkPolyData polyData, Rectangle rect)
        {
            try
            {
                SimplePointFile.OpenWriteFile(filename);

                var color = polyData.GetPointData().GetScalars();

                for (var i = 0; i < rect.Height; i++)
                {
                    for (var j = 0; j < rect.Width; j++)
                    {
                        var data = polyData.GetPoint(i * rect.Width + j);
                        var c    = color.GetComponent(i * rect.Width + j, 0);

                        SimplePointFile.Writeline(new[] { data[0], data[1], data[2], c, c, c });
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                SimplePointFile.CloseWriteFile();
            }
        }
示例#5
0
        public void WriteVTP(string filePath, List <Vector3d> point_data, List <Vector3> cellPointsList, Dictionary <String, vtkDataArray> scalar_dataArray, List <String> arrayNames)
        {
            vtkPoints points = vtkPoints.New();

            for (int i = 0; i < point_data.Count(); i++)
            {
                points.InsertNextPoint(point_data[i].X, point_data[i].Y, point_data[i].Z);
            }

            vtkPolyData polyData = vtkPolyData.New();

            polyData.SetPoints(points);

            vtkCellArray cellArrayOne = vtkCellArray.New();

            for (int i = 0; i < cellPointsList.Count(); i++)
            {
                vtkTetra tetra = vtkTetra.New();

                tetra.GetPointIds().SetId(0, (long)cellPointsList[i][0]);
                tetra.GetPointIds().SetId(1, (long)cellPointsList[i][1]);
                tetra.GetPointIds().SetId(2, (long)cellPointsList[i][2]);
                tetra.GetPointIds().SetId(3, (long)cellPointsList[i][2]);
                cellArrayOne.InsertNextCell(tetra);
            }

            polyData.SetPolys(cellArrayOne);

            int numberOfScalarData = scalar_dataArray.Count();

            for (int i = 0; i < numberOfScalarData; i++)
            {
                scalar_dataArray.TryGetValue(arrayNames[i], out vtkDataArray scalars);
                polyData.GetPointData().AddArray(scalars);
            }

            vtkXMLPolyDataWriter writer = vtkXMLPolyDataWriter.New();

            // add file ending if it is not existent
            string suffix = (".vtp");

            if (!(filePath.EndsWith(suffix)))
            {
                filePath += suffix;
            }

            writer.SetFileName(filePath);
            writer.SetInput(polyData);
            writer.Write();

            // Read and display file for verification that it was written correctly
            vtkXMLStructuredGridReader reader = vtkXMLStructuredGridReader.New();

            if (reader.CanReadFile(filePath) == 0)
            {
                //MessageBox.Show("Cannot read file \"" + filePath + "\"", "Error", MessageBoxButtons.OK);
                return;
            }
            Console.WriteLine("VTP file was writen and is saved at {0}", filePath);
        }
示例#6
0
        public static void GetRectData(vtkPolyData data, Rectangle rect)
        {
            var points     = vtkPoints.New();
            var colorArray = vtkUnsignedCharArray.New();

            colorArray.SetNumberOfComponents(3);

            RectImageData = vtkImageData.New();
            RectImageData.SetExtent(0, rect.Size.Width - 1, 0, rect.Size.Height - 1, 0, 0);
            RectImageData.SetNumberOfScalarComponents(1);
            RectImageData.SetScalarTypeToUnsignedChar();

            for (var i = rect.Top; i < rect.Bottom; i++)
            {
                for (var j = rect.Left; j < rect.Right; j++)
                {
                    double[] p = data.GetPoint(i * ImageWidth + j);
                    points.InsertNextPoint(j - rect.Left, i - rect.Top, p[2]);

                    double[] c = data.GetPointData().GetScalars().GetTuple3(i * ImageWidth + j);
                    colorArray.InsertNextTuple3(c[0], c[1], c[2]);

                    RectImageData.SetScalarComponentFromDouble(j - rect.Left, i - rect.Top, 0, 0, c[0]);
                }
            }


            RectPolyData = vtkPolyData.New();
            RectPolyData.SetPoints(points);
            RectPolyData.GetPointData().SetScalars(colorArray);
            RectPolyData.Update();
        }
示例#7
0
        public static void SaveData(int ratio, string filename)
        {
            try
            {
                SimplePointFile.OpenWriteFile(filename);

                var color = PolyData.GetPointData().GetScalars();

                for (var i = 0; i < ImageHeight; i += ratio)
                {
                    for (var j = 0; j < ImageWidth; j += ratio)
                    {
                        var data = PolyData.GetPoint(i * ImageWidth + j);
                        var c    = color.GetComponent(i * ImageWidth + j, 0);
                        SimplePointFile.Writeline(new[] { data[0] / ratio, data[1] / ratio, data[2], c, c, c });
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                SimplePointFile.CloseWriteFile();
            }
        }
示例#8
0
        private static void NullPoint()
        {
            vtkPoints points = vtkPoints.New();

            points.InsertNextPoint(1, 1, 1);
            points.InsertNextPoint(2, 2, 2);
            points.InsertNextPoint(3, 3, 3);

            vtkPolyData polydata = vtkPolyData.New();

            polydata.SetPoints(points);

            vtkFloatArray floatArray = vtkFloatArray.New();

            floatArray.SetNumberOfValues(3);
            floatArray.SetNumberOfComponents(1);
            floatArray.SetName("FloatArray");
            for (int i = 0; i < 3; i++)
            {
                floatArray.SetValue(i, 2);
            }
            polydata.GetPointData().AddArray(floatArray);

            vtkIntArray intArray = vtkIntArray.New();

            intArray.SetNumberOfValues(3);
            intArray.SetNumberOfComponents(1);
            intArray.SetName("IntArray");
            for (int i = 0; i < 3; i++)
            {
                intArray.SetValue(i, 2);
            }

            polydata.GetPointData().AddArray(intArray);

            Console.WriteLine("PointIdx   x y z " + "floatArray" + " " + "intArray");
            Console.WriteLine("----------------------------------------");
            for (int i = 0; i < 3; i++)
            {
                double[]      p = polydata.GetPoint(i);
                vtkFloatArray pointsFloatArray = vtkFloatArray.SafeDownCast(polydata.GetPointData().GetArray("FloatArray"));
                vtkIntArray   pointsIntArray   = vtkIntArray.SafeDownCast(polydata.GetPointData().GetArray("IntArray"));
                Console.WriteLine("   " + i + "       " + p[0] + " " + p[1] + " " + p[2] + "    "
                                  + pointsFloatArray.GetValue(i) + "          " + pointsIntArray.GetValue(i));
            }

            polydata.GetPointData().NullPoint(1);
            polydata.Modified();
            Console.WriteLine("");

            for (int i = 0; i < 3; i++)
            {
                double[]      p = polydata.GetPoint(i);
                vtkFloatArray pointsFloatArray = vtkFloatArray.SafeDownCast(polydata.GetPointData().GetArray("FloatArray"));
                vtkIntArray   pointsIntArray   = vtkIntArray.SafeDownCast(polydata.GetPointData().GetArray("IntArray"));
                Console.WriteLine("   " + i + "       " + p[0] + " " + p[1] + " " + p[2] + "    "
                                  + pointsFloatArray.GetValue(i) + "          " + pointsIntArray.GetValue(i));
            }
        }
示例#9
0
        public static void SetColorByImage(vtkPolyData data, vtkImageData image, Rectangle rect)
        {
            for (int i = 0; i < rect.Width * rect.Height; i++)
            {
                float c = image.GetScalarComponentAsFloat(i % rect.Width, i / rect.Width, 0, 0);
                data.GetPointData().GetScalars().SetTuple3(i, c, c, c);
            }

            data.Modified();
        }
示例#10
0
        public VTKDataModel(SimulationModel sm)
        {
            simModel = sm;

            int numCells = sm.Cells.Count;

            cellIDs = vtkIntArray.New();
            cellIDs.SetNumberOfComponents(1);
            cellIDs.SetNumberOfValues(numCells);
            cellIDs.SetName(cellIdsArrayName);

            cellTypes = vtkIntArray.New();
            cellTypes.SetNumberOfComponents(1);
            cellTypes.SetNumberOfValues(numCells);
            cellTypes.SetName(cellTypeArrayName);

            points = vtkPoints.New();
            points.SetNumberOfPoints(numCells);

            verts = vtkCellArray.New();
            verts.Allocate(verts.EstimateSize(1, numCells), 1000);
            verts.InsertNextCell(numCells);

            foreach (MotileCell cell in sm.Cells)
            {
                int i = cell.CellId;
                int c = cell.CellType;
                double[] p = cell.Position;
                points.SetPoint(i, p[0], p[1], p[2]);
                cellIDs.SetValue(i, i);
                cellTypes.SetValue(i, c);
                verts.InsertCellPoint(i);
            }

            poly = vtkPolyData.New();
            poly.SetPoints(points);
            poly.SetVerts(verts);
            poly.GetPointData().AddArray(cellIDs);
            poly.GetPointData().AddArray(cellTypes);
        }
示例#11
0
        private void SetFlatData(float[] src)
        {
            using (var warp = vtkWarpScalar.New())
                using (var mapper = vtkPolyDataMapper.New())
                    using (var actor = vtkActor.New())
                    {
                        if (src != null)
                        {
                            IntPtr pIds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * Size);
                            Marshal.Copy(src, 0, pIds, Size);

                            var da = vtkFloatArray.New();
                            da.SetArray(pIds, Size, 1);

                            pointPoly.GetPointData().SetScalars(da);
                        }
                        warp.SetInput(pointPoly);
                        warp.SetScaleFactor(Scale);

                        //var transform = vtkTransform.New();
                        //transform.RotateX(180);
                        //var transformFilter = vtkTransformPolyDataFilter.New();
                        //transformFilter.SetTransform(transform);
                        //transformFilter.SetInputConnection(warp.GetOutputPort());

                        //mapper.SetInput(transformFilter.GetOutput());
                        mapper.SetInput(warp.GetPolyDataOutput());

                        mapper.SetLookupTable(lut);
                        //mapper.SetColorModeToMapScalars();
                        mapper.SetScalarRange(ScalarRangeMin, ScalarRangeMax);

                        DataActor.SetMapper(mapper);
                        DataActor.GetProperty().SetPointSize(PointSize);
                        //DataActor.SetOrientation(90, 0, 0);
                    }
        }
示例#12
0
        public static void ReadDataFromFile(string filename)
        {
            try
            {
                SimplePointFile.GetImageInfo(filename);

                ImageWidth  = SimplePointFile.ImageWidth;
                ImageHeight = SimplePointFile.ImageHeight;

                //Console.WriteLine("ImageWidth:" + ImageWidth);
                //Console.WriteLine("ImageHeight:" + ImageHeight);

                var points = vtkPoints.New();

                var colorArray = vtkUnsignedCharArray.New();
                colorArray.SetNumberOfComponents(3);

                ImageData = vtkImageData.New();
                ImageData.SetExtent(0, ImageWidth - 1, 0, ImageHeight - 1, 0, 0);
                ImageData.SetNumberOfScalarComponents(1);
                ImageData.SetScalarTypeToUnsignedChar();


                SimplePointFile.OpenReadFile(filename);
                double[] data;
                while ((data = SimplePointFile.ReadLine()) != null)
                {
                    points.InsertNextPoint(data[0], data[1], data[2]);
                    colorArray.InsertNextTuple3(data[3], data[4], data[5]);

                    ImageData.SetScalarComponentFromDouble((int)data[0], (int)data[1], 0, 0, data[3]);
                }

                PolyData = vtkPolyData.New();
                PolyData.SetPoints(points);
                PolyData.GetPointData().SetScalars(colorArray);
                PolyData.Update();

                //Console.WriteLine("PolyData & ImageData Load.");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                SimplePointFile.CloseReadFile();
            }
        }
示例#13
0
        private vtkActor2D VirtualHeaterVTKBuilder()
        {
            vtkActor2D actor = vtkActor2D.New();

            vtkPoints      pointSource = vtkPoints.New();
            vtkStringArray labels      = vtkStringArray.New();
            vtkCellArray   verts       = vtkCellArray.New();

            TowerModelInstance.VTKLabelGetter(ref pointSource, ref labels, ref verts, paras, WorkSpaceInstance);

            //MessageBox.Show(labels.ToString());
            vtkPolyData polyData = vtkPolyData.New();

            polyData.SetPoints(pointSource);
            polyData.SetVerts(verts);
            polyData.GetPointData().AddArray(labels);

            vtkTextProperty textProp = vtkTextProperty.New();

            textProp.SetFontSize(12);
            //textProp.SetColor(1.0, 1.0, 0.5);
            textProp.SetFontFamilyToArial();

            vtkPointSetToLabelHierarchy hie = vtkPointSetToLabelHierarchy.New();

            hie.SetInput(polyData);
            hie.SetMaximumDepth(15);
            hie.SetLabelArrayName("111");
            hie.SetTargetLabelCount(100);
            hie.SetTextProperty(textProp);

            vtkLabelPlacementMapper labelMapper = new vtkLabelPlacementMapper();

            labelMapper.SetInputConnection(hie.GetOutputPort());

            vtkFreeTypeLabelRenderStrategy strategy = new vtkFreeTypeLabelRenderStrategy();

            labelMapper.SetRenderStrategy(strategy);
            labelMapper.UseDepthBufferOn();
            labelMapper.SetShapeToNone();
            labelMapper.SetStyleToOutline();

            //labelMapper.UseUnicodeStringsOff();

            actor.SetMapper(labelMapper);
            return(actor);
        }
示例#14
0
        public void ReadPointIntoObject(RenderWindowControl renderWindowControl, List <nvmPointModel> listPointModel)
        {
            vtkUnsignedCharArray colors = vtkUnsignedCharArray.New();

            colors.SetNumberOfComponents(3);
            colors.SetName("Colors");
            vtkPoints points = vtkPoints.New();

            foreach (var point in listPointModel)
            {
                colors.InsertNextValue(byte.Parse(point.color.X.ToString(), CultureInfo.InvariantCulture));
                colors.InsertNextValue(byte.Parse(point.color.Y.ToString(), CultureInfo.InvariantCulture));
                colors.InsertNextValue(byte.Parse(point.color.Z.ToString(), CultureInfo.InvariantCulture));
                points.InsertNextPoint(
                    double.Parse(point.position.X.ToString(), CultureInfo.InvariantCulture),
                    double.Parse(point.position.Y.ToString(), CultureInfo.InvariantCulture),
                    double.Parse(point.position.Z.ToString(), CultureInfo.InvariantCulture));
            }

            vtkPolyData polydata = vtkPolyData.New();

            polydata.SetPoints(points);
            polydata.GetPointData().SetScalars(colors);
            vtkVertexGlyphFilter glyphFilter = vtkVertexGlyphFilter.New();

            glyphFilter.SetInputConnection(polydata.GetProducerPort());

            // Visualize
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();

            mapper.SetInputConnection(glyphFilter.GetOutputPort());
            vtkActor actor = vtkActor.New();

            actor.SetMapper(mapper);
            actor.GetProperty().SetPointSize(2);
            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();

            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(actor);
            renderer.ResetCamera();
        }
示例#15
0
        private static void FindAllData(ref vtkPolyData polydata)
        {
            Console.WriteLine("Normals: " + polydata.GetPointData().GetNormals());

            int numberOfPointArrays = polydata.GetPointData().GetNumberOfArrays();

            Console.WriteLine("Number of PointData arrays: " + numberOfPointArrays);

            int numberOfCellArrays = polydata.GetCellData().GetNumberOfArrays();

            Console.WriteLine("Number of CellData arrays: " + numberOfCellArrays);

            Console.WriteLine(
                Environment.NewLine +
                "Type table/key: " +
                Environment.NewLine +
                "-------------------------");
            //more values can be found in <VTK_DIR>/Common/vtkSetGet.h

            Console.WriteLine(3 + " unsigned char");
            Console.WriteLine(7 + " unsigned int");
            Console.WriteLine(10 + " float");
            Console.WriteLine(11 + " double" + Environment.NewLine);

            for (int i = 0; i < numberOfPointArrays; i++)
            {
                // The following two lines are equivalent
                //arrayNames.push_back(polydata.GetPointData().GetArray(i).GetName());
                //arrayNames.push_back(polydata.GetPointData().GetArrayName(i));
                int    dataTypeID       = polydata.GetPointData().GetArray(i).GetDataType();
                string dataTypeAsString = polydata.GetPointData().GetArray(i).GetDataTypeAsString();
                Console.WriteLine("Array " + i + ": "
                                  + polydata.GetPointData().GetArrayName(i)
                                  + " (type: " + dataTypeID + ")"
                                  + " (type as string: " + dataTypeAsString + ")" + Environment.NewLine);
            }

            for (int i = 0; i < numberOfCellArrays; i++)
            {
                // The following two lines are equivalent
                //polydata.GetPointData().GetArray(i).GetName();
                //polydata.GetPointData().GetArrayName(i);
                int    dataTypeID       = polydata.GetCellData().GetArray(i).GetDataType();
                string dataTypeAsString = polydata.GetPointData().GetArray(i).GetDataTypeAsString();
                Console.WriteLine("Array " + i + ": "
                                  + polydata.GetCellData().GetArrayName(i)
                                  + " (type: " + dataTypeID + ")"
                                  + " (type as string: " + dataTypeAsString + ")");
            }
        }
示例#16
0
        public static void SetColorByHeight(vtkPolyData data, Rectangle rect)
        {
            double zmin = data.GetPoint(0)[2];
            double zmax = zmin;

            for (int i = 0; i < rect.Width * rect.Height; i++)
            {
                double z = data.GetPoint(i)[2];
                if (z < zmin)
                {
                    zmin = z;
                }

                if (z > zmax)
                {
                    zmax = z;
                }
            }

            //Console.WriteLine("Zmin:" + zmin + " Zmax:" + zmax);

            vtkColorTransferFunction colorFunction = vtkColorTransferFunction.New();

            colorFunction.AddRGBPoint(zmin, 0, 0, 1);
            colorFunction.AddRGBPoint(zmax, 1, 0, 0);

            //Console.WriteLine("Color:" + colorFunction.GetColor(0)[0] + " "
            //                  + colorFunction.GetColor(0)[1] + " "
            //                  + colorFunction.GetColor(0)[2]);

            for (int i = 0; i < rect.Width * rect.Height; i++)
            {
                double   z = data.GetPoint(i)[2];
                double[] c = colorFunction.GetColor(z);
                data.GetPointData().GetScalars().SetTuple3(i, c[0] * 255, c[1] * 255, c[2] * 255);
            }

            data.Modified();
        }
        private static void FindAllData(ref vtkPolyData polydata)
        {
            Console.WriteLine("Normals: " + polydata.GetPointData().GetNormals());

             int numberOfPointArrays = polydata.GetPointData().GetNumberOfArrays();
             Console.WriteLine("Number of PointData arrays: " + numberOfPointArrays);

             int numberOfCellArrays = polydata.GetCellData().GetNumberOfArrays();
             Console.WriteLine("Number of CellData arrays: " + numberOfCellArrays);

             Console.WriteLine(
            Environment.NewLine +
            "Type table/key: " +
            Environment.NewLine +
            "-------------------------");
             //more values can be found in <VTK_DIR>/Common/vtkSetGet.h

             Console.WriteLine(3 + " unsigned char");
             Console.WriteLine(7 + " unsigned int");
             Console.WriteLine(10 + " float");
             Console.WriteLine(11 + " double" + Environment.NewLine);

             for(int i = 0; i < numberOfPointArrays; i++) {
            // The following two lines are equivalent
            //arrayNames.push_back(polydata.GetPointData().GetArray(i).GetName());
            //arrayNames.push_back(polydata.GetPointData().GetArrayName(i));
            int dataTypeID = polydata.GetPointData().GetArray(i).GetDataType();
            string dataTypeAsString = polydata.GetPointData().GetArray(i).GetDataTypeAsString();
            Console.WriteLine("Array " + i + ": "
               + polydata.GetPointData().GetArrayName(i)
               + " (type: " + dataTypeID + ")"
               + " (type as string: " + dataTypeAsString + ")" + Environment.NewLine);
             }

             for(int i = 0; i < numberOfCellArrays; i++) {
            // The following two lines are equivalent
            //polydata.GetPointData().GetArray(i).GetName();
            //polydata.GetPointData().GetArrayName(i);
            int dataTypeID = polydata.GetCellData().GetArray(i).GetDataType();
            string dataTypeAsString = polydata.GetPointData().GetArray(i).GetDataTypeAsString();
            Console.WriteLine("Array " + i + ": "
               + polydata.GetCellData().GetArrayName(i)
               + " (type: " + dataTypeID + ")"
               + " (type as string: " + dataTypeAsString + ")");
             }
        }
        private void RenderXYZColor()
        {
            FileStream   fs = null;
            StreamReader sr = null;
            String       sLineBuffer;

            String[]  sXYZ;
            char[]    chDelimiter = new char[] { ' ', '\t', ';' };
            double[]  xyz         = new double[3];
            double[]  rgb         = new double[3];
            vtkPoints points      = vtkPoints.New();
            vtkPoints colors      = vtkPoints.New();
            int       cnt         = 0;

            try
            {
                // in case file must be open in another application too use "FileShare.ReadWrite"
                fs = new FileStream(m_FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                sr = new StreamReader(fs);

                vtkDoubleArray colorScalor = new vtkDoubleArray();
                int            n           = 1;
                while (!sr.EndOfStream)
                {
                    sLineBuffer = sr.ReadLine();
                    cnt++;
                    sXYZ = sLineBuffer.Split(chDelimiter, StringSplitOptions.RemoveEmptyEntries);
                    if (sXYZ == null || sXYZ.Length != 6)
                    {
                        MessageBox.Show("data seems to be in wrong format at line " + cnt, "Format Exception", MessageBoxButtons.OK);
                        return;
                    }
                    xyz[0] = double.Parse(sXYZ[0], CultureInfo.InvariantCulture) * 11100;
                    xyz[1] = double.Parse(sXYZ[1], CultureInfo.InvariantCulture) * 11100;
                    xyz[2] = double.Parse(sXYZ[2], CultureInfo.InvariantCulture);

                    rgb[0] = double.Parse(sXYZ[0], CultureInfo.InvariantCulture);
                    rgb[1] = double.Parse(sXYZ[1], CultureInfo.InvariantCulture);
                    rgb[2] = double.Parse(sXYZ[2], CultureInfo.InvariantCulture);

                    points.InsertNextPoint(xyz[0], xyz[1], xyz[2]);
                    colors.InsertNextPoint(rgb[0], rgb[1], rgb[2]);
                    colorScalor.InsertNextTuple1(n++);
                }
                vtkPolyData polydata = vtkPolyData.New();
                polydata.SetPoints(points);
                polydata.GetPointData().SetScalars(colorScalor); //设置点的Scalar(标量)属性

                vtkVertexGlyphFilter glyphFilter = vtkVertexGlyphFilter.New();
                glyphFilter.SetInputConnection(polydata.GetProducerPort());

                vtkLookupTable lookupTable = new vtkLookupTable();
                lookupTable.SetNumberOfColors(n);
                // SetSetTableValue(vtkIdType  indx, double r, double g, double  b, double a);
                Random random = new Random();
                for (int i = 0; i < n; i++)
                {
                    double[] tmp = colors.GetPoint(i);
                    double   r   = tmp[0];
                    double   g   = tmp[1];
                    double   b   = tmp[2];
                    lookupTable.SetTableValue(i, r, g, b, 1);
                }

                // Visualize
                vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
                mapper.SetInputConnection(glyphFilter.GetOutputPort());
                mapper.SetLookupTable(lookupTable);
                mapper.SetScalarRange(1, n);

                vtkActor actor = vtkActor.New();
                actor.SetMapper(mapper);
                actor.GetProperty().SetPointSize(1);
                //actor.GetProperty().SetColor(1, 0.5, 0);
                // add our actor to the renderer
                m_Renderer.AddActor(actor);
                imgPropList.Add(actor);

                m_Renderer.ResetCamera();

                //Rerender the screen
                m_RenderWindow.Render();
                m_Renderer.Render();
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "IOException", MessageBoxButtons.OK);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                    sr = null;
                }
            }
        }
示例#19
0
        private void WarpVector()
        {
            vtkPoints points = vtkPoints.New();

            points.InsertNextPoint(0.0, 0.0, 0.0);
            points.InsertNextPoint(1.0, 0.0, 0.0);
            points.InsertNextPoint(2.0, 0.0, 0.0);
            points.InsertNextPoint(3.0, 0.0, 0.0);
            points.InsertNextPoint(4.0, 0.0, 0.0);

            vtkCellArray lines = vtkCellArray.New();
            vtkLine      line  = vtkLine.New();

            line.GetPointIds().SetId(0, 0);
            line.GetPointIds().SetId(1, 1);
            lines.InsertNextCell(line);
            line.GetPointIds().SetId(0, 1);
            line.GetPointIds().SetId(1, 2);
            lines.InsertNextCell(line);
            line.GetPointIds().SetId(0, 2);
            line.GetPointIds().SetId(1, 3);
            lines.InsertNextCell(line);
            line.GetPointIds().SetId(0, 3);
            line.GetPointIds().SetId(1, 4);
            lines.InsertNextCell(line);

            vtkDoubleArray warpData = vtkDoubleArray.New();

            warpData.SetNumberOfComponents(3);
            warpData.SetName("warpData");
            double[] warp = new double[] { 0.0, 0.0, 0.0 };
            warp[1] = 0.0;
            warpData.InsertNextTuple3(warp[0], warp[1], warp[2]);
            warp[1] = 0.1;
            warpData.InsertNextTuple3(warp[0], warp[1], warp[2]);
            warp[1] = 0.3;
            warpData.InsertNextTuple3(warp[0], warp[1], warp[2]);
            warp[1] = 0.0;
            warpData.InsertNextTuple3(warp[0], warp[1], warp[2]);
            warp[1] = 0.1;
            warpData.InsertNextTuple3(warp[0], warp[1], warp[2]);

            vtkPolyData polydata = vtkPolyData.New();

            polydata.SetPoints(points);
            polydata.SetLines(lines);
            polydata.GetPointData().AddArray(warpData);
            polydata.GetPointData().SetActiveVectors(warpData.GetName());

            //WarpVector will use the array marked as active vector in polydata
            //it has to be a 3 component array
            //with the same number of tuples as points in polydata
            vtkWarpVector warpVector = vtkWarpVector.New();

#if VTK_MAJOR_VERSION_5
            warpVector.SetInput(polydata);
#else
            warpVector.SetInputData(polydata);
#endif
            warpVector.Update();

            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            mapper.SetInput(warpVector.GetPolyDataOutput());
#else
            mapper.SetInputData(warpVector.GetPolyDataOutput());
#endif
            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);
            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
            // set background color
            renderer.SetBackground(.2, .6, .3);
            renderer.AddActor(actor);
        }
        private void Window_Activated(object sender, EventArgs e)
        {
            vtkPolyData   cube    = new vtkPolyData();
            vtkPoints     points  = new vtkPoints();
            vtkCellArray  polys   = new vtkCellArray();
            vtkFloatArray scalars = new vtkFloatArray();

            Kitware.VTK.RenderWindowControl vtkControl = new Kitware.VTK.RenderWindowControl();
            vtkControl.AddTestActors = false;
            vtkControl.Location      = new System.Drawing.Point(10, 10);
            vtkControl.Name          = "_renwin";
            vtkControl.Size          = new System.Drawing.Size(100, 100);
            vtkControl.TabIndex      = 0;
            vtkControl.TestText      = null;
            vtkControl.Dock          = System.Windows.Forms.DockStyle.Fill;
            vtkformhost.Child        = vtkControl;
            vtkformhost.Visibility   = System.Windows.Visibility.Visible;


            int i;

            float[][] x = new float[8][]
            {
                new float[] { 0, 0, 0 }, //第0个点的坐标
                new float[] { 1, 0, 0 }, //第1个点的坐标
                new float[] { 1, 1, 0 }, //第2个点的坐标
                new float[] { 0, 1, 0 }, //3
                new float[] { 0, 0, 1 }, //4
                new float[] { 1, 0, 1 }, //5
                new float[] { 1, 1, 1 }, //6
                new float[] { 0, 1, 1 } //7
            };
            for (i = 0; i < 8; i++)
            {
                points.InsertPoint(i, x[i][0], x[i][1], x[i][2]);                    //加载点,创建数据结构的几何
            }
            List <int[]> temp = new List <int[]>();

            int[] temparray0 = new int[4] {
                0, 1, 2, 3
            };                                           //第0,1,2,3个点连接在一起,成为一个单元
            int[] temparray1 = new int[4] {
                4, 5, 6, 7
            };                                           //第4,5,6,7个点连接在一起,成为一个单元
            int[] temparray2 = new int[4] {
                0, 1, 5, 4
            };
            int[] temparray3 = new int[4] {
                1, 2, 6, 5
            };
            int[] temparray4 = new int[4] {
                2, 3, 7, 6
            };
            int[] temparray5 = new int[4] {
                3, 0, 4, 7
            };
            temp.Add(temparray0);
            temp.Add(temparray1);
            temp.Add(temparray2);
            temp.Add(temparray3);
            temp.Add(temparray4);
            temp.Add(temparray5);
            //因为在activiz中没有vtkIdType这个类,所以用了其他的方法代替C++代码中的实现。
            for (int j = 0; j < temp.Count; j++)
            {
                IntPtr pP = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * 4);
                Marshal.Copy(temp[j], 0, pP, 4);
                polys.InsertNextCell(4, pP);//加载单元,定义数据集的拓扑
                Marshal.FreeHGlobal(pP);
            }
            for (i = 0; i < 8; i++)
            {
                scalars.InsertTuple1(i, i);                    //为每一个点设置点属性。
            }
            cube.SetPoints(points);
            cube.SetPolys(polys);
            cube.GetPointData().SetScalars(scalars);

            vtkPolyDataMapper cubemapper = new vtkPainterPolyDataMapper();

            cubemapper.SetInput(cube);
            cubemapper.SetScalarRange(0, 7);

            vtkActor cubeactor = new vtkActor();

            cubeactor.SetMapper(cubemapper);

            // Create components of the rendering subsystem
            //
            vtkRenderWindow _renwin = vtkControl.RenderWindow;
            vtkRenderer     ren1    = _renwin.GetRenderers().GetFirstRenderer();


            // Add the actors to the renderer, set the window size
            //
            ren1.AddViewProp(cubeactor);
            _renwin.SetSize(250, 250);
            _renwin.Render();
            ren1.ResetCamera();
        }
示例#21
0
        public bool Read_Poly_Data_File(string filename)
        {
            //Initalize VTK Reader
            vtkXMLPolyDataReader reader = new vtkXMLPolyDataReader();

            reader.SetFileName(filename);

            reader.Update();

            vtkPolyData polydata = reader.GetOutput();

            if (polydata == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Invalid Poly data Input");

                return(false);
            }

            // Read Point Coordinates
            int numPoints = (int)polydata.GetNumberOfPoints();

            List <Vector3d> point_dat = new List <Vector3d>();

            if (numPoints != 0)
            {
                double[] pt;

                for (int i = 0; i < numPoints; i++)
                {
                    pt = polydata.GetPoint(i);

                    point_dat.Add(new Vector3d((float)pt[0], (float)pt[1], (float)pt[2]));
                }
                if (this.vertex_data.ContainsKey("vertices"))
                {
                    this.vertex_data["vertices"] = point_dat;
                }
                else
                {
                    this.vertex_data.Add("vertices", point_dat);
                }
                Console.WriteLine("All points read in correctly!");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("---------------No Points existent");
            }

            // Read Point Indices
            int numpolydatacells = (int)polydata.GetNumberOfCells();

            vtkCell   polydataCell;
            vtkIdList pts;

            if (numpolydatacells != 0)
            {
                int counter = 0;
                cells.SetNumberOfCells(numpolydatacells);

                for (int i = 0; i < numpolydatacells; i++)
                {
                    polydataCell = polydata.GetCell(i);

                    int numCellPoints = (int)polydataCell.GetNumberOfPoints();
                    cells.InsertNextCell(polydataCell);

                    Vector3 trianglePoints = new Vector3();
                    if (numCellPoints == 3)
                    {
                        pts = polydataCell.GetPointIds();

                        int one   = (int)pts.GetId(0);
                        int two   = (int)pts.GetId(1);
                        int three = (int)pts.GetId(2);
                        //this.Get_Triangle(counter, pts);
                        trianglePoints = new Vector3(one, two, three);
                        counter++;
                    }
                    triangleList.Add(trianglePoints);
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("---------------No Triangles existent");
            }

            // Read point data
            vtkPointData pointData = polydata.GetPointData();

            // Load point attributes
            this.Load_Point_Attributes(pointData);

            return(true);
        }
        private void BandedPolyDataContourFilter()
        {
            vtkPoints pts = vtkPoints.New();

            pts.InsertPoint(0, 0, 0, 0);
            pts.InsertPoint(1, 0, 1, 0);
            pts.InsertPoint(2, 0, 2, 0);
            pts.InsertPoint(3, 1, 0, 0);
            pts.InsertPoint(4, 1, 1, 0);
            pts.InsertPoint(5, 1, 2, 0);
            pts.InsertPoint(6, 2, 0, 0);
            pts.InsertPoint(7, 2, 2, 0);
            pts.InsertPoint(8, 3, 0, 0);
            pts.InsertPoint(9, 3, 1, 0);
            pts.InsertPoint(10, 3, 2, 0);
            pts.InsertPoint(11, 4, 0, 0);
            pts.InsertPoint(12, 6, 0, 0);
            pts.InsertPoint(13, 5, 2, 0);
            pts.InsertPoint(14, 7, 0, 0);
            pts.InsertPoint(15, 9, 0, 0);
            pts.InsertPoint(16, 7, 2, 0);
            pts.InsertPoint(17, 9, 2, 0);
            pts.InsertPoint(18, 10, 0, 0);
            pts.InsertPoint(19, 12, 0, 0);
            pts.InsertPoint(20, 10, 1, 0);
            pts.InsertPoint(21, 12, 1, 0);
            pts.InsertPoint(22, 10, 2, 0);
            pts.InsertPoint(23, 12, 2, 0);
            pts.InsertPoint(24, 10, 3, 0);
            pts.InsertPoint(25, 12, 3, 0);

            vtkCellArray polys = vtkCellArray.New();

            polys.InsertNextCell(4);
            polys.InsertCellPoint(14);
            polys.InsertCellPoint(15);
            polys.InsertCellPoint(17);
            polys.InsertCellPoint(16);
            polys.InsertNextCell(3);
            polys.InsertCellPoint(11);
            polys.InsertCellPoint(12);
            polys.InsertCellPoint(13);

            vtkFloatArray scalars = vtkFloatArray.New();

            scalars.SetNumberOfTuples(26);
            scalars.SetTuple1(0, 0);
            scalars.SetTuple1(1, 50);
            scalars.SetTuple1(2, 100);
            scalars.SetTuple1(3, 0);
            scalars.SetTuple1(4, 50);
            scalars.SetTuple1(5, 100);
            scalars.SetTuple1(6, 10);
            scalars.SetTuple1(7, 90);
            scalars.SetTuple1(8, 10);
            scalars.SetTuple1(9, 50);
            scalars.SetTuple1(10, 90);
            scalars.SetTuple1(11, 10);
            scalars.SetTuple1(12, 40);
            scalars.SetTuple1(13, 100);
            scalars.SetTuple1(14, 0);
            scalars.SetTuple1(15, 60);
            scalars.SetTuple1(16, 40);
            scalars.SetTuple1(17, 100);
            scalars.SetTuple1(18, 0);
            scalars.SetTuple1(19, 25);
            scalars.SetTuple1(20, 25);
            scalars.SetTuple1(21, 50);
            scalars.SetTuple1(22, 50);
            scalars.SetTuple1(23, 75);
            scalars.SetTuple1(24, 75);
            scalars.SetTuple1(25, 100);

            vtkPolyData polyData = vtkPolyData.New();

            polyData.SetPoints(pts);
            polyData.SetPolys(polys);
            polyData.GetPointData().SetScalars(scalars);

            vtkBandedPolyDataContourFilter bf = vtkBandedPolyDataContourFilter.New();

#if VTK_MAJOR_VERSION_5
            bf.SetInput(polyData);
#else
            bf.SetInputData(polyData);
#endif
            bf.GenerateValues(3, 25, 75);

            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
            mapper.SetInputConnection(bf.GetOutputPort());
            mapper.SetScalarModeToUseCellData();
            mapper.SetScalarRange(0, 4);
            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
            // set background color
            renderer.SetBackground(.2, .3, .4);
            // add our actor to the renderer
            renderer.AddActor(actor);
        }
示例#23
0
        private void WeightedTransformFilter()
        {
            // Use a sphere as a basis of the shape
            vtkSphereSource sphere = vtkSphereSource.New();

            sphere.SetPhiResolution(40);
            sphere.SetThetaResolution(40);
            sphere.Update();

            vtkPolyData sphereData = sphere.GetOutput();

            // Create a data array to hold the weighting coefficients
            vtkFloatArray tfarray = vtkFloatArray.New();
            int           npoints = sphereData.GetNumberOfPoints();

            tfarray.SetNumberOfComponents(2);
            tfarray.SetNumberOfTuples(npoints);

            // Parameterize the sphere along the z axis, and fill the weights
            // with (1.0-a, a) to linearly interpolate across the shape
            IntPtr pPoint = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * 3);

            double[] point = new double[3];
            for (int i = 0; i < npoints; i++)
            {
                sphereData.GetPoint(i, pPoint);
                Marshal.Copy(pPoint, point, 0, 3);
                double x = point[0];
                double y = point[1];
                double z = point[2];

                double zn  = z + 0.5;
                double zn1 = 1.0 - zn;
                if (zn > 1.0)
                {
                    zn = 1.0;
                }
                if (zn1 < 0.0)
                {
                    zn1 = 0.0;
                }

                tfarray.SetComponent(i, 0, zn1);
                tfarray.SetComponent(i, 1, zn);
            }
            Marshal.FreeHGlobal(pPoint);

            // Create field data to hold the array, and bind it to the sphere
            vtkFieldData fd = vtkFieldData.New();

            tfarray.SetName("weights");
            sphereData.GetPointData().AddArray(tfarray);

            // Use an ordinary transform to stretch the shape
            vtkTransform stretch = vtkTransform.New();

            stretch.Scale(1, 1, 3.2);

            vtkTransformFilter stretchFilter = vtkTransformFilter.New();

            stretchFilter.SetInputConnection(sphereData.GetProducerPort());
            stretchFilter.SetTransform(stretch);

            // Now, for the weighted transform stuff
            vtkWeightedTransformFilter weightedTrans = vtkWeightedTransformFilter.New();

            // Create two transforms to interpolate between
            vtkTransform identity = vtkTransform.New();

            identity.Identity();

            vtkTransform rotated      = vtkTransform.New();
            double       rotatedAngle = 45;

            rotated.RotateX(rotatedAngle);

            weightedTrans.SetNumberOfTransforms(2);
            weightedTrans.SetTransform(identity, 0);
            weightedTrans.SetTransform(rotated, 1);
            // which data array should the filter use ?
            weightedTrans.SetWeightArray("weights");

            weightedTrans.SetInputConnection(stretchFilter.GetOutputPort());

            vtkPolyDataMapper weightedTransMapper = vtkPolyDataMapper.New();

            weightedTransMapper.SetInputConnection(weightedTrans.GetOutputPort());
            vtkActor weightedTransActor = vtkActor.New();

            weightedTransActor.SetMapper(weightedTransMapper);
            weightedTransActor.GetProperty().SetDiffuseColor(0.8, 0.8, 0.1);
            weightedTransActor.GetProperty().SetRepresentationToSurface();

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();

            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(weightedTransActor);

            renderer.ResetCamera();
            renderer.GetActiveCamera().Azimuth(90);
            renderer.GetActiveCamera().Dolly(1);
        }
示例#24
0
        private void ColoredElevationMap()
        {
            // Create a grid of points (height/terrian map)
            vtkPoints points = vtkPoints.New();

            uint   GridSize = 20;
            double xx, yy, zz;

            for (uint x = 0; x < GridSize; x++)
            {
                for (uint y = 0; y < GridSize; y++)
                {
                    xx = x + vtkMath.Random(-.2, .2);
                    yy = y + vtkMath.Random(-.2, .2);
                    zz = vtkMath.Random(-.5, .5);
                    points.InsertNextPoint(xx, yy, zz);
                }
            }

            // Add the grid points to a polydata object
            vtkPolyData inputPolyData = vtkPolyData.New();

            inputPolyData.SetPoints(points);

            // Triangulate the grid points
            vtkDelaunay2D delaunay = vtkDelaunay2D.New();

#if VTK_MAJOR_VERSION_5
            delaunay.SetInput(inputPolyData);
#else
            delaunay.SetInputData(inputPolyData);
#endif
            delaunay.Update();
            vtkPolyData outputPolyData = delaunay.GetOutput();

            double[] bounds = outputPolyData.GetBounds();

            // Find min and max z
            double minz = bounds[4];
            double maxz = bounds[5];

            Debug.WriteLine("minz: " + minz);
            Debug.WriteLine("maxz: " + maxz);

            // Create the color map
            vtkLookupTable colorLookupTable = vtkLookupTable.New();
            colorLookupTable.SetTableRange(minz, maxz);
            colorLookupTable.Build();

            // Generate the colors for each point based on the color map
            vtkUnsignedCharArray colors = vtkUnsignedCharArray.New();
            colors.SetNumberOfComponents(3);
            colors.SetName("Colors");

            Debug.WriteLine("There are " + outputPolyData.GetNumberOfPoints()
                            + " points.");


#if UNSAFE // fastest way to fill color array
            colors.SetNumberOfTuples(outputPolyData.GetNumberOfPoints());
            unsafe {
                byte *pColor = (byte *)colors.GetPointer(0).ToPointer();

                for (int i = 0; i < outputPolyData.GetNumberOfPoints(); i++)
                {
                    double[] p = outputPolyData.GetPoint(i);

                    double[] dcolor = colorLookupTable.GetColor(p[2]);
                    Debug.WriteLine("dcolor: "
                                    + dcolor[0] + " "
                                    + dcolor[1] + " "
                                    + dcolor[2]);

                    byte[] color = new byte[3];
                    for (uint j = 0; j < 3; j++)
                    {
                        color[j] = (byte)(255 * dcolor[j]);
                    }
                    Debug.WriteLine("color: "
                                    + color[0] + " "
                                    + color[1] + " "
                                    + color[2]);

                    *(pColor + 3 * i)     = color[0];
                    *(pColor + 3 * i + 1) = color[1];
                    *(pColor + 3 * i + 2) = color[2];
                }
            }
#else
            for (int i = 0; i < outputPolyData.GetNumberOfPoints(); i++)
            {
                double[] p = outputPolyData.GetPoint(i);

                double[] dcolor = colorLookupTable.GetColor(p[2]);
                Debug.WriteLine("dcolor: "
                                + dcolor[0] + " "
                                + dcolor[1] + " "
                                + dcolor[2]);

                byte[] color = new byte[3];
                for (uint j = 0; j < 3; j++)
                {
                    color[j] = (byte)(255 * dcolor[j]);
                }
                Debug.WriteLine("color: "
                                + color[0] + " "
                                + color[1] + " "
                                + color[2]);
                colors.InsertNextTuple3(color[0], color[1], color[2]);
                //IntPtr pColor = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * 3);
                //Marshal.Copy(color, 0, pColor, 3);
                //colors.InsertNextTupleValue(pColor);
                //Marshal.FreeHGlobal(pColor);
            }
#endif

            outputPolyData.GetPointData().SetScalars(colors);

            // Create a mapper and actor
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            mapper.SetInputConnection(outputPolyData.GetProducerPort());
#else
            mapper.SetInputData(outputPolyData);
#endif

            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(actor);
        }
示例#25
0
        /// <summary>
        /// Generates a Unity Mesh from a vtkPolyData.
        /// </summary>
        /// <param name="pd">The vtk poly data.</param>
        /// <returns>The Unity Mesh (without colors).</returns>
        private static Mesh PolyDataToMesh(vtkPolyData pd)
        {
            if (pd == null)
            {
                Debug.LogWarning("No PolyData passed!");
                return null;
            }

            var numVertices = pd.GetNumberOfPoints();
            if (numVertices == 0)
            {
                Debug.LogWarning("No vertices to convert!");
                return null;
            }

            var mesh = new Mesh();

            // Points / Vertices
            var vertices = new Vector3[numVertices];
            for (var i = 0; i < numVertices; ++i)
            {
                var pnt = pd.GetPoint(i);
                // Flip z-up to y-up
                vertices[i] = new Vector3(-(float) pnt[0], (float) pnt[2], (float) pnt[1]);
            }
            mesh.vertices = vertices;

            // Normals
            var vtkNormals = pd.GetPointData().GetNormals();
            if (vtkNormals != null)
            {
                var numNormals = vtkNormals.GetNumberOfTuples();
                var normals = new Vector3[numNormals];
                for (var i = 0; i < numNormals; i++)
                {
                    var normal = vtkNormals.GetTuple3(i);
                    // flip normals ?
                    normals[i] = new Vector3(-(float) normal[0], -(float) normal[1], -(float) normal[2]);
                }
                mesh.normals = normals;
            }
            else
            {
                Debug.Log("No Normals!");
            }

            // Texture coordinates
            var vtkTexCoords = pd.GetPointData().GetTCoords();
            if (vtkTexCoords != null)
            {
                var numCoords = vtkTexCoords.GetNumberOfTuples();
                var uvs = new Vector2[numCoords];
                for (var i = 0; i < numCoords; ++i)
                {
                    var texCoords = vtkTexCoords.GetTuple2(i);
                    uvs[i] = new Vector2((float) texCoords[0], (float) texCoords[1]);
                }
                mesh.uv = uvs;
            }

            // Triangles / Cells
            var numTriangles = pd.GetNumberOfPolys();
            var polys = pd.GetPolys();
            if (polys.GetNumberOfCells() > 0)
            {
                var triangles = new int[numTriangles*3];
                var prim = 0;
                var pts = vtkIdList.New();
                polys.InitTraversal();
                while (polys.GetNextCell(pts) != 0)
                {
                    for (var i = 0; i < pts.GetNumberOfIds(); ++i)
                        triangles[prim*3 + i] = pts.GetId(i);

                    ++prim;
                }
                mesh.SetTriangles(triangles, 0);
                //Mesh.RecalculateNormals();
                mesh.RecalculateBounds();
                return mesh;
            }

            // Lines
            var lines = pd.GetLines();
            if (lines.GetNumberOfCells() > 0)
            {
                var idList = new ArrayList();
                var pts = vtkIdList.New();
                lines.InitTraversal();
                while (lines.GetNextCell(pts) != 0)
                {
                    for (var i = 0; i < pts.GetNumberOfIds() - 1; ++i)
                    {
                        idList.Add(pts.GetId(i));
                        idList.Add(pts.GetId(i + 1));
                    }
                }

                mesh.SetIndices(idList.ToArray(typeof (int)) as int[], MeshTopology.Lines, 0);
                mesh.RecalculateBounds();
                return mesh;
            }

            // Points
            var points = pd.GetVerts();
            var numPointCells = points.GetNumberOfCells();
            if (numPointCells > 0)
            {
                var idList = new ArrayList();
                var pts = vtkIdList.New();
                points.InitTraversal();
                while (points.GetNextCell(pts) != 0)
                {
                    for (int i = 0; i < pts.GetNumberOfIds(); ++i)
                    {
                        idList.Add(pts.GetId(i));
                    }
                }

                mesh.SetIndices(idList.ToArray(typeof (int)) as int[], MeshTopology.Points, 0);
                mesh.RecalculateBounds();
            }

            return mesh;
        }
示例#26
0
        private void ElevationFilter()
        {
            // Created a grid of points (heigh/terrian map)
            vtkPoints points = vtkPoints.New();

            uint GridSize = 10;

            for (uint x = 0; x < GridSize; x++)
            {
                for (uint y = 0; y < GridSize; y++)
                {
                    points.InsertNextPoint(x, y, (x + y) / (y + 1));
                }
            }
            double[] bounds = points.GetBounds();

            // Add the grid points to a polydata object
            vtkPolyData inputPolyData = vtkPolyData.New();

            inputPolyData.SetPoints(points);

            // Triangulate the grid points
            vtkDelaunay2D delaunay = vtkDelaunay2D.New();

#if VTK_MAJOR_VERSION_5
            delaunay.SetInput(inputPolyData);
#else
            delaunay.SetInputData(inputPolyData);
#endif
            delaunay.Update();

            vtkElevationFilter elevationFilter = vtkElevationFilter.New();
            elevationFilter.SetInputConnection(delaunay.GetOutputPort());
            elevationFilter.SetLowPoint(0.0, 0.0, bounds[4]);
            elevationFilter.SetHighPoint(0.0, 0.0, bounds[5]);
            elevationFilter.Update();

            vtkPolyData output = vtkPolyData.New();
            output.ShallowCopy(vtkPolyData.SafeDownCast(elevationFilter.GetOutput()));

            vtkFloatArray elevation =
                vtkFloatArray.SafeDownCast(output.GetPointData().GetArray("Elevation"));

            // Create the color map
            vtkLookupTable colorLookupTable = vtkLookupTable.New();
            colorLookupTable.SetTableRange(bounds[4], bounds[5]);
            colorLookupTable.Build();

            // Generate the colors for each point based on the color map
            vtkUnsignedCharArray colors = vtkUnsignedCharArray.New();
            colors.SetNumberOfComponents(3);
            colors.SetName("Colors");

            for (int i = 0; i < output.GetNumberOfPoints(); i++)
            {
                double val = elevation.GetValue(i);
                Debug.WriteLine("val: " + val);

                double[] dcolor = colorLookupTable.GetColor(val);
                //Debug.WriteLine("dcolor: "
                //          + dcolor[0] + " "
                //          + dcolor[1] + " "
                //          + dcolor[2]);
                byte[] color = new byte[3];
                for (int j = 0; j < 3; j++)
                {
                    color[j] = (byte)(255 * dcolor[j]);
                }
                //Debug.WriteLine("color: "
                //          + color[0] + " "
                //          + color[1] + " "
                //          + color[2]);

                colors.InsertNextTuple3(color[0], color[1], color[2]);
            }

            output.GetPointData().AddArray(colors);

            // Visualize
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            mapper.SetInputConnection(output.GetProducerPort());
#else
            mapper.SetInputData(output);
#endif

            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(actor);
        }