XAML 如何在VisualStudio 2022社区版17.5.4中绘制三角形网格,在2023年?

bpzcxfmw  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(106)

我在Windows 11上的Visual Studio中有一个WPF项目(.NET7)。
我想画一个三角形,其法线在Viewport3D区域内。Windows打开了,但除了白色的背景,我什么也没看到。我还尝试添加一个摄像头并将其指向不同的方向,但这并没有帮助。

<Application x:Class="Test.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">   
</Application>
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Viewport3D Name="viewport3D"/>
    </Grid>
</Window>
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace Test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            MeshGeometry3D mesh = new MeshGeometry3D();
            mesh.Positions.Add(new Point3D(0, 0, -1));
            mesh.Positions.Add(new Point3D(0, 1, -1));
            mesh.Positions.Add(new Point3D(1, 0, -1));
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(2);

            GeometryModel3D model = new GeometryModel3D(mesh, new DiffuseMaterial(Brushes.Red));

            ModelVisual3D visual = new ModelVisual3D();
            visual.Content = model;

            viewport3D.Children.Add(visual);
        }
    }
}

有人能提供一个最小的例子,一个3D三角形被渲染在一个viewport3D?

wdebmtf2

wdebmtf21#

我最好的猜测是,你还没有画三角形的反面,一定要以相反的顺序再次添加相同的索引(顺序决定哪一边将渲染)。
这段代码应该可以工作:

MeshGeometry3D mesh = new MeshGeometry3D();
mesh.Positions.Add(new Point3D(-5, -5, 0));
mesh.Positions.Add(new Point3D(5, -5, 0));
mesh.Positions.Add(new Point3D(0, 5, 0));

//Add one side of the triangle
mesh.TriangleIndices.Add(0);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(2);

//Add the reverse side of the triangle
mesh.TriangleIndices.Add(2);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(0);

GeometryModel3D model = new GeometryModel3D(mesh, new DiffuseMaterial(Brushes.Red));

ModelVisual3D visual = new ModelVisual3D();
visual.Content = model;

viewport3D.Children.Add(visual);

//Light the scene, otherwise everything will be black
var light = new ModelVisual3D();
light.Content = new AmbientLight(Colors.White);
viewport3D.Children.Add(light);

//Set the camera on the Z axis looking back to origin   
var camera = new PerspectiveCamera(
  position: new Point3D(0, 0, -40),
  lookDirection: new Vector3D(0, 0, 1),
  upDirection: new Vector3D(0, 1, 0),
  fieldOfView: 60);
camera.NearPlaneDistance = 1;
camera.FarPlaneDistance = 100;
viewport3D.Camera = camera;

然而,我得到了非常奇怪的渲染,当我调整窗口大小时,渲染会发生变化:

编辑:出于某种原因,将XAML更改为包含RenderOptions.EdgeMode="Aliased"修复了我的渲染:

<Viewport3D Name="viewport3D" RenderOptions.EdgeMode="Aliased" />

相关问题