//三角形利用矩阵乘法变换 传入变换矩阵 public void TransForm(Matrix4x4 m) { //为了避免 double 类型反复相乘的 数据精确度下降 每次都是用原始数据相乘 this.a = m.Mul(this.A); this.b = m.Mul(this.B); this.c = m.Mul(this.C); }
public vector4(vector4 v) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = v.w; }
private void Form1_Load(object sender, EventArgs e) { vector4 a = new vector4(0, 0.5, 0, 1);//只有第四个点位1 矩阵乘法才成立 所以最后一位要求是1 vector4 b = new vector4(0.5, -0.5, 0, 1); vector4 c = new vector4(-0.5, -0.5, 0, 1); t = new Triangle3D(a, b, c); }
/// <summary> /// 把四维 点 转化为投影平面的 2D点 /// </summary> /// <param name="v"></param> /// <returns></returns> private PointF Get2DPointF(vector4 v) { PointF p = new PointF(); p.X = (float)(v.x / v.w);//透视除法 向量分量 除以 w分量 p.Y = -(float)(v.y / v.w); return(p); }
public vector4 Mul(vector4 v) { vector4 newV = new vector4(); newV.x = v.x * this[1, 1] + v.y * this[2, 1] + v.z * this[3, 1] + v.w * this[4, 1]; newV.y = v.x * this[1, 2] + v.y * this[2, 2] + v.z * this[3, 2] + v.w * this[4, 2]; newV.z = v.x * this[1, 3] + v.y * this[2, 3] + v.z * this[3, 3] + v.w * this[4, 3]; newV.w = v.x * this[1, 4] + v.y * this[2, 4] + v.z * this[3, 4] + v.w * this[4, 4]; return(newV); }
//绘制三角形到2d 窗口上 // public void CalculateLighting(Matrix4x4 _Object2world, vector4 L) { this.TransForm(_Object2world); //直接完成世界坐标的变换 vector4 U = this.b - this.a; vector4 V = this.c - this.a; vector4 normal = U.Cross(V); dot = normal.Noralized.Dot(L.Noralized);//得到夹角 dot = Math.Max(0, dot); vector4 E = new vector4(0, 0, -1, 0); cullBack = normal.Noralized.Dot(E) < 0 ? true : false;//法向量与 视向量的点积小于0 则剔除 }
public Triangle3D(vector4 a, vector4 b, vector4 c) { this.A = this.a = new vector4(a); this.B = this.b = new vector4(b); this.C = this.c = new vector4(c); }
/// <summary> /// 向量点积得到 夹角 /// </summary> /// <param name="v"></param> /// <returns></returns> public float Dot(vector4 v) { return((float)(this.x * v.x + this.y * v.y + this.z * v.z)); }
/// <summary> /// 向量叉乘 得到法向量 /// </summary> /// <param name="v"></param> /// <returns></returns> public vector4 Cross(vector4 v) { return(new vector4(this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.z, this.x * v.y - this.y - v.x, 0)); }