wireframe
What’s the “minimum” amount of C# code you need to create a spinning wireframe quad in 3D?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace Wireframe1
{
public partial class Form1 : Form
{
List<Vertex> vertices = new List<Vertex>();
Point prev = new Point();
Point curr = new Point();
Point first = new Point();
float angle = 0.0f;
public Form1()
{
InitializeComponent();
vertices.Add(new Vertex(-1.0f, -1.0f, 0.0f));
vertices.Add(new Vertex(-1.0f, 1.0f, 0.0f));
vertices.Add(new Vertex( 1.0f, 1.0f, 0.0f));
vertices.Add(new Vertex( 1.0f, -1.0f, 0.0f));
}
private void OnTick(object sender, EventArgs e)
{
this.Invalidate();
}
private void OnPaint(object sender, PaintEventArgs e)
{
// rotate quad a little
int rotationTime = 8000;
int time = System.Environment.TickCount % rotationTime;
angle = time * (2.0f * (float)Math.PI) / rotationTime;
for (int i = 0; i < 4; ++i)
{
// we don't want to alter the original vert
Vertex v = new Vertex(vertices[i].x,
vertices[i].y,
vertices[i].z);
float oldX = vertices[i].x;
float oldY = vertices[i].y;
float oldZ = vertices[i].z;
// y-axis rotation
v.x = oldX * (float) Math.Cos(angle) +
oldZ * (float)Math.Sin(angle);
v.z = oldX * (float)-Math.Sin(angle) +
oldZ * (float)Math.Cos(angle);
// view transform - translate inverse cam
v.z -= -2.4f; // move camera back slightly
// - simple perspective divide (not the best looking)
// - note: building a perspective matrix with an
// arbitrary field of view is more involved
v.x /= v.z;
v.y /= v.z;
// screen transform
v.x = v.x * 640 / 2 + 640 / 2;
v.y = -v.y * 480 / 2 + 480 / 2;
curr.X = (int)v.x;
curr.Y = (int)v.y;
if (i == 0)
{
first = curr;
prev = curr;
continue;
}
e.Graphics.DrawLine(Pens.Black, prev, curr);
prev = curr;
} // end for
e.Graphics.DrawLine(Pens.Black, curr, first);
} // end OnPaint
} // end Form
public struct Vertex
{
public float x;
public float y;
public float z;
public Vertex(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
} // end Vertex
} // end namespace
Leave a Reply
You must be logged in to post a comment.
