#-*- coding: UTF-8 -*-'''Vector3 3D向量类
关于操作符重载 http://docs.python.org/reference/datamodel.html'''importmathclassVector3():def__init__(self,x,y,z):
self.x=x
self.y=y
self.z=z#置为零向量defzero():
self.x=0
self.y=0
self.z=0#"=" 赋值不支持重载#重载 "==" 操作符def__eq__(self, other):returnself.x==other.xandself.y==other.yandself.z==other.z#重载 "!=" 操作符def__ne__(self, other):returnself.x!=other.xorself.y!=other.yorself.z!=other.z#重载一元 "-" 操作符def__neg__(self):returnVector3(-self.x,-self.y,-self.z)#重载 "+" 操作符def__add__(self, other):returnVector3(self.x+other.x, self.y+other.y, self.z+other.z)#重载 "-" 操作符def__sub__(self, other):returnVector3(self.x-other.x, self.y-other.y, self.z-other.z)#重载 "*" 操作符def__mul__(self, a):returnVector3(self.x*a, self.y*a, self.z*a)#重载 "/" 操作符def__div__(self, a):if(a!=0):returnVector3(self.x/a, self.y/a, self.z/a)else:returnNone#重载 "+=" 操作符def__iadd__(self, other):
self.x+=other.x
self.y+=other.y
self.z+=other.zreturnself#重载 "-=" 操作符def__isub__(self, other):
self.x-=other.x
self.y-=other.y
self.z-=other.zreturnself#重载 "*=" 操作符def__imul__(self, a):
self.x*=a
self.y*=a
self.z*=areturnself#重载 "/=" 操作符def__idiv__(self, a):if(a!=0):
self.x/=a
self.y/=a
self.z/=areturnself#向量标准化defnormalize(self):
magSq=self.x*self.x+self.y*self.y+self.z*self.zif(magSq>0):
oneOverMag=1.0/math.sqrt(magSq)
self.x*=oneOverMag
self.y*=oneOverMag
self.z*=oneOverMag#向量求模defvectorMag(self):returnmath.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)#向量显示deftoString(self):print"{x:"+str(self.x)+",y:"+str(self.y)+",z:"+str(self.z)+"}"#向量点乘defdotProduct(va, vb):returnva.x*vb.x+va.y*vb.y+va.z*vb.z#向量叉乘defcrossProduct(va, vb):
x=va.y*vb.z-va.z*vb.y
y=va.z*vb.x-va.x*vb.z
z=va.x*vb.y-va.y*vb.xreturnVector3(x,y,z)#计算两点间的距离defdistance(va, vb):
dx=va.x-vb.x
dy=va.y-vb.y
dz=va.z-vb.zreturnmath.sqrt(dx*dx+dy*dy+dz*dz)