none
Loading x files into directx ( a conversion between C# and VB) RRS feed

  • Question

  • Hi all,

    I want to create a Mesh in VB.Net via directx. I've seen different C# code but I wasn't successful to translate to VB.net.

    I will be thankful if you can help me.

    private Material[] meshMaterials;
    private Texture[] meshTextures;
    
    private void LoadMesh(string file)
    {
        ExtendedMaterial[] mtrl;
    
        // Load our mesh
        mesh = Mesh.FromFile(file, MeshFlags.Managed, device, out mtrl);
    
        // If we have any materials, store them
        if ((mtrl != null) && (mtrl.Length > 0))
        {
            meshMaterials = new Material[mtrl.Length];
            meshTextures = new Texture[mtrl.Length];
    
            // Store each material and texture
            for (int i = 0; i < mtrl.Length; i++)
            {
                meshMaterials[i] = mtrl[i].Material3D;
                if ((mtrl[i].TextureFilename != null) && (mtrl[i].TextureFilename !=
                    string.Empty))
                {
                    // We have a texture, try to load it
                    meshTextures[i] = TextureLoader.FromFile(device, @"..\..\" +
                        mtrl[i].TextureFilename);
                }
            }
        }
    }

    My translation:
        Private meshMaterials() As Material
        Private meshTextures() As Texture
        Private Sub LoadMesh(ByVal file As String)
            Dim mtrl() As ExtendedMaterial
            Dim i As Integer
    
            MeshBuffer = Mesh.FromFile(file, MeshFlags.Managed, Device, , XXX) 'What should I put instead of xxx
    
    
            If (mtrl.Length > 0) Then
    
                meshMaterials = New Material(mtrl.Length) ' Error'
                meshTextures = New Texture(mtrl.Length) ' Error'
    
                For i = 0 To i < mtrl.Length
                    meshMaterials(i) = mtrl(i).Material3D
                    If ((mtrl(i).TextureFilename <> vbEmpty) And (mtrl(i).TextureFilename <> vbEmpty)) Then
    
                    meshTextures(i) = TextureLoader.FromFile(device, @"..\..\" + mtrl[i].TextureFilename);
    
                    End If
                Next
    
            End If
        End Sub

    • Edited by Parisa_1 Tuesday, April 3, 2018 8:12 AM
    Tuesday, April 3, 2018 8:08 AM

Answers

  • Pari,

    You cant just tear out bits and pieces from the examples as there are many parameters that must be changed and or maintained. You need to keep the entire example in one project until you learn what the things are.

    Here is a working vb.net example of the tutor 6 from the sdk. You need a mesh file .x and need to set the path. This uses "tiger.x" and is the tutor6 example from the sdk in vb.net. You must set up the project the way I showed in the other example ie .net 3.5, x86, add the visual c ref, disable loader lock etc as described in the last example.

    You probably need to put the project in the sdk folder with the c++ example folders so it finds the files for textures and etc. I am not sure. That is where I run this example and it works. You will need to track those things down. The example shows the tiger rotating.

    https://msdn.microsoft.com/en-us/library/windows/desktop/bb153263%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

    '-----------------------------------------------------------------------------
    ' File: Meshes.vb
    '
    ' Desc: For advanced geometry, most apps will prefer to load pre-authored
    '       meshes from a file. Fortunately, when using meshes, D3DX does most of
    '       the work for this, parsing a geometry file and creating vertx buffers
    '       (and index buffers) for us. This tutorial shows how to use a D3DXMESH
    '       object, including loading it from a file and rendering it. One thing
    '       D3DX does not handle for us is the materials and textures for a mesh,
    '       so note that we have to handle those manually.
    '
    '       Note: one advanced (but nice) feature that we don't show here is that
    '       when cloning a mesh we can specify the FVF. So, regardless of how the
    '       mesh was authored, we can add/remove normals, add more texture
    '       coordinate sets (for multi-texturing), etc.
    '
    ' Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
    '-----------------------------------------------------------------------------
    Imports System
    Imports System.Drawing
    Imports System.ComponentModel
    Imports System.Windows.Forms
    Imports System.IO
    Imports Microsoft.DirectX
    Imports Microsoft.DirectX.Direct3D
    Imports Direct3D = Microsoft.DirectX.Direct3D
    
    Namespace MeshesTutorial
        Public Class Meshes
            Inherits Form
    
            Private device As device = Nothing ' Our rendering device
            Private mesh As mesh = Nothing ' Our mesh object in sysmem
            Private meshMaterials() As Direct3D.Material ' Materials for our mesh
            Private meshTextures() As Texture ' Textures for our mesh
            Private presentParams As New PresentParameters()
            Private pause As Boolean = False
    
    
            Public Sub New()
                ' Set the initial size of our form
                Me.ClientSize = New System.Drawing.Size(400, 300)
                ' And it's caption
                Me.Text = "Direct3D Tutorial 6 - Meshes"
            End Sub 'New
    
    
            Function InitializeGraphics() As Boolean
                ' Get the current desktop display mode, so we can set up a back
                ' buffer of the same format
                Try
                    ' Set up the structure used to create the D3DDevice. Since we are now
                    ' using more complex geometry, we will create a device with a zbuffer.
                    presentParams.Windowed = True
                    presentParams.SwapEffect = SwapEffect.Discard
                    presentParams.EnableAutoDepthStencil = True
                    presentParams.AutoDepthStencilFormat = DepthFormat.D16
    
                    ' Create the D3DDevice
                    device = New Device(0, DeviceType.Hardware, Me, CreateFlags.SoftwareVertexProcessing, presentParams)
                    AddHandler device.DeviceReset, AddressOf Me.OnResetDevice
                    Me.OnResetDevice(device, Nothing)
                    pause = False
                Catch e As DirectXException
                    Return False
                End Try
                Return True
            End Function 'InitializeGraphics
    
            Public Sub OnResetDevice(ByVal sender As Object, ByVal e As EventArgs)
                Dim materials As ExtendedMaterial() = Nothing
    
                ' Set the directory up two to load the right data (since the default build location is bin\debug or bin\release
                Directory.SetCurrentDirectory((Application.StartupPath + "\..\"))
                Dim dev As Device = CType(sender, Device)
                ' Turn on the zbuffer
                dev.RenderState.ZBufferEnable = True
    
                ' Turn on ambient lighting 
                dev.RenderState.Ambient = System.Drawing.Color.White
                ' Load the mesh from the specified file
                mesh = mesh.FromFile("tiger.x", MeshFlags.SystemMemory, device, materials)
    
    
                If meshTextures Is Nothing Then
                    ' We need to extract the material properties and texture names 
                    meshTextures = New Texture(materials.Length) {}
                    meshMaterials = New Direct3D.Material(materials.Length) {}
                    Dim i As Integer
                    For i = 0 To materials.Length - 1
                        meshMaterials(i) = materials(i).Material3D
                        ' Set the ambient color for the material (D3DX does not do this)
                        meshMaterials(i).Ambient = meshMaterials(i).Diffuse
    
                        ' Create the texture
                        meshTextures(i) = TextureLoader.FromFile(dev, materials(i).TextureFilename)
                    Next i
                End If
            End Sub 'OnResetDevice
    
            Sub SetupMatrices()
                ' For our world matrix, we will just leave it as the identity
                device.Transform.World = Matrix.RotationY((Environment.TickCount / 1000.0F))
    
                ' Set up our view matrix. A view matrix can be defined given an eye point,
                ' a point to lookat, and a direction for which way is up. Here, we set the
                ' eye five units back along the z-axis and up three units, look at the 
                ' origin, and define "up" to be in the y-direction.
                device.Transform.View = Matrix.LookAtLH(New Vector3(0.0F, 3.0F, -5.0F), New Vector3(0.0F, 0.0F, 0.0F), New Vector3(0.0F, 1.0F, 0.0F))
    
                ' For the projection matrix, we set up a perspective transform (which
                ' transforms geometry from 3D view space to 2D viewport space, with
                ' a perspective divide making objects smaller in the distance). To build
                ' a perpsective transform, we need the field of view (1/4 pi is common),
                ' the aspect ratio, and the near and far clipping planes (which define at
                ' what distances geometry should be no longer be rendered).
                device.Transform.Projection = Matrix.PerspectiveFovLH(CSng(Math.PI / 4), 1.0F, 1.0F, 100.0F)
            End Sub 'SetupMatrices
    
            Private Sub Render()
                If device Is Nothing Then
                    Return
                End If
                If pause Then
                    Return
                End If
                'Clear the backbuffer to a blue color 
                device.Clear(ClearFlags.Target Or ClearFlags.ZBuffer, System.Drawing.Color.Blue, 1.0F, 0)
                'Begin the scene
                device.BeginScene()
                ' Setup the world, view, and projection matrices
                SetupMatrices()
    
                ' Meshes are divided into subsets, one for each material. Render them in
                ' a loop
                Dim i As Integer
                For i = 0 To meshMaterials.Length - 1
                    ' Set the material and texture for this subset
                    device.Material = meshMaterials(i)
                    device.SetTexture(0, meshTextures(i))
    
                    ' Draw the mesh subset
                    mesh.DrawSubset(i)
                Next i
    
                'End the scene
                device.EndScene()
                device.Present()
            End Sub 'Render
    
    
            Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
                Me.Render() ' Render on painting
            End Sub 'OnPaint
    
            Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
                If Asc(e.KeyChar) = CInt(System.Windows.Forms.Keys.Escape) Then
                    Me.Dispose() ' Esc was pressed
                End If
            End Sub 'OnKeyPress
    
            Protected Overrides Sub OnResize(ByVal e As System.EventArgs)
                pause = (Me.WindowState = FormWindowState.Minimized Or Not Me.Visible)
            End Sub 'OnResize
    
            '/ <summary>
            '/ The main entry point for the application.
            '/ </summary>
            Shared Sub Main()
                Dim frm As New Meshes()
                If Not frm.InitializeGraphics() Then ' Initialize Direct3D
                    MessageBox.Show("Could not initialize Direct3D.  This tutorial will exit.")
                    Return
                End If
                frm.Show()
    
                While frm.Created
                    frm.Render()
                    Application.DoEvents()
                End While
            End Sub 'Main
    
            Private Sub InitializeComponent()
                '
                'Meshes
                '
                Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
                Me.ClientSize = New System.Drawing.Size(292, 266)
                Me.Name = "Meshes"
    
            End Sub
    
            Private Sub Meshes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            End Sub
        End Class 'Meshes
    End Namespace 'MeshesTutorial


    • Edited by tommytwotrain Tuesday, April 3, 2018 1:46 PM
    • Marked as answer by Parisa_1 Tuesday, April 10, 2018 6:22 PM
    Tuesday, April 3, 2018 1:45 PM

All replies

  • Mesh.FromFile(file, MeshFlags.Managed, device, mtrl)


    Success
    Cor

    Tuesday, April 3, 2018 8:22 AM
  • Thanks Cor Ligthert for your response. it removed the first error. but it shows me this warning:

    Warning	1	Variable 'mtrl' is passed by reference before it has been
    assigned a value. A null reference exception could result at runtime.

    Do you mind if you help me with these two errors?

                meshMaterials = New Material(mtrl.Length) ' Error'
                meshTextures = New Texture(mtrl.Length) ' Error'

    Error    1    Too many arguments to 'Public Sub New()'.  

    and

    Error    2    Value of type 'Microsoft.DirectX.Direct3D.Texture' cannot be converted to '1-dimensional array of Microsoft.DirectX.Direct3D.Texture'. 
    as you see the first function meshTextures should be an array not a usual variable



    • Edited by Parisa_1 Tuesday, April 3, 2018 10:41 AM
    Tuesday, April 3, 2018 8:59 AM
  • The warning you can forget, that is because the C# programmers who made the designer think it has the same problems as C#.

    However, are you 100% sure the C# programs is 100% correct, there are on Internet many pieces of code trying to convert DirectX11 to C# which simply fail. 

    Better ask here what you want to do. You get no help from me, but there are here who know a lot of DirectX. 


    Success
    Cor

    Tuesday, April 3, 2018 12:28 PM
  • Pari,

    You cant just tear out bits and pieces from the examples as there are many parameters that must be changed and or maintained. You need to keep the entire example in one project until you learn what the things are.

    Here is a working vb.net example of the tutor 6 from the sdk. You need a mesh file .x and need to set the path. This uses "tiger.x" and is the tutor6 example from the sdk in vb.net. You must set up the project the way I showed in the other example ie .net 3.5, x86, add the visual c ref, disable loader lock etc as described in the last example.

    You probably need to put the project in the sdk folder with the c++ example folders so it finds the files for textures and etc. I am not sure. That is where I run this example and it works. You will need to track those things down. The example shows the tiger rotating.

    https://msdn.microsoft.com/en-us/library/windows/desktop/bb153263%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

    '-----------------------------------------------------------------------------
    ' File: Meshes.vb
    '
    ' Desc: For advanced geometry, most apps will prefer to load pre-authored
    '       meshes from a file. Fortunately, when using meshes, D3DX does most of
    '       the work for this, parsing a geometry file and creating vertx buffers
    '       (and index buffers) for us. This tutorial shows how to use a D3DXMESH
    '       object, including loading it from a file and rendering it. One thing
    '       D3DX does not handle for us is the materials and textures for a mesh,
    '       so note that we have to handle those manually.
    '
    '       Note: one advanced (but nice) feature that we don't show here is that
    '       when cloning a mesh we can specify the FVF. So, regardless of how the
    '       mesh was authored, we can add/remove normals, add more texture
    '       coordinate sets (for multi-texturing), etc.
    '
    ' Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
    '-----------------------------------------------------------------------------
    Imports System
    Imports System.Drawing
    Imports System.ComponentModel
    Imports System.Windows.Forms
    Imports System.IO
    Imports Microsoft.DirectX
    Imports Microsoft.DirectX.Direct3D
    Imports Direct3D = Microsoft.DirectX.Direct3D
    
    Namespace MeshesTutorial
        Public Class Meshes
            Inherits Form
    
            Private device As device = Nothing ' Our rendering device
            Private mesh As mesh = Nothing ' Our mesh object in sysmem
            Private meshMaterials() As Direct3D.Material ' Materials for our mesh
            Private meshTextures() As Texture ' Textures for our mesh
            Private presentParams As New PresentParameters()
            Private pause As Boolean = False
    
    
            Public Sub New()
                ' Set the initial size of our form
                Me.ClientSize = New System.Drawing.Size(400, 300)
                ' And it's caption
                Me.Text = "Direct3D Tutorial 6 - Meshes"
            End Sub 'New
    
    
            Function InitializeGraphics() As Boolean
                ' Get the current desktop display mode, so we can set up a back
                ' buffer of the same format
                Try
                    ' Set up the structure used to create the D3DDevice. Since we are now
                    ' using more complex geometry, we will create a device with a zbuffer.
                    presentParams.Windowed = True
                    presentParams.SwapEffect = SwapEffect.Discard
                    presentParams.EnableAutoDepthStencil = True
                    presentParams.AutoDepthStencilFormat = DepthFormat.D16
    
                    ' Create the D3DDevice
                    device = New Device(0, DeviceType.Hardware, Me, CreateFlags.SoftwareVertexProcessing, presentParams)
                    AddHandler device.DeviceReset, AddressOf Me.OnResetDevice
                    Me.OnResetDevice(device, Nothing)
                    pause = False
                Catch e As DirectXException
                    Return False
                End Try
                Return True
            End Function 'InitializeGraphics
    
            Public Sub OnResetDevice(ByVal sender As Object, ByVal e As EventArgs)
                Dim materials As ExtendedMaterial() = Nothing
    
                ' Set the directory up two to load the right data (since the default build location is bin\debug or bin\release
                Directory.SetCurrentDirectory((Application.StartupPath + "\..\"))
                Dim dev As Device = CType(sender, Device)
                ' Turn on the zbuffer
                dev.RenderState.ZBufferEnable = True
    
                ' Turn on ambient lighting 
                dev.RenderState.Ambient = System.Drawing.Color.White
                ' Load the mesh from the specified file
                mesh = mesh.FromFile("tiger.x", MeshFlags.SystemMemory, device, materials)
    
    
                If meshTextures Is Nothing Then
                    ' We need to extract the material properties and texture names 
                    meshTextures = New Texture(materials.Length) {}
                    meshMaterials = New Direct3D.Material(materials.Length) {}
                    Dim i As Integer
                    For i = 0 To materials.Length - 1
                        meshMaterials(i) = materials(i).Material3D
                        ' Set the ambient color for the material (D3DX does not do this)
                        meshMaterials(i).Ambient = meshMaterials(i).Diffuse
    
                        ' Create the texture
                        meshTextures(i) = TextureLoader.FromFile(dev, materials(i).TextureFilename)
                    Next i
                End If
            End Sub 'OnResetDevice
    
            Sub SetupMatrices()
                ' For our world matrix, we will just leave it as the identity
                device.Transform.World = Matrix.RotationY((Environment.TickCount / 1000.0F))
    
                ' Set up our view matrix. A view matrix can be defined given an eye point,
                ' a point to lookat, and a direction for which way is up. Here, we set the
                ' eye five units back along the z-axis and up three units, look at the 
                ' origin, and define "up" to be in the y-direction.
                device.Transform.View = Matrix.LookAtLH(New Vector3(0.0F, 3.0F, -5.0F), New Vector3(0.0F, 0.0F, 0.0F), New Vector3(0.0F, 1.0F, 0.0F))
    
                ' For the projection matrix, we set up a perspective transform (which
                ' transforms geometry from 3D view space to 2D viewport space, with
                ' a perspective divide making objects smaller in the distance). To build
                ' a perpsective transform, we need the field of view (1/4 pi is common),
                ' the aspect ratio, and the near and far clipping planes (which define at
                ' what distances geometry should be no longer be rendered).
                device.Transform.Projection = Matrix.PerspectiveFovLH(CSng(Math.PI / 4), 1.0F, 1.0F, 100.0F)
            End Sub 'SetupMatrices
    
            Private Sub Render()
                If device Is Nothing Then
                    Return
                End If
                If pause Then
                    Return
                End If
                'Clear the backbuffer to a blue color 
                device.Clear(ClearFlags.Target Or ClearFlags.ZBuffer, System.Drawing.Color.Blue, 1.0F, 0)
                'Begin the scene
                device.BeginScene()
                ' Setup the world, view, and projection matrices
                SetupMatrices()
    
                ' Meshes are divided into subsets, one for each material. Render them in
                ' a loop
                Dim i As Integer
                For i = 0 To meshMaterials.Length - 1
                    ' Set the material and texture for this subset
                    device.Material = meshMaterials(i)
                    device.SetTexture(0, meshTextures(i))
    
                    ' Draw the mesh subset
                    mesh.DrawSubset(i)
                Next i
    
                'End the scene
                device.EndScene()
                device.Present()
            End Sub 'Render
    
    
            Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
                Me.Render() ' Render on painting
            End Sub 'OnPaint
    
            Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
                If Asc(e.KeyChar) = CInt(System.Windows.Forms.Keys.Escape) Then
                    Me.Dispose() ' Esc was pressed
                End If
            End Sub 'OnKeyPress
    
            Protected Overrides Sub OnResize(ByVal e As System.EventArgs)
                pause = (Me.WindowState = FormWindowState.Minimized Or Not Me.Visible)
            End Sub 'OnResize
    
            '/ <summary>
            '/ The main entry point for the application.
            '/ </summary>
            Shared Sub Main()
                Dim frm As New Meshes()
                If Not frm.InitializeGraphics() Then ' Initialize Direct3D
                    MessageBox.Show("Could not initialize Direct3D.  This tutorial will exit.")
                    Return
                End If
                frm.Show()
    
                While frm.Created
                    frm.Render()
                    Application.DoEvents()
                End While
            End Sub 'Main
    
            Private Sub InitializeComponent()
                '
                'Meshes
                '
                Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
                Me.ClientSize = New System.Drawing.Size(292, 266)
                Me.Name = "Meshes"
    
            End Sub
    
            Private Sub Meshes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            End Sub
        End Class 'Meshes
    End Namespace 'MeshesTutorial


    • Edited by tommytwotrain Tuesday, April 3, 2018 1:46 PM
    • Marked as answer by Parisa_1 Tuesday, April 10, 2018 6:22 PM
    Tuesday, April 3, 2018 1:45 PM
  • PS The Directx 9c VB.NET tutorial projects are available here for a limited time only:

    http://sandiasoftware.com/beta/test.htm

    Download the zip file and extract it in your mydocs folder. Go to the tutorial6 and open the .sln and run with vs 2010 or above. That is the example above that I just made and it works.

    Notice all the textures and mesh files in the \obj\debug folder. You must have those.

    Tuesday, April 3, 2018 2:20 PM
  • PS The Directx 9c VB.NET tutorial projects are available here for a limited time only:

    http://sandiasoftware.com/beta/test.htm

    Download the zip file and extract it in your mydocs folder. Go to the tutorial6 and open the .sln and run with vs 2010 or above. That is the example above that I just made and it works.

    Notice all the textures and mesh files in the \obj\debug folder. You must have those.

    Tommy,

    When I saw that Lion I knew I had done that before. However, I could never find the samples anymore.


    Thanks
    Cor


    Tuesday, April 3, 2018 2:58 PM
  • Tommy,

    When I saw that Lion I knew I had done that before. However, I could never find the samples anymore.


    Thanks
    Cor


    Yeah the tiger is second oldest to the teapot.

    The teapot is the famous shape for 3d as it has inside and outside to deal with.

    The samples in the current 9c sdk are now only c++ it appears.

    I have these vb.net versions from an old computer that still has the old dx 9 sdk from 2006. However the old 2006 vb.net samples require some mods to run on vs2010 and up and win7 and up depending what they use and etc.



    Tuesday, April 3, 2018 3:21 PM
  • "Loading x files into directx ( a conversion between C# and VB)"

    The xfiles are on channel 50 here I believe. I like the xfiles!


    La vida loca

    Wednesday, April 4, 2018 1:52 AM
  • I really appreciate your help tommytwotrian

    I run the code and it works perfectly. However, by changing the x file in this line

      mesh = mesh.FromFile("g:\tiny.x", MeshFlags.SystemMemory, device, materials)

    by one of SDK examples x file it doesn't work(in addition each time I should clean the project completely and rebuild all of them).

    in last SDK the tiny x file is available in this path:

    C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Samples\Media\Tiny

    what is my mistake?

    Thursday, April 5, 2018 12:46 PM
  • I really appreciate your help tommytwotrian

    I run the code and it works perfectly. However, by changing the x file in this line

      mesh = mesh.FromFile("g:\tiny.x", MeshFlags.SystemMemory, device, materials)

    by one of SDK examples x file it doesn't work(in addition each time I should clean the project completely and rebuild all of them).

    in last SDK the tiny x file is available in this path:

    C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Samples\Media\Tiny

    what is my mistake?

    I think you need to try a bit harder.

    You show code with the path 

       "g:\tiny.x"

    and then you show us the file tiny.x is at: 

        C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Samples\Media\Tiny

    and ask us what the problem is??

    Do you get an error message? What does it say?

    And the code needs to find any texture files as well. Perhaps you need to put the files in a folder where the app can find them as I mentioned previously. Perhaps the code has more references to the materials and etc. Where are the tiger.x files that are working and are any of them materials or texture files?

    Finally do you know what tiny.x is? You might need to change the view size parameters to see it.

    Thursday, April 5, 2018 2:59 PM
  • Dear tommytwotrian for your cooperation. it works fine.
    Tuesday, April 10, 2018 6:22 PM