utils3D.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import numpy as np
  2. import pyrr
  3. from collections import defaultdict
  4. import copy
  5. def getRay(x, y):
  6. direc = [y[0] - x[0], y[1] - x[1], y[2] - x[2]]
  7. return np.array([x, direc])
  8. def getDist(pos1, pos2):
  9. return np.sqrt(sum([(pos1[0] - pos2[0]) ** 2, (pos1[1] - pos2[1]) ** 2, (pos1[2] - pos2[2]) ** 2]))
  10. def getManDist(pos1, pos2):
  11. return sum([abs(pos1[0] - pos2[0]), abs(pos1[1] - pos2[1]), abs(pos1[2] - pos2[2])])
  12. def getNearest(Space, pt):
  13. '''get the nearest point on the grid'''
  14. mindis, minpt = 1000, None
  15. for pts in Space:
  16. dis = getDist(pts, pt)
  17. if dis < mindis:
  18. mindis, minpt = dis, pts
  19. return minpt
  20. def Heuristic(Space, t):
  21. '''Max norm distance'''
  22. h = {}
  23. for k in Space.keys():
  24. h[k] = max([abs(t[0] - k[0]), abs(t[1] - k[1]), abs(t[2] - k[2])])
  25. return h
  26. def heuristic_fun(initparams, k, t=None):
  27. if t is None:
  28. t = initparams.goal
  29. return max([abs(t[0] - k[0]), abs(t[1] - k[1]), abs(t[2] - k[2])])
  30. def isinbound(i, x, mode=False):
  31. if mode == 'obb':
  32. return isinobb(i, x)
  33. if i[0] <= x[0] < i[3] and i[1] <= x[1] < i[4] and i[2] <= x[2] < i[5]:
  34. return True
  35. return False
  36. def isinball(i, x):
  37. if getDist(i[0:3], x) <= i[3]:
  38. return True
  39. return False
  40. def isinobb(i, x):
  41. # pt = i.O.T@np.array(x) # transform the point from {W} to {body}
  42. # minx,miny,minz,maxx,maxy,maxz = i.P[0] - i.E[0],i.P[1] - i.E[1],i.P[2] - i.E[2],i.P[0] + i.E[0],i.P[1] + i.E[1],i.P[2] + i.E[2]
  43. T = np.vstack([np.column_stack([i.O.T,-i.O.T@i.P]),[0,0,0,1]])
  44. pt = T@np.append(x,1) # transform the point from {W} to {body}
  45. minx,miny,minz,maxx,maxy,maxz = - i.E[0],- i.E[1],- i.E[2],+ i.E[0],+ i.E[1],+ i.E[2]
  46. block = [minx,miny,minz,maxx,maxy,maxz]
  47. return isinbound(block, pt)
  48. def OBB2AABB(obb):
  49. # https://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?print=1
  50. aabb = copy.deepcopy(obb)
  51. P = obb.P
  52. a = obb.E
  53. A = obb.O
  54. # a1(A1 dot x) + a2(A2 dot x) + a3(A3 dot x)
  55. Ex = a[0]*abs(A[0][0]) + a[1]*abs(A[1][0]) + a[2]*abs(A[2][0])
  56. Ey = a[0]*abs(A[0][1]) + a[1]*abs(A[1][1]) + a[2]*abs(A[2][1])
  57. Ez = a[0]*abs(A[0][2]) + a[1]*abs(A[1][2]) + a[2]*abs(A[2][2])
  58. E = np.array([Ex, Ey, Ez])
  59. aabb.P = P
  60. aabb.E = E
  61. aabb.O = np.array([[1,0,0],[0,1,0],[0,0,1]])
  62. return aabb
  63. def lineSphere(p0, p1, ball):
  64. # https://cseweb.ucsd.edu/classes/sp19/cse291-d/Files/CSE291_13_CollisionDetection.pdf
  65. c, r = ball[0:3], ball[-1]
  66. line = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]
  67. d1 = [c[0] - p0[0], c[1] - p0[1], c[2] - p0[2]]
  68. t = (1 / (line[0] * line[0] + line[1] * line[1] + line[2] * line[2])) * (
  69. line[0] * d1[0] + line[1] * d1[1] + line[2] * d1[2])
  70. if t <= 0:
  71. if (d1[0] * d1[0] + d1[1] * d1[1] + d1[2] * d1[2]) <= r ** 2: return True
  72. elif t >= 1:
  73. d2 = [c[0] - p1[0], c[1] - p1[1], c[2] - p1[2]]
  74. if (d2[0] * d2[0] + d2[1] * d2[1] + d2[2] * d2[2]) <= r ** 2: return True
  75. elif 0 < t < 1:
  76. x = [p0[0] + t * line[0], p0[1] + t * line[1], p0[2] + t * line[2]]
  77. k = [c[0] - x[0], c[1] - x[1], c[2] - x[2]]
  78. if (k[0] * k[0] + k[1] * k[1] + k[2] * k[2]) <= r ** 2: return True
  79. return False
  80. def lineAABB(p0, p1, dist, aabb):
  81. # https://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?print=1
  82. # aabb should have the attributes of P, E as center point and extents
  83. mid = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2] # mid point
  84. I = [(p1[0] - p0[0]) / dist, (p1[1] - p0[1]) / dist, (p1[2] - p0[2]) / dist] # unit direction
  85. hl = dist / 2 # radius
  86. P = aabb.P # center of the AABB
  87. E = aabb.E # extents of AABB
  88. T = [P[0] - mid[0], P[1] - mid[1], P[2] - mid[2]]
  89. # do any of the principal axis form a separting axis?
  90. if abs(T[0]) > (E[0] + hl * abs(I[0])): return False
  91. if abs(T[1]) > (E[1] + hl * abs(I[1])): return False
  92. if abs(T[2]) > (E[2] + hl * abs(I[2])): return False
  93. # I.cross(x axis) ?
  94. r = E[1] * abs(I[2]) + E[2] * abs(I[1])
  95. if abs(T[1] * I[2] - T[2] * I[1]) > r: return False
  96. # I.cross(y axis) ?
  97. r = E[0] * abs(I[2]) + E[2] * abs(I[0])
  98. if abs(T[2] * I[0] - T[0] * I[2]) > r: return False
  99. # I.cross(z axis) ?
  100. r = E[0] * abs(I[1]) + E[1] * abs(I[0])
  101. if abs(T[0] * I[1] - T[1] * I[0]) > r: return False
  102. return True
  103. def lineOBB(p0, p1, dist, obb):
  104. T = np.vstack([np.column_stack([obb.O.T,-obb.O.T@obb.P]),[0,0,0,1]])
  105. p0 = T@np.append(p0,1) # transform the points to the box
  106. p1 = T@np.append(p1,1)
  107. return lineAABB(p0[0:3],p1[0:3],dist,obb)
  108. def OBBOBB(obb1, obb2):
  109. # https://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?print=1
  110. # each obb class should contain attributes:
  111. # E: extents along three principle axis in R3
  112. # P: position of the center axis in R3
  113. # O: orthornormal basis in R3*3
  114. a , b = np.array(obb1.E), np.array(obb2.E)
  115. Pa, Pb = np.array(obb1.P), np.array(obb2.P)
  116. A , B = np.array(obb1.O), np.array(obb2.O)
  117. # check if two oriented bounding boxes overlap
  118. # translation, in parent frame
  119. v = Pb - Pa
  120. # translation, in A's frame
  121. # vdotA[0],vdotA[1],vdotA[2]
  122. T = [v@B[0], v@B[1], v@B[2]]
  123. R = np.zeros([3,3])
  124. for i in range(0,3):
  125. for k in range(0,3):
  126. R[i][k] = A[i]@B[k]
  127. # use separating axis thm for all 15 separating axes
  128. # if the separating axis cannot be found, then overlap
  129. # A's basis vector
  130. for i in range(0,3):
  131. ra = a[i]
  132. rb = b[0]*abs(R[i][0]) + b[1]*abs(R[i][1]) + b[2]*abs(R[i][2])
  133. t = abs(T[i])
  134. if t > ra + rb:
  135. return False
  136. for k in range(0,3):
  137. ra = a[0]*abs(R[0][k]) + a[1]*abs(R[1][k]) + a[2]*abs(R[2][k])
  138. rb = b[k]
  139. t = abs(T[0]*R[0][k] + T[1]*R[1][k] + T[2]*R[2][k])
  140. if t > ra + rb:
  141. return False
  142. #9 cross products
  143. #L = A0 x B0
  144. ra = a[1]*abs(R[2][0]) + a[2]*abs(R[1][0])
  145. rb = b[1]*abs(R[0][2]) + b[2]*abs(R[0][1])
  146. t = abs(T[2]*R[1][0] - T[1]*R[2][0])
  147. if t > ra + rb:
  148. return False
  149. #L = A0 x B1
  150. ra = a[1]*abs(R[2][1]) + a[2]*abs(R[1][1])
  151. rb = b[0]*abs(R[0][2]) + b[2]*abs(R[0][0])
  152. t = abs(T[2]*R[1][1] - T[1]*R[2][1])
  153. if t > ra + rb:
  154. return False
  155. #L = A0 x B2
  156. ra = a[1]*abs(R[2][2]) + a[2]*abs(R[1][2])
  157. rb = b[0]*abs(R[0][1]) + b[1]*abs(R[0][0])
  158. t = abs(T[2]*R[1][2] - T[1]*R[2][2])
  159. if t > ra + rb:
  160. return False
  161. #L = A1 x B0
  162. ra = a[0]*abs(R[2][0]) + a[2]*abs(R[0][0])
  163. rb = b[1]*abs(R[1][2]) + b[2]*abs(R[1][1])
  164. t = abs( T[0]*R[2][0] - T[2]*R[0][0] )
  165. if t > ra + rb:
  166. return False
  167. # L = A1 x B1
  168. ra = a[0]*abs(R[2][1]) + a[2]*abs(R[0][1])
  169. rb = b[0]*abs(R[1][2]) + b[2]*abs(R[1][0])
  170. t = abs( T[0]*R[2][1] - T[2]*R[0][1] )
  171. if t > ra + rb:
  172. return False
  173. #L = A1 x B2
  174. ra = a[0]*abs(R[2][2]) + a[2]*abs(R[0][2])
  175. rb = b[0]*abs(R[1][1]) + b[1]*abs(R[1][0])
  176. t = abs( T[0]*R[2][2] - T[2]*R[0][2] )
  177. if t > ra + rb:
  178. return False
  179. #L = A2 x B0
  180. ra = a[0]*abs(R[1][0]) + a[1]*abs(R[0][0])
  181. rb = b[1]*abs(R[2][2]) + b[2]*abs(R[2][1])
  182. t = abs( T[1]*R[0][0] - T[0]*R[1][0] )
  183. if t > ra + rb:
  184. return False
  185. # L = A2 x B1
  186. ra = a[0]*abs(R[1][1]) + a[1]*abs(R[0][1])
  187. rb = b[0] *abs(R[2][2]) + b[2]*abs(R[2][0])
  188. t = abs( T[1]*R[0][1] - T[0]*R[1][1] )
  189. if t > ra + rb:
  190. return False
  191. #L = A2 x B2
  192. ra = a[0]*abs(R[1][2]) + a[1]*abs(R[0][2])
  193. rb = b[0]*abs(R[2][1]) + b[1]*abs(R[2][0])
  194. t = abs( T[1]*R[0][2] - T[0]*R[1][2] )
  195. if t > ra + rb:
  196. return False
  197. # no separating axis found,
  198. # the two boxes overlap
  199. return True
  200. def StateSpace(env, factor=0):
  201. boundary = env.boundary
  202. resolution = env.resolution
  203. xmin, xmax = boundary[0] + factor * resolution, boundary[3] - factor * resolution
  204. ymin, ymax = boundary[1] + factor * resolution, boundary[4] - factor * resolution
  205. zmin, zmax = boundary[2] + factor * resolution, boundary[5] - factor * resolution
  206. xarr = np.arange(xmin, xmax, resolution).astype(float)
  207. yarr = np.arange(ymin, ymax, resolution).astype(float)
  208. zarr = np.arange(zmin, zmax, resolution).astype(float)
  209. Space = set()
  210. for x in xarr:
  211. for y in yarr:
  212. for z in zarr:
  213. Space.add((x, y, z))
  214. return Space
  215. def g_Space(initparams):
  216. '''This function is used to get nodes and discretize the space.
  217. State space is by x*y*z,3 where each 3 is a point in 3D.'''
  218. g = {}
  219. Space = StateSpace(initparams.env)
  220. for v in Space:
  221. g[v] = np.inf # this hashmap initialize all g values at inf
  222. return g
  223. def isCollide(initparams, x, child, dist):
  224. '''see if line intersects obstacle'''
  225. '''specified for expansion in A* 3D lookup table'''
  226. if dist==None:
  227. dist = getDist(x, child)
  228. # check in bound
  229. if not isinbound(initparams.env.boundary, child):
  230. return True, dist
  231. # check collision in AABB
  232. for i in range(len(initparams.env.AABB)):
  233. if lineAABB(x, child, dist, initparams.env.AABB[i]):
  234. return True, dist
  235. # check collision in ball
  236. for i in initparams.env.balls:
  237. if lineSphere(x, child, i):
  238. return True, dist
  239. # check collision with obb
  240. for i in initparams.env.OBB:
  241. if lineOBB(x, child, dist, i):
  242. return True, dist
  243. return False, dist
  244. def children(initparams, x, settings = 0):
  245. # get the neighbor of a specific state
  246. allchild = []
  247. allcost = []
  248. resolution = initparams.env.resolution
  249. for direc in initparams.Alldirec:
  250. child = tuple(map(np.add, x, np.multiply(direc, resolution)))
  251. if any([isinobb(i, child) for i in initparams.env.OBB]):
  252. continue
  253. if any([isinball(i ,child) for i in initparams.env.balls]):
  254. continue
  255. if any([isinbound(i ,child) for i in initparams.env.blocks]):
  256. continue
  257. if isinbound(initparams.env.boundary, child):
  258. allchild.append(child)
  259. allcost.append((child,initparams.Alldirec[direc]*resolution))
  260. if settings == 0:
  261. return allchild
  262. if settings == 1:
  263. return allcost
  264. def obstacleFree(initparams, x):
  265. for i in initparams.env.blocks:
  266. if isinbound(i, x):
  267. return False
  268. for i in initparams.env.balls:
  269. if isinball(i, x):
  270. return False
  271. return True
  272. def cost(initparams, i, j, dist=None, settings='Euclidean'):
  273. collide, dist = isCollide(initparams, i, j, dist)
  274. # collide, dist= False, getDist(i, j)
  275. if settings == 'Euclidean':
  276. if collide:
  277. return np.inf
  278. else:
  279. return dist
  280. if settings == 'Manhattan':
  281. if collide:
  282. return np.inf
  283. else:
  284. return getManDist(i, j)
  285. def initcost(initparams):
  286. # initialize cost dictionary, could be modifed lateron
  287. c = defaultdict(lambda: defaultdict(dict)) # two key dicionary
  288. for xi in initparams.X:
  289. cdren = children(initparams, xi)
  290. for child in cdren:
  291. c[xi][child] = cost(initparams, xi, child)
  292. return c
  293. if __name__ == "__main__":
  294. pass
  295. # obb1 = obb([0,0,0],[1,1,1],[[1,0,0],[0,1,0],[0,0,1]])
  296. # obb2 = obb([1,1,0],[1,1,1],[[1/np.sqrt(3)*1,1/np.sqrt(3)*1,1/np.sqrt(3)*1],[np.sqrt(3/2)*(-1/3),np.sqrt(3/2)*2/3,np.sqrt(3/2)*(-1/3)],[np.sqrt(1/8)*(-2),0,np.sqrt(1/8)*2]])
  297. # print(OBBOBB(obb1, obb2))