Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Go Back  Xtreme Visual Basic Talk > > > Exploring 3D graphics with VB.Net, but without using DirectX or XNA


Reply
 
Thread Tools Display Modes
  #1  
Old 10-19-2014, 07:10 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Exploring 3D graphics with VB.Net, but without using DirectX or XNA


This thread could be just a "Technical Discussions" thread with so broad a thread title, but I'm hoping to explore (and get help with) several code samples designed to produce (or simulate) 3D objects/models using VB.Net.
This will hopefully be more of a practical (rather than a theoretical) thread.


My last Managed DirectX thread ended up with me giving up on DirectX and just attaching some working code showing how to do OpenGL without relying on third party .dlls (or binaries compiled in another language).

Unfortunately even knowing you can do OpenGL rendering in VB.Net doesn't necessary mean you can used VB.Net with OpenGL to render a textured 3D primitive (I'm still working on that).


And (thinking ahead) what about loading complex animated 3D models in VB.Net..or whole environments (like Quake levels) using VB.Net code that handle 3D collisioning between moving 3D models and the 3D environment that contains them in a typical 3D RPG game?
But that's definitely getting way too far ahead..


At this point I would (humbly) start by trying to find/present a way to make static (but semi-sophisticated) 3D statistical charts/graphs.


Just try searching for hours through MSDN for hours/days/weeks (I have) for a way to make a curvy 3D plane graphs out of a multivariate scatter plots and you'll only find 3D chart examples like 3D exploded pies and 3D bar graphs.
I hope you can understand my frustration every time I see this line:
Code:
Imports System.Drawing.Drawing2D
..then think why isn't there also a "System.Drawing.Drawing3D" namespace?

Towards that end, I've attached below a working sample of 3D wireframe modelling/graphing (with uses simple fills of multi-color gradients).
However, such uncommon GDI+ extending-into-3D code sub/functions as there are inside this sample are (unfortunately) only a starting point.

I urge anyone who downloads it to play around.
On the main form1 you'll see this code:
Code:
    Private Sub ToolStripComboMiscObj_SelectedIndexChanged(ByVal sender As Object,
                                                       ByVal e As System.EventArgs) Handles ToolStripComboMiscObj.SelectedIndexChanged
        Select Case ToolStripComboMiscObj.SelectedIndex
            'Handles the combining of 3D models
            Case 0 'Sphere and triangle tube 
                Dim graph1 As New CylindricalFunction
                Dim o1, o2 As Object3D
                o1 = graph1.getObject3D(18, 300, 300)
                o2 = graph1.getObject3D(8, 300, 300)
                Canvas.object1 = AddObject3D(o1, o2)
                Canvas.object1.drawMode = ToolStripComboDrawmode.SelectedIndex
                graph1 = Nothing
                Canvas.Invalidate()
            Case 1 'Intersecting rings
                Dim graph1 As New CylindricalFunction
                Dim o1, o2 As Object3D
                o1 = graph1.getObject3D(17, 300, 300)
                o2 = graph1.getObject3D(17, 300, 300)
                Dim m As Matrix4x4
                m = Matrix4x4.matrixTranslate3D(70, 0, 0)
                o2.Rotate(0, 90)
                o2.transform(m)
                Canvas.object1 = AddObject3D(o1, o2)
                Canvas.object1.drawMode = ToolStripComboDrawmode.SelectedIndex
                graph1 = Nothing
                Canvas.Invalidate()
        End Select
    End Sub
After you run the demo, click the down arrow next to "Demo Objects" and you see four nested drop downs inside.
Click the down arrow next to "Select Object" under "Misc Objects" and you see two model combos of different 3D models joined together.

Try substituting these alternate lines for o1 and o2 in case 0 and see what different results you get:
Code:
o1 = graph1.getObject3D(17, 300, 300)
o2 = graph1.getObject3D(8, 140, 140)
or
Code:
o1 = graph1.getObject3D(17, 300, 300)
o2 = graph1.getObject3D(18, 180, 180)
The first parameter represents the "model type" (from 0-18 of course).
The second set of parameters is for X,Y scaling.

Even though this code is pretty unique (and fun to play around with),
if you really want to do honest-to-goodness 3D modeling it's all about the textures (and 3D "uv type" texture-wrapping),
but I'll have a little bit more on that topic in the next post.
Attached Images
File Type: jpg 3D-torus_around_intersecting_trishape_screenshot.jpg (33.3 KB, 53 views)
File Type: jpg 3D-torus_around_sphere_screenshot.jpg (32.1 KB, 42 views)
Attached Files
File Type: zip 3D Project VB.net_update_9d.zip (1.85 MB, 110 views)
Reply With Quote
  #2  
Old 10-20-2014, 05:03 AM
PlausiblyDamp's Avatar
PlausiblyDampExploring 3D graphics with VB.Net, but without using DirectX or XNA PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,052
Default

If you are using .Net and need to be doing 3d graphics it might be worth looking at WPF instead of Windows Forms as there is a lot of support for 3D graphics built in.
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags
Reply With Quote
  #3  
Old 10-22-2014, 06:05 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Continuing on with 3D texture wrapping..can't get 4 pt quadrilateral distortion in VB

Hi PlausiblyDamp!
Thanks for posting to my humble thread.

You are right that WPF (Windows Presentation Foundation) can do 3D (including texture wrapping), but I've heard all these rumors about WPF dying off for some time now..

Even when it was in its "heyday" there was still more C# WPF code than VB.Net WPF open source code.

It looks like there is source code for a "Farseer" WPF 3D physics engine, but its in C#:
http://farseerphysics.codeplex.com/


I did find this Rod Stephens article though (that shows a VB.Net WPF project featuring a 3D model loading inside a 3D maze):
http://www.devx.com/dotnet/Article/42450/0/page/2

In another of Rod Stephens WPF articles, though, about 3D robot model rotation using WPF, it says:
Quote:
Unlike the RobotArm program, this example builds its robot out of spheres and cylinders. All together, those shapes contain thousands of triangles, so building the whole thing in XAML code is impractical..
I don't understand why this is...but maybe because I haven't worked with XAML all that much --maybe there is some kind of performance penalty?


Anyway I've only begun to skim the surface of Quaternion and Euler rotation (with or without transformational matrices).

The kind of math I see for using quaternions in regard to spacial rotations is pretty daunting.



At this point I am still trying to get 4 point texture distortion to work in VB.Net.

This is basically an extension of what passel was trying to do in adapting DrawImage from three point to four point distortion in this old XVBT Image Warping thread:
Image warping using custom per pixel interpolation - needs performance tuning



So I tried translating the C# source code for this CodeProject "Quadrilateral Distortion" article:
http://www.codeproject.com/Articles/...ral-Distortion

The version 2 bilinear interpolation (lerping) looked very promising and worked well (see screenshots below) but I couldn't get the four point distortion to work in my VB.Net translation.
I'll attach the non-working project below (I patched in some three point DrawImage code just so something would show up on the screen but it's not drag-distortable).


The error it gives me when I uncomment out the DrawImageUnscaled line in the form Paint event is:
Quote:
Value of type 'FourPointDrawImage.FastBitmap' cannot be converted to 'System.Drawing.Image'
However I see that the "oOut" object (at a breakpoint in the Form Paint event looks similar in VB.Net versus C#, see screenshot below) so it's probably just some kind of simple casting error (I'm hoping).


What I was thinking --if I could "shape" a texture into a distorted quadrilateral (with a series of drag boxes to establish the corner points),
then three of these textures could be aligned together to form the perspective mapped sides of a textured cube.


This wouldn't give me the ability to rotated the textured cube in 3D space, but it would be a step forward.

Just in case no one knows how to fix the error, I'll also keep working on converting the other C# 3D project I found into VB.Net code.
Attached Images
File Type: jpg working_code_oOut_breakpoint_intellisense_output.JPG (110.3 KB, 30 views)
File Type: jpg 4_Point_Distort_code_working_screenshot.JPG (33.6 KB, 28 views)
Attached Files
File Type: zip FourPointDistort.zip (1.19 MB, 49 views)
Reply With Quote
  #4  
Old 10-22-2014, 06:09 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default A working texturedcube w/ 3D rotation!(Pure VB.net, No WPF, XNA, DirectX, or OpenGL)

I had to re-create and refactor the project 17 times but it's working! (in VB.Net 2010)

See source code and screenshot below.

Maybe one day someone could explain some of the quaternion/matrix transforms math behind all my code wrestling.
Hopefully it doesn't gimbal lock at some point.
Please let me know if it does.
(I'll try to work on a animation button later).

I don't have a clue how (or if) this code could be combined with the working code in post #1 of this thread, though..
Attached Images
File Type: jpg cube_texturing_with_quarternion_rotation_screenshot.JPG (49.6 KB, 39 views)
Attached Files
File Type: zip QuaternionDrawing17b.zip (65.8 KB, 56 views)

Last edited by passel; 10-23-2014 at 01:40 PM. Reason: Removed execuables (removed bin and obj directories) from zip
Reply With Quote
  #5  
Old 10-23-2014, 01:44 PM
passel's Avatar
passelExploring 3D graphics with VB.Net, but without using DirectX or XNA passel is offline
Sinecure Expert

Super Moderator
* Guru *
 
Join Date: Jun 2003
Location: Upstate New York, usa
Posts: 8,011
Default

Remember to remove executables from attached files. I've removed the obj and bin directories in the attachment for you.
If I have time I'll try to look at the code. Have to take a business related trip next week, and trying to wrap stuff up this week before I head out of town.
__________________
There Is An Island Of Opportunity In The Middle of Every Difficulty.
Miss That, Though, And You're Pretty Much Doomed.
Reply With Quote
  #6  
Old 10-25-2014, 05:45 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default passel joins the thread!

Quote:
Originally Posted by passel
Remember to remove executables from attached files. I've removed the obj and bin directories in the attachment for you.
Hi passel,
I was hoping you would see this thread eventually and thanks for clearing the compiled binaries --guess
I was just too eager/rushed in posting (and forgot to do a little cleaning, sorry )

Quote:
Originally Posted by passel
If I have time I'll try to look at the code.
I would appreciate any insights you have to offer.


I mentioned the OpenGL Tao Framework (and the related xvbt forum attachments that use this framework) way back in this post.

Since none of the existing martonx attachment use textures I've been searching far and wide over the internet
for some working Tao Framework VB.Net code that actually use 3D textures.

The Tao Framework eventually evolved into something called "OpenTk" so
so the Tao Framework wasn't very popular for very long;
thus not that many examples which show this way of working with OpenGL in VB.Net.


However, I did find one promising page:
pauldahuach's VB.Net Tao Framework examples:
http://www.pauldahuach.com.ar/program_en.htm

Many of that page's downloads (when run inside the .Net IDE) gave the same error though:
Quote:
BadImageFormat was unhandled
If you're like me you are scratching your head?


Eventually I found the MSDN page for the "BadImageFormatException Class":
http://msdn.microsoft.com/en-US/libr...vs.110%29.aspx

...where its says:
Quote:
The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.
Great!
But why is it invalid??????

I didn't write the dll(s) used by the Tao Framework so how would I know?


After digging around a bit more (those pauldahuach page screenshots are sure nice looking..),
I found this "Troubleshooting Exceptions: System.BadImageFormatException" (for VB.Net 2005) page,
which suggested:
Quote:
Reflecting on C++ executable files may throw this exception.
This is most likely caused by the C++ compiler stripping the relocation addresses or the .Reloc section from the executable file.
To preserve the .relocation address in a C++ executable file, specify /fixed:no when linking.
Of course I'm not coding in C++ so this official "remark" in the MSDN troubleshooting docs was not helpful.
Thank goodness for comments on MSDN pages from community members, though.

If you scroll down the page to the bottom of that same page,
someone named "chaiguy1337" actually posted something meaningful/useful:
Quote:
This exception can occur when a .NET application running on a 64-bit platform attempts to load a DLL that does not support native 64-bit execution.
If the application is built in platform-agnostic (i.e. "Any CPU") mode, it will launch in 64-bit mode on the host operating system, leading to this problem.

To fix this, you can force the application to run in 32-bit mode by compiling for x86 architecture explicitly,
forcing the program to launch in WoW64 mode on the 64-bit system,
and allowing the 32-bit DLL to be accessed.
So..the plot thickens!
But come on chaiguy1337, just tell me exactly what button(s) to push to fix the problem!

After a little "mosey-ing around" in the innards (guts) of the project I eventually found the .Net setting that actually allows the samples to run:
Quote:
First go to the Project menu and select "Properties"
Then on the left select the "Compile" tab
From there scroll down and press the "Advance Compiler Options" button
Another dialog box pops up with a "Target CPU" dropdown
It will probably say "Any CPU"
Click on the drop down arrow and select "x86"
Run and build the project and this time the "BadImageFormat was unhandled" error is gone,
and you'll see some sweet OpenGL rendering with textures and shadows.
This fix works on all of the following pauldahuach page (linked to above) zipped project downloads:
vb.net OpenGL Texture Coord Array
vb.net OpenGL Multiple Passes
vb.net OpenGL MultiTexture
vb.net OpenGL Dot3 BumpMap
vb.net OpenGL Normal Map + Gloss Map
vb.net Cg Shadow Volumes (z-Fail Shadows)
vb.net ShadowMaps

The rest of the Paul's VB.Net samples still don't work for me (even with this adjustment).


However, this is better than most of the advanced NeHe's famous OpenGL code lessons
(like lesson06: "Texture Filters, Lighting & Keyboard Control"),
where there is no working VB.Net code.


In Re: Shadow Volumes
They are also referred to as "stencil shadows" in John Carmack's famous email:
http://fabiensanglard.net/doom3_docu...dowVolumes.txt

This GameDev.Net Cg shading page also mentions:
Quote:
..the shadow volume algorithm called the "Z-Fail" algorithm ([is] known as "Carmack's Reverse")
Now you know..

Last edited by dotnetwrassler; 10-25-2014 at 06:08 PM.
Reply With Quote
  #7  
Old 10-26-2014, 06:33 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default oOut issue for FourPointDistort solved!

I kept massaging and refactoring the code attached to post #3 of this thread (FourPointDistort.zip) and nothing was working.


So I figured the best bet was to try and recreate the project from scratch and import the converted C# code in pieces.

But what kept happening was that the Form1.Designer file would start to show errors (become corrupted essentially) when I imported the three converted .vb files into the project.


So then I started recreating the modules (FastBitmap.vb, QuadDistort.vb and RGBColor.vb) manually by copying and pasting the code in pieces.
It was only then that I finally found what was corrupting the Form1.Designer file --Namespaces.

The C# to VB.Net conversion had wrapped the classes in the three modules with:
Code:
Namespace System.Drawing
...
End Namespace
It was so simple...and so stupid.

Once I stripped these namespace lines out of the converted vb class modules the form.designer stopped being corrupted (having errors pop-up).

Then "oOut" worked, but there was still a lot of flickering.

There was some converted C# code that VB.Net didn't like (which I had commented out to get things to run):
Code:
Public Sub New()
  Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
  Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
End Sub

Since the VS.Net IDE didn't seem to like the "Sub New" part I dumped the lines instead into:
Code:
Protected Overrides Sub OnLoad(e As EventArgs)
   MyBase.OnLoad(e)
   Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
   Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
   LoadImage("..\..\SS.png")
   Me.ClientSize = New Size(oTexture.Width + 80, oTexture.Height + 80)
End Sub
This eliminated the flickering, but made the refresh after the drag too slow.

Hmmmmmm..what to do?

Well, the standard approach to reducing flickering when drawing directly to a form (not on a control) is to set the form's DoubleBuffering to True.

So I commented out the two lines I had pasted in the OnLoad event and set the form's DoubleBuffering to True just to see what would happen.

This did have a noticeable effect in speeding up the redraws after dragging the green rect (representing the distortion point for the lower right corner of the image).

It was still slow, though -- but then I was running the code on an old computer.
Your results may very.
I'll attach the working project below.

The screenshot for this now-working VB.Net app is basically the same as that in post #3 of this thread for the working C# application (so I consider the language conversion part done).

Oh..and hopefully everyone had a chance to read through the original CodeProject article.

It references this ryoushin article for the original algorithm.

I prefer the article's visual explanation better, so I made a combined png to show what's happening at the pixel level (going from nearest neighbor line drawing to bilinear interpolation) and will attach it below.


Archival note: This VB.Net bilinear interpolation code also may help shape a solution to the region stretching in this old Goggy thread.


Now I can start working on trying to establish real time distortion-dragging rects/boxes for all four corners of the image.
Attached Images
File Type: jpg good_distortion_thru_pixel_lerping.jpg (78.7 KB, 38 views)
Attached Files
File Type: zip QuadDistort7b.zip (1.02 MB, 50 views)

Last edited by dotnetwrassler; 10-26-2014 at 07:05 PM.
Reply With Quote
  #8  
Old 11-02-2014, 09:06 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Box O' Cubes?

I'm still trying to figure out how to make all the drag point for the quad distort work, so in the meantime I'd thought I would play around with the more impressive code found in the attachment to post#4 of this thread.

The reason it's so nice (and impressive) is that it's extensible!

Take a look at the screenshot attached below.
It shows that the original cube has been flattened into a 3D panel and 4 more panels of a similar nature have been added, forming a rectangular 3D container.

You're probably wondering - "Where are you going with this..?"

Well this screenshot shows it might be possible to make:
1.) A 3D room (four walls, floor and ceiling --all textured)
2.) A 3D maze

Possibility #2 also means I might be able to make a series of rooms like a Wolfenstein3D setup, complete with sliding doors.
Oh - now your ears are perking up.

Yes, but to do this I have to figure out how to move the camera so it is inside the enclosing panels - ideas?

Anyway, I'll post the code that produced the screenshot so anyone that wants to can play around a little..I think you'll find that positioning 3D objects using code for 6-axis quaternion rotation can be quite maddening!
Attached Images
File Type: jpg screenshot_3D_squished_cube_panels_to_make_3D_container.JPG (29.1 KB, 30 views)
Attached Files
File Type: zip QuaternionDrawing23.zip (1.52 MB, 41 views)
Reply With Quote
  #9  
Old 11-09-2014, 03:38 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default VB.Net 2010: Image Drag Distortion Warp using 3 and/or 4 points

Getting four drag points to work for the QuadDistort7b attachment to post #7 of this thread proved somewhat challenging.

What I finally had to do was a mashup.
Typically the word "mashup" is used when doing a web development project that "blends" together the functionality of multiple web APIs.
I'm just using the term for blending/merging/melding two different VB.Net code bases:
code A + code B + some "glue" code = code C (hopefully with some synergy)

I started with this code for "Code A":
http://www.vb-helper.com/howto_net_image_drag_warp.html

Then the non-dragging QuadDistort7b was "Code B"

The secret to doing an code mashup if to find some tangential point of similarity to pivot off of - in this case
it was a Point array, used to define the shaping of the image as well as establish mouse-drag-adjustable corner ellipses.

Four point distortion could also be referred to under the tags: trapezoidal distortion / warping

The only previous working trapezoidal distortion attachment to an xvbt forum post was,
"trapezoid_warp_using_draggable_grab_handles.zip" attached to this post:
http://www.xtremevbtalk.com/1397373-post1.html

I believe the attachment below shows a significant performance increase over that previous
trapezoidal image / picture warping source code attachment (but you can download and compare the two to judge for yourself).

I've also left in the 3 point DrawImage based drag warp/distort for performance comparison purposes as well.
I think it compares favorably.

I'm imagining this code could be further developed to show a hexagon shape encircled by a set of trapezoids (maybe with all the points draggable);
where the center hexagon shape could contain a texture mapped image that could be made distortable using this existing code,
by means of splitting the image into two trapezoids that would be "mated" back to back into the hexagon shape.

However if I want to render a texture mapped dodecahedron (or maybe some other coded Platonic solid shape),
I would have to figure a GDI+ way to map the texture(s) to x,y,z vertex points in a 3D space.
Any ideas?
Attached Images
File Type: jpg screenshot_3_and_4_point_drag_distort.JPG (69.0 KB, 25 views)
Attached Files
File Type: zip 3-and-4_Point_DragDistort.zip (1.14 MB, 60 views)

Last edited by dotnetwrassler; 11-09-2014 at 03:53 PM.
Reply With Quote
  #10  
Old 11-16-2014, 11:43 AM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Sphere wrapping with color gradients - simulating 3D with math

I know I taunted the readers of this thread with a screenshot back in post#8,
but creating a room out of 3D rect boxes (basically flattened 3D cubes) has proven not a trivial task.

What I need is some kind of alignment grid (perspective mapped into a 3D space).

Additionally it would be helpful to have a
"System.Drawing.Drawing3D.SnapToPerspectiveMappedGrid" function

Of course you can search through the MSDN all day and not find this
because .Net GDIplus section doesn't have an "System.Drawing.Drawing3D" subsection.
<*sigh*>



Anyway, thus far in this thread I've used special VB.Net add on classes that define points in 3D space (X,Y,Z),
then map then into a 2D space to render / draw them onto to a form or control,
however this is not the only approach you can take.

You could (theoretically) just use a whole bunch of trigonometry math (VB.Net has a Math library) and
simulate 3D by drawing at the pixel level directly onto a 2D form space.

I've searched for an example of this using VB.Net code and found nothing.
However I did find this interesting C# example:
http://www.codeproject.com/Articles/...D-Demo-using-C

The main issues with trying to convert this:
1.) There is a lot of casting (type coercion I think its called) going on.
Many of the online translators tried to use "DirectCast" which didn't work at all.
2.) Even after I found a workaround for the casting conversion issues,
all the math (combined with the slow SetPixel API nested calls) made the form painting way too pokey and all but unusable.

So I had to throw in the Boops Boops FastPix wrapper to get things up to speed
with the inclusion of some Marshal.Copy and Lock/Unlock bits code.
Form DoubleBuffering is set to True to have smooth, flicker free animation as well.

3.) Finally I wanted to play around with the coloration, so I threw in some extra code color gradients code
(commented out) to encourage others to have some fun with the code.
Code:
Dim gray As Integer, blackgray As Integer
'..
gray = Math.Abs(240 - CInt(i))
blackgray = Math.Abs(120 - CInt(i))
'..
Using fp As New FastPix(bmap)
'..
 If (j + i) Mod 64 >= 0 AndAlso (j + i) Mod 64 <= 32 Then
   If z2 < 0 Then
   'Blue to green
    fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(&H7800FF00 + CInt(i) * &HFF))

   'Magenta to light yellow
   'fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(&H78FF00FF + CInt(i) * &HFF))

   'Blue to lighter blue
   'fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(&H780000FF + CInt(i) * &H55))

   'Pink to lighter pink -----Note: You can change the '78' (alpha value) in the line below 
   '                      to FF for darker color or 00 for lighter color
   'fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(&H78FF0000 + CInt(i) * &H55))

   'Light orange to light yellow 
   'fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(&H96FFAA00 + CInt(i) * &H55))
   Else
    fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(gray, gray, gray))

     'Comment out the line above and uncomment the line below for a slightly different coloration
     'fp.SetPixel(CInt(xc), CInt(yc), Color.FromArgb(blackgray, blackgray, blackgray))
   End If
 End If
'..
End Using
The z rotation isn't for depth adjusting as in many of the 3D rotational schemes,
so feel free to download ("view") the attachment if you want to find out what this adjustment actually does.

Hopefully I've something better to offer next week...

Oh and if anyone has (of knows of) any VB.Net code to texture wrap a sphere I would really love to see it (any code or links appreciated).
Attached Images
File Type: jpg spherewrap_screenshot.JPG (55.0 KB, 25 views)
Attached Files
File Type: zip SphereWrap.zip (50.0 KB, 51 views)

Last edited by dotnetwrassler; 11-16-2014 at 11:58 AM.
Reply With Quote
  #11  
Old 11-22-2014, 09:15 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Still working on a perspective mapping grid for 3D wall alignment..

Well, I've done some fiddling around with aligning the wall panels (3D flattened cubes) and
I've come to the conclusion I need a working VB.Net perspective mapped grid code.

Sounds easy..even commonplace, doesn't it?

Like there should be dozens of examples of how to do this,
but after many fruitless hours of internet searching the only code I could find was some VB6 code
from an old (September of 1998) ElementK tutorial article dug out of the Wayback Machine.

The source zip was gone, but based on the article I was able to recreate it.

Also...in searching from perspective grids (using Google's Image search), I also found that the UnReal Development Toolkit's (UDK) Unread Editor 2.1 uses
such a grid for alignment of room wall textures, so that convinced me I was on the right track.

The screenshots for both of these are attached below.


So to get some code to render / draw a VB.Net Perspective Mapped Grid,
I ended up using a shareware VB6 to VB.Net convertor:
http://vbto-converter.downloadnow-18...gramsbase.com/

It only managed to output a lot of garbage VB.Net code, but I was able to clean it up enough to get something working.



The main issue for the conversion is that the VB6 code uses a picturebox's scalemode which picturebox controls in VB.net don't have.

VB.Net also didn't benefit from using the Double type values, so I converted the values to Singles,
in order to use PointF structures for the DrawLine calls (instead of Points,
which use Integer types that get too badly truncated with CInt).


I'll also throw in a screenshot of the VB.Net version to show that
the perspective mapped grid lines don't quite fully fill / line up
to the horizon line (which is determined by setting the vanishing point).


The code zip attachment has both the VB6 and VB.Net versions inside.
Maybe there is something that can be done with scale transforms
to more accurately simulate VB6's picturebox control's ScaleMode of "3" (Pixels)

Last edited by dotnetwrassler; 11-22-2014 at 09:27 PM.
Reply With Quote
  #12  
Old 11-24-2014, 01:27 AM
passel's Avatar
passelExploring 3D graphics with VB.Net, but without using DirectX or XNA passel is offline
Sinecure Expert

Super Moderator
* Guru *
 
Join Date: Jun 2003
Location: Upstate New York, usa
Posts: 8,011
Default

I don't know if the grid example is going to be that useful or not for what you're doing.
But, if you want to replicate the ScaleMode of VB6 to a certain extent, you can use the ScaleTransform.
Also, the VB6 program doesn't really use ScaleMode 3. It sets Scalemode 3 so it can get the size of the window in pixels to calculate the aspect ratio to maintain square pixels when it creates a custom scalemode.
As soon as they execute the command: pb.ScaleLeft = pbl
the Scalemode goes to 0, i.e. Custom.
Changing any of the Scale parameters (ScaleLeft, ScaleTop, ScaleWidth or ScaleHeight) changes the mode to custom.
The desire is to have a window whose scale is 100 units wide, and the vertical scale is whatever value that maintains square pixels, which in this case is 70.265...
It also desires to have 0,0 in the bottom left corner, so the top pixel, instead of being the normal Y coordinate of 0, is 70.265...
The ScaleHeight is set to negative 70.625... so that the coordinates count down from 70.625 at the top to 0.0 at the bottom of the window.

You can do something similar on the .Net side.
You use ScaleTransform so that your X coordinates run from 0 to 100 across the window ( sx parameter set to WindowWidth/100) and the sy parameter set to a negative number so that Y scale runs in the reverse direction. The magnitude of the sy value being the calculated value to keep the pixels square (70.265...) divided into the window height.

The main issue to be aware of doing it this way is that in .Net, all drawing is effected by the inverse scale, so while the lines will be drawn and look the same as the VB6 code, if you drew an image or drew some text while the scaling was in effect, the image and text would be drawn upside down.

In any case, a few adjustments to the .Net code will give you output that looks like the VB6 window.
You should have set AutoRedraw to True on your VB6 picturebox, so you don't have to worry about wiping out your work if your want to leave the window open for comparison.

In the .Net code I moved the "Dim pbhpx As Single, pbwpx As Single"
line out to the form class scope, so I could reference them when setting the ScaleTransform.
I also change the Pen width to 0, so the pen width wouldn't scale with the scaletransform, otherwise, a pen width of 1 pixel would draw about 5 pixels wide when we change the scale so that only 100 units covered the horizontal width of the window (pen width would be 1 unit thick).
Dim pen As New Pen(Color.MediumBlue, 0) '0 = Always draw minimum width (1 pixel) line regardless of scale

In the Form Load event, I changed the vOffset back to 20, to match the VB6 code.
vOffset = 20 '-180

In Init3d, I changed the line referencing vOffset back to match what it was in the VB6 code. (adding vOffset, not subtracting it).
vpy = (((pbt - pbb) * (0.5)) + pbb) + vOffset

Also removed the "Dim pbhpx As Single, pbwpx As Single" since that was moved to Class scope.

Then in the Paint event changed the TranslateTransform to put 0,0 at the bottom left, like was done in VB6, and calculated the scaling values to match the custom scale done in VB6. I also moved the horizon line draw code down to make sure it was subject to the transforms.

The 100.0F for the horizontal scale was hardcoded, but probably the value passed to the init3d routine should have been copied to a class variable so it could be referenced here.
I also didn't see a reason for the Doevents, in either the VB6 or the .Net code.

Code:
'....
    ' e.Graphics.TranslateTransform(300.0F, 230.0F)
    e.Graphics.TranslateTransform(0.0F, pbhpx)  '0, pb height
    ' e.Graphics.RotateTransform(180.0F)
 
    e.Graphics.ScaleTransform(pbwpx / 100.0F, -pbhpx / pbt)

    g.DrawLine(pen, pt1F, pt2F)

      'x lines
      For lp = xmin To xmax Step gstep
          ln3d(g, lp, 0, zmin, lp, 0, zmax)
      '       Application.DoEvents()
      Next lp
      'z(lines)
      For lp = zmin To zmax Step gstep
          ln3d(g, xmin, 0, lp, xmax, 0, lp)
      '      Application.DoEvents()
      Next lp
After those changes, if you run both, then compare the windows side by side, or under and over, you'll see the lines should line up between the vb6 and .Net version.
Attached Images
File Type: jpg NetAndVB6HorizonGrid.jpg (109.8 KB, 22 views)
__________________
There Is An Island Of Opportunity In The Middle of Every Difficulty.
Miss That, Though, And You're Pretty Much Doomed.

Last edited by passel; 11-24-2014 at 01:49 AM.
Reply With Quote
  #13  
Old 11-29-2014, 07:25 AM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default passel helps out...

Thanks passel!
Your knowledge of using Transforms in VB.Net is obviously much more adept than mine.

I will work with your code update, but I need to be able to have the perspective projection to happen in all three axises to be able to slant the walls right.

I'm working with making 3D "planes" out of 3D dots so I can figure out what x,y,z points I need. That's the hardest part is mathematically calculating all the points in 3D space.

In the meantime, working with 3D "slantiness" I've been able to come with a 3D wireframe pyramid. Theoretically using the quad distortion texturing it should be possible to "pinch" two of the corners to have the texture shaped like a triangle and mapped to the pyramid.

I'm thinking that eventually 3D plotting code can eventually produce something like the Chen_Gackstatter_minimal_surface picture attached below.
I know - I'm dreaming...but if you are going to dream you might as well dream big!

However, that's it for now.

I ended up working through the Thanksgiving day holiday, so I'm working through Friday. I will try to post something again on Saturday.
Attached Images
File Type: jpg screenshot_pyramid_3D.JPG (59.5 KB, 20 views)
File Type: jpg Chen_Gackstatter_minimal_surface.jpg (61.6 KB, 22 views)
Attached Files
File Type: zip Pyramid_3D.zip (83.4 KB, 35 views)
Reply With Quote
  #14  
Old 12-01-2014, 08:54 AM
boops boops's Avatar
boops boops boops boops is offline
Centurion
 
Join Date: Dec 2006
Location: Holland and France
Posts: 146
Default

System.Drawing.Drawing2D does in fact contain a little nugget of 3D cleverness: the Perspective mode in the GraphicsPath.Warp method. Unfortunately it only works for GraphicsPaths, not for bitmaps. But it's fairly efficient, I suppose because the number of path points requiring computation is normally tiny compared to the number of pixels in any self-respecting bitmap. Here's a code example:

Code:
gp.AddEllipse(srcRect)
Using sf As New StringFormat With _
{.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center}
    gp.AddString("Really?", New FontFamily("Georgia"), FontStyle.Bold, 65, srcRect, sf)
End Using

'apply a perspective warp to the path:
gp.Warp({A.To2D, B.To2D, D.To2D, C.To2D}, srcRect, Nothing, Drawing2D.WarpMode.Perspective)
It comes from the attached rotating cube demo. At the moment, the cube is wireframe with the front and back faces filled. And there's at least one bug: I still haven't figured out why the text starts (and mostly stays) upside down.

Screen shot and code attached. Give it a try!

BB
Attached Images
File Type: jpg CubeReally.jpg (114.5 KB, 18 views)
Attached Files
File Type: zip PerspectiveWarp3.zip (19.4 KB, 24 views)
Reply With Quote
  #15  
Old 12-06-2014, 04:51 AM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default boops boops joins the thread (with an attachment)!

Thanks for posting boops boops.

Text undergoing warped transform as a graphics path - wow.
That's something I never would of though of...

The way the tint shaded from the cube's back plane shows through the text outlines is really interesting as well.

The perspective mapped text outlines would make for some nice HUD (Heads up display) labeling in a 3D game.

The issue with the text being backwards can probably be correct with some kind of
transform(s) probably...but I really don't understand how they work even with passel's help a few posts back.

Speaking of which...
I had trouble getting passel's code suggestions to work, because the value of
pbt (as I stepped through the code) kept coming up as -1
in this line:
Code:
pbt = b + ((pbhpx / pbwpx) * w)
which then caused an error in this line:
Code:
e.Graphics.ScaleTransform(pbwpx / 100.0F, -pbhpx / pbt)
So I fiddled around with it and finally came up with a magic number (without knowing why it works):
Code:
Sub init3d(ByVal l As Single, ByVal b As Single, _
              ByVal w As Single, ByVal z As Single, ByVal vpoff As Single)
    '...
    'pbt = b + ((pbhpx / pbwpx) * w)
    pbt = 1000
    '...
End Sub
I also wanted to try and get an addition perspective map grid oriented vertically.
The screenshot below was the best I could come up with (produced from the working multiple perspective mapping code zip attached below).
Maybe someone can steer me to the right transform(s) code?

What should be happening:
The red perspective map should align vertically with the center of the window (going from the top edge of the blue perspective lines
to the top of the window --instead of pinching off
at the center and narrowing toward the vanishing point/plane).

It would also be nice if it could extend fully in 3D space,
so half the red perspective plane is above the blue perspective plane and
half below it (right now the whole red perspective plane
is position above the blue perspective plane in 3D space).

I want the two planes to form two axes perpendicular to each other to figure out
the correct 3D mapping point for the quad distortion texture mapping of 3 walls and a floor.
One wall would be in the back and the other two walls would slant inward to meet it from the left and the right side.
The floor plane, of course, would intersect all three walls at the bottom (in a trapezoidal shape).


Last (but not least) I also throw in a working screenshot of some C# code I'm trying to do a VB.Net translation of ---remember I
mentioned in my last post about a cube made from planes of 3D dots.

I managed to clear all the errors from the VB.Net version, but the SetPixel routines
(connected with the FastBitmap class) just aren't showing up any graphics for some reason????

I know the Form Paint event is corrected hooked into the e.graphics
because the screen does execute a g.FillRectangle correctly.
I also know the FastBitmap is creating the bitmap properly
(otherwise I'd be getting a big red "X" on the DrawImage flip graphics call).

Both working and non-working code are zipped together and attached below if anyone is interested.

Last edited by dotnetwrassler; 12-06-2014 at 05:11 AM.
Reply With Quote
  #16  
Old 12-07-2014, 09:23 AM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Some thoughts on the conceptual leap (paradigm shift) from 2D to 3D

I spent a few hours playing with boops boops's PerspectiveWarp3 code attachment (from post#14 of this thread) and something was bothering me.

I couldn't quite figure out what exactly that was.
So I went to sleep.
I woke up this morning and realized what it was.

Here's the "problem" code:
Code:
 'get the 2D coordinates of the front and rear faces:
 front = {A.To2D, B.To2D, C.To2D, D.To2D}
 rear = {AA.To2D, BB.To2D, CC.To2D, DD.To2D}

 'choose front fill colors according to inside/outside cube:
 Dim color1, color2 As Color
 If FaceOut(front) Then
  color1 = Color.DimGray : color2 = Color.Yellow
 Else
  color1 = Color.Blue : color2 = Color.Red
 End If
What's wrong with that (you might ask)...it's perfect valid working code, right?
Yes, but there is something going on that (conceptually) for me is a little off..

To explain let me tell you a little bit about my frustration with researching via MSDN.

The online/offline MSDN is great if you just need to reference some API or function.
It even (in places) provides helpful bits of code that can be snagged to help projects develop faster.

Here's what the MSDN is not good for --it doesn't really explain things.

The closest that you get is usually stashed away in an appendix, or a C++ "walkthrough".

Take a look at this yummy "Matrix Representation of Transformations" page (part of a section called "Coordinate Systems and Transformations").
You think "oh yeah, even a kindergarden kid could understand that..."

The question that keeps pinging around my mind though is this:
"How is a 2D space really all that different a 3D space?"
It's basically just a set of points right?
So a 2D point is (x1, y1)
A 3D point is (x1, y1, z1)
You can make lines out of 3D points the same way you can make lines out of 2D points. All you need is two points, right?

But wait a minute...not so fast!

There is a translation that goes on.
As of this point in time we don't have holographic 3D screens, so we have to settle for the old 2D LED type display.
To represent 3D on a 2D display means that has to be a "flattening" of dimensions.

This is what is getting me in trouble conceptually.

For one thing such a flattening takes place in the context of the viewer (and viewer angle).
In 3D terminology such a viewing "cone" (or sometimes pyramid) is called a frustrum.
Anything outside of the frustrum is usually "culled" (eliminated) in the 3D to 2D "translation"
(and not having to do texture mapping of anything not seen is an important performance enhancer).

Going back to boops boops's code snippet above, you notice that there is an opportunity for the color gradients to change
depending on the viewing angle (whether you are seeing the front face or the back face).

This is like saying if you tilt your head at a different angle when viewing a 2D gradient on a 2D screen
there would be a color shift --but of course in a strictly 2D context such a shift does not happen.

Here's the other weird thing --if you texture map a 3D quad (a set of 4 corners each of which is a point in 3D space)
you can actually "turn around" (change the "camera" viewer angle)
to where the mapped texture disappears (becomes literally non-visible/invisible).

The viewing or camera angle can also determine if a 3D point/object is actually still
seen (or considered visible) after the 3D to 2D "flattening" transform happens.

It's hard to see this in boops boops' example because the existing code doesn't allow you
to move the camera (or viewing angle) to be inside the cube.

That's what I'm struggle with right now trying to make a texture mapped 3D "room".

All of which must seem painfully obvious to skilled 3D programmers, but it's really not explained
(in a non-mathematical way) anywhere in the MSDN,
so I just so I thought in a note in this middle of this thread might be appropriate.

If anyone can point me to another xvbt forum thread that makes the same point in a GDI+ 3D context,
please feel free to post a link..because I haven't found such a thread/post.

Last edited by dotnetwrassler; 12-07-2014 at 09:28 AM.
Reply With Quote
  #17  
Old 12-07-2014, 03:02 PM
boops boops's Avatar
boops boops boops boops is offline
Centurion
 
Join Date: Dec 2006
Location: Holland and France
Posts: 146
Default

Quote:
Originally Posted by dotnetwrassler View Post
I spent a few hours playing with boops boops's PerspectiveWarp3 code attachment (from post#14 of this thread) and something was bothering me.

I couldn't quite figure out what exactly that was.
So I went to sleep.
I woke up this morning and realized what it was.

Here's the "problem" code:
Code:
 'get the 2D coordinates of the front and rear faces:
 front = {A.To2D, B.To2D, C.To2D, D.To2D}
 rear = {AA.To2D, BB.To2D, CC.To2D, DD.To2D}

 'choose front fill colors according to inside/outside cube:
 Dim color1, color2 As Color
 If FaceOut(front) Then
  color1 = Color.DimGray : color2 = Color.Yellow
 Else
  color1 = Color.Blue : color2 = Color.Red
 End If
Actually there is at least one error in there: FaceOut should have been called FaceIn.

My animated cube was meant in the first place as a demo of GraphicsPath.WarpMode.Perspective. I tried to work out the geometry of the cube corners as far as possible myself as a learning process. Interestingly, I ended up with a Point3D class which is practically identical to yours in your tetrahedron code. But it's nothing really new anyway.

There are 2 problems that need looking at.

1. Hidden surfaces of the cube aren't always rendered in the right order. For example if you position the camera behind the cube (e.g. z=-500), the cube sometimes looks like a truncated pyramid because a small square masks a big one. I believe I can fix it like this: find the average Z of the corners of each face, and paint them in rising average-Z order. It should work for any polyhedron except one with self-intersecting faces, and I hope I can make it work for wire-frame lines at the same time.

2. The demo goes amusingly haywire once the camera gets inside the cube. That may be something that needs working out for your room interior view, although my rotating cube demo is hardly an ideal place to start. It should be possible to fix it but it will take some thinking about.

Quote:
Yes, but there is something going on that (conceptually) for me is a little off..

To explain let me tell you a little bit about my frustration with researching via MSDN.

The online/offline MSDN is great if you just need to reference some API or function.
It even (in places) provides helpful bits of code that can be snagged to help projects develop faster.

Here's what the MSDN is not good for --it doesn't really explain things.

The closest that you get is usually stashed away in an appendix, or a C++ "walkthrough".

Take a look at this yummy "Matrix Representation of Transformations" page (part of a section called "Coordinate Systems and Transformations").
You think "oh yeah, even a kindergarden kid could understand that..."
Msdn sometimes explains things better than that, but I share your pain in this case. That article is in any case about matrices in 2D, and I don't think you need to worry about them. Matrix operations are an mathematical technique for combining successive transformations so as to reduce the computation need. But for most purposes Graphics methods like TranslateTransform, ScaleTransform and RotateTransform do all that work for you under the surface. Still, the Matrix class is there if you want it and it does have a rather neat RotateAt method which is lacking in Graphics.

People sometimes use matrices for 3D rendering but it's more in theory than practice. Besides, quaternions are better for practical purposes. Their main purpose is for efficiently combining simultaneous rotations around 2 or 3 axes into a single rotation around a different axis. They also serve a purpose for interpolation, but that's off-topic for the moment. The quaternion saves quite a bit of computation when rendering 3D points or a texture, and it's immune to gimbal lock. You quaterion17a code seems to me to illustrate their use rather well. You don't need to look at the Quaternion class itself or to understand the theory behind it: just treat it like a black box. All you need is its New and Multiply methods. Incidentally, there is already a fully developed Quaternion class available in dotnet, in System.Windows.Media. It's part of WPF but there's no reason you can't reference it and use the Quaternion and its methods in a non-WPF program.

Quote:
The question that keeps pinging around my mind though is this:
"How is a 2D space really all that different a 3D space?"
It's basically just a set of points right?
So a 2D point is (x1, y1)
A 3D point is (x1, y1, z1)
You can make lines out of 3D points the same way you can make lines out of 2D points. All you need is two points, right?
3D is more difficult than 2D by a factor of Math.Pi ^ i ^j ^k. OK, I just made that up.
Quote:
But wait a minute...not so fast!
Go ahead.
Quote:
There is a translation that goes on.
As of this point in time we don't have holographic 3D screens, so we have to settle for the old 2D LED type display.
To represent 3D on a 2D display means that has to be a "flattening" of dimensions.

This is what is getting me in trouble conceptually.

For one thing such a flattening takes place in the context of the viewer (and viewer angle).
In 3D terminology such a viewing "cone" (or sometimes pyramid) is called a frustrum.
Anything outside of the frustrum is usually "culled" (eliminated) in the 3D to 2D "translation"
(and not having to do texture mapping of anything not seen is an important performance enhancer).

Going back to boops boops's code snippet above, you notice that there is an opportunity for the color gradients to change
depending on the viewing angle (whether you are seeing the front face or the back face).

This is like saying if you tilt your head at a different angle when viewing a 2D gradient on a 2D screen
there would be a color shift --but of course in a strictly 2D context such a shift does not happen.
The color gradients and transparency I use in the demo are just decoration. They won't help you at all with the rendering of light sources and reflective materials that the real 3d whizzes do.
Quote:
Here's the other weird thing --if you texture map a 3D quad (a set of 4 corners each of which is a point in 3D space)
you can actually "turn around" (change the "camera" viewer angle)
to where the mapped texture disappears (becomes literally non-visible/invisible).
I guess you need to paint the back surface too.
Quote:
The viewing or camera angle can also determine if a 3D point/object is actually still
seen (or considered visible) after the 3D to 2D "flattening" transform happens.

It's hard to see this in boops boops' example because the existing code doesn't allow you
to move the camera (or viewing angle) to be inside the cube.
That's what I'm struggle with right now trying to make a texture mapped 3D "room".
The faulty hidden-surface rendering is a separate problem from rendering an interior, as I explained above.

BB
Reply With Quote
  #18  
Old 12-14-2014, 06:45 PM
dotnetwrassler dotnetwrassler is offline
Regular
 
Join Date: Sep 2014
Location: USA (Pacific/West Coast)
Posts: 71
Default Hidden surfaces and amusingly haywire viewing..

Thanks for your lengthy reply to my last post and for "feeling my pain".
And you are quite right that 3D is much more difficult than 2D
(I'm just beginning to explore the many/different ways it is more difficult).


Pressing on, though...I casually mentioned back in post #13:
Quote:
Theoretically using the quad distortion texturing it should be possible to "pinch" two of the corners
to have the texture shaped like a triangle and mapped to the pyramid.
Getting a working demo of this required merging code from the attachment to post #9
into the code attachment for post #13 and then adding addition point arrays coding.


I'll attach the screenshot of the new (and probably the only VB.Net GDI+ based) tetrahedron texture mapping test program below.



boops boops mentioned (in regard to z-ordering and hidden surface removal):
Quote:
I believe I can fix it like this: find the average Z of the corners of each face, and paint them in rising average-Z order.
It should work for any polyhedron except one with self-intersecting faces, and I hope I can make it work for wire-frame lines at the same time
I haven't seen any code for calculating "rising average-Z order", so I just fudged things for this TTM test program
by just putting in an extra If.. statement that flips the z-order before & after the 90 degrees rotation angle.


Of course the tetrahedron demo doesn't allow for end-over-end gimbaled quaternion rotation,
which would definitely require some fancier type of rotational test code and z-ordering adjustment.

That's the point where I become hopelessly lost..



So, backing up a bit to work on something else...the Perspective Warp demo suggests
that there are possibilities of doing mapping of the faces using a vector approach.


Of course what immediately comes to mind is using PathGradients, but the attached working test program suggests
that it's hard (somewhat involved) to get the gradient to show an enlarged background color in the center,
let alone a nice round rectangle alpha gradient fill for a cube face
(see the graphic for my Photoshop mockup of this "glow effect" below).


However not using PathGradient I was better able to get something closer
(see the roundRect fill alphaGradient technique screenshot below).
Can you guess what type of graphics coding I used?
Hint: I'm also not using WPF Alpha Radial gradients.



Lastly, with the first ever semi-successful coding of texture mapped tetrahedrons, this brings up a number of possibilities like:
1.) Terrain meshes made from textured triangle strips
2.) Puzzle games based on 3D tangrams

Does anyone remember which Keanu Reeves movie had a VR sequence that used 3D tangrams as a hotel passkey?
The "glow effect" also appears in another movie with a 3D fly thru sequence..anyone remember in which movie?
Attached Images
File Type: jpg screenshot_texturemapped_tetrahedron.JPG (58.8 KB, 21 views)
File Type: jpg wireframe_cube_with_glow_effect.jpg (40.1 KB, 20 views)
File Type: jpg roundRectFill_alphaGradient_test.JPG (14.3 KB, 20 views)
Attached Files
File Type: zip tetrahedron texture_mapping_test.zip (1.25 MB, 35 views)
File Type: zip PathGradient_Tester.zip (47.2 KB, 33 views)

Last edited by dotnetwrassler; 12-14-2014 at 06:55 PM.
Reply With Quote
  #19  
Old 12-15-2014, 09:24 AM
boops boops's Avatar
boops boops boops boops is offline
Centurion
 
Join Date: Dec 2006
Location: Holland and France
Posts: 146
Default

Quote:
Originally Posted by dotnetwrassler View Post
Thanks for your lengthy reply to my last post and for "feeling my pain".
And you are quite right that 3D is much more difficult than 2D
(I'm just beginning to explore the many/different ways it is more difficult).

Pressing on, though...I casually mentioned back in post #13:

Getting a working demo of this required merging code from the attachment to post #9
into the code attachment for post #13 and then adding addition point arrays coding.

I'll attach the screenshot of the new (and probably the only VB.Net GDI+ based) tetrahedron texture mapping test program below.
I hate to mention this, but a square-based pyramid isn't a tetrahedron. That has only four faces (all equilateral triangles) and four vertices. If it's a tetrahedron you actually want, you can find a formula for its vertex coordinates in Wikipedia ("Tetrahedron").

Quote:
boops boops mentioned (in regard to z-ordering and hidden surface removal):

I haven't seen any code for calculating "rising average-Z order", so I just fudged things for this TTM test program
by just putting in an extra If.. statement that flips the z-order before & after the 90 degrees rotation angle.

Of course the tetrahedron demo doesn't allow for end-over-end gimbaled quaternion rotation,
which would definitely require some fancier type of rotational test code and z-ordering adjustment.
I don't think you need quaternions at this stage, because you only have 5 point3Ds to reposition. Just calling their RotateX and RotateZ methods instead of (or as well as) RotateY should work. The real time guzzler in your code is the texture mapping. I can think of some ways it might be possible to speed it up, but it is never going to get anywhere near the hardware-accelerated methods of DirectX etc.

Quote:
That's the point where I become hopelessly lost..

So, backing up a bit to work on something else...the Perspective Warp demo suggests
that there are possibilities of doing mapping of the faces using a vector approach.

Of course what immediately comes to mind is using PathGradients, but the attached working test program suggests
that it's hard (somewhat involved) to get the gradient to show an enlarged background color in the center,
let alone a nice round rectangle alpha gradient fill for a cube face
(see the graphic for my Photoshop mockup of this "glow effect" below).

However not using PathGradient I was better able to get something closer
(see the roundRect fill alphaGradient technique screenshot below).
Can you guess what type of graphics coding I used?
Hint: I'm also not using WPF Alpha Radial gradients.
My guess is that you are repeatedly superimposing the same shape, scaling it down and increasing the opacity each time. But I'm sure it's possible to do it with a PathGradientBrush.

Quote:
Lastly, with the first ever semi-successful coding of texture mapped tetrahedrons, this brings up a number of possibilities like:
1.) Terrain meshes made from textured triangle strips
2.) Puzzle games based on 3D tangrams

Does anyone remember which Keanu Reeves movie had a VR sequence that used 3D tangrams as a hotel passkey?
The "glow effect" also appears in another movie with a 3D fly thru sequence..anyone remember in which movie?
I've attached upgraded code of my cube anim. It's a work in progress. Now it has much more of an OOP structure. I think I've fixed the z-order using average Z for each face and the haywire paths were a simple bug. You can roll the camera in and out with the mouse wheel, but don't expect too much of it: now the program seizes up when the camera gets too close to the cube, and the cube stretches in the Z direction like something getting sucked into a black hole.

Rotations around cube center points other than (0,0,0) also don't work correctly (yet). Maybe I'll put off sorting that out until I've replaced the Point3D rotate methods by something with quaternions.

The cube now has text on all faces. I started by labelling the faces "Front", "Top" etc. for debugging purposes. To amuse myself I added some (mostly) rhyming texts to fill up the faces. The main purpose was to see how it behaves when there's a lot of path points. Performance data (frames per second) is written to the form's title bar. There's a check box to disable rendering to the screen, to get some idea of how much time is taken just to compute the geometry.

BB
Attached Files
File Type: zip PerspectiveWarp3.zip (34.1 KB, 26 views)
Reply With Quote
  #20  
Old 12-15-2014, 06:58 PM
passel's Avatar
passelExploring 3D graphics with VB.Net, but without using DirectX or XNA passel is offline
Sinecure Expert

Super Moderator
* Guru *
 
Join Date: Jun 2003
Location: Upstate New York, usa
Posts: 8,011
Default

I made a couple of small changes to make the cube seem more interactive to me. They may not be correct changes, but here they are.
I went ahead and commented out the /10 so the distance the camera is away from the object can be changed quicker with the scroll wheel.
I also went ahead and limited (to 400) how close the camera can get to the object to avoid the hang or rendering slow down, for now.
Code:
  Private Sub Form2_MouseWheel(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseWheel
    Scene.Camera.Z -= e.Delta '/ 10
    If Scene.Camera.Z < 400 Then Scene.Camera.Z = 400
    Me.Text = "camera Z = " & Scene.Camera.Z.ToString("G")
    'Cube1.Center.Z += e.Delta / 5
    'Me.Text = "centre Z = " & Cube1.Center.Z.ToString("G")
    Me.Invalidate()
  End Sub
Then, the z distance ratio as I understand it has primarily two parts, the distance between the eye and the screen you are projecting on, which should be a constant, and the distance between the eye and the object being drawn.
You essentially divide the eye to screen distance by the eye to object distance to get the scaling.
You were dividing camera distance to the object by (camera distance to the object - size of object).

You can usually calculate the eye to screen distance constant by determining what size object you want to fill the screen at what distance from the eye.
In your case, since you defaulted the distance to 1000 at the start to mostly fill the screen with your box, then your eye distance to the screen constant should be around 1000.
So, I changed the p2D function to use that 1000 for now.
Give it a try and see if you like the way it scales the object better.
Code:
  'get 2D projection on Z=0 plane of a Point3D:
  Private Function p2D(p3D As Point3D) As PointF
    Dim zDist As Double = Scene.Camera.Z - p3D.Z
    If zDist = 0 Then
      Return New PointF(CSng(p3D.X), CSng(p3D.Y))
    Else
    '      Dim f As Double = Scene.Camera.Z / zDist
      Dim f As Double = 1000 / zDist
      'If p3D.Z < 0 Then f = 1 / f
      Return New PointF(CSng(p3D.X * f), CSng(p3D.Y * f))
    End If
  End Function
For a general class, you'll want a way to configure/specify that eye to screen const to suit the scale the user of the class wants for their implementation.
__________________
There Is An Island Of Opportunity In The Middle of Every Difficulty.
Miss That, Though, And You're Pretty Much Doomed.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
 
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
Exploring 3D graphics with VB.Net, but without using DirectX or XNA
 
-->