utils3D.py 12 KB

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