models.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals, division, print_function
  3. import os
  4. from math import radians, degrees, sin, cos, asin, atan2, sqrt, ceil
  5. from django.db import models
  6. from django.conf import settings
  7. from django.core.exceptions import ValidationError
  8. from django.core.validators import MinValueValidator, MaxValueValidator
  9. from django.core.urlresolvers import reverse
  10. from django.utils.encoding import python_2_unicode_compatible
  11. from django.utils.translation import ugettext_lazy as _
  12. from .tasks import generate_tiles
  13. from .utils import makedirs, path_exists
  14. EARTH_RADIUS = 6371009
  15. class Point(models.Model):
  16. """Geographical point, with altitude."""
  17. latitude = models.FloatField(verbose_name=_("latitude"), help_text=_("In degrees"),
  18. validators=[MinValueValidator(-90),
  19. MaxValueValidator(90)])
  20. longitude = models.FloatField(verbose_name=_("longitude"), help_text=_("In degrees"),
  21. validators=[MinValueValidator(-180),
  22. MaxValueValidator(180)])
  23. ground_altitude = models.FloatField(verbose_name=_("altitude at ground level"),
  24. help_text=_("In meters"),
  25. validators=[MinValueValidator(0.)])
  26. height_above_ground = models.FloatField(verbose_name=_("height above ground"),
  27. help_text=_("In meters"),
  28. default=0.)
  29. @property
  30. def altitude(self):
  31. return self.ground_altitude + self.height_above_ground
  32. @property
  33. def latitude_rad(self):
  34. return radians(self.latitude)
  35. @property
  36. def longitude_rad(self):
  37. return radians(self.longitude)
  38. @property
  39. def altitude_abs(self):
  40. """Absolute distance to the center of Earth (in a spherical model)"""
  41. return EARTH_RADIUS + self.altitude
  42. def great_angle(self, other):
  43. """Returns the great angle, in radians, between the two given points. The
  44. great angle is the angle formed by the two points when viewed from
  45. the center of the Earth.
  46. """
  47. lon_delta = other.longitude_rad - self.longitude_rad
  48. a = (cos(other.latitude_rad) * sin(lon_delta)) ** 2 \
  49. + (cos(self.latitude_rad) * sin(other.latitude_rad) \
  50. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)) ** 2
  51. b = sin(self.latitude_rad) * sin(other.latitude_rad) \
  52. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)
  53. angle = atan2(sqrt(a), b)
  54. return angle
  55. def great_circle_distance(self, other):
  56. """Returns the great circle distance between two points, without taking
  57. into account their altitude. Don't use this to compute
  58. line-of-sight distance, see [line_distance] instead.
  59. """
  60. return EARTH_RADIUS * self.great_angle(other)
  61. def line_distance(self, other):
  62. """Distance of the straight line between two points on Earth, in meters.
  63. Note that this is only useful because we are considering
  64. line-of-sight links, where straight-line distance is the relevant
  65. distance. For arbitrary points on Earth, great-circle distance
  66. would most likely be preferred.
  67. """
  68. delta_lon = other.longitude_rad - self.longitude_rad
  69. # Cosine of the angle between the two points on their great circle.
  70. cos_angle = sin(self.latitude_rad) * sin(other.latitude_rad) \
  71. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  72. # Al-Kashi formula
  73. return sqrt(self.altitude_abs ** 2 \
  74. + other.altitude_abs ** 2 \
  75. - 2 * self.altitude_abs * other.altitude_abs * cos_angle)
  76. def bearing(self, other):
  77. """Bearing, in degrees, between this point and another point."""
  78. delta_lon = other.longitude_rad - self.longitude_rad
  79. y = sin(delta_lon) * cos(other.latitude_rad)
  80. x = cos(self.latitude_rad) * sin(other.latitude_rad) \
  81. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  82. return degrees(atan2(y, x))
  83. def elevation(self, other):
  84. """Elevation, in degrees, between this point and another point."""
  85. d = self.line_distance(other)
  86. sin_elev = (other.altitude_abs ** 2 - self.altitude_abs ** 2 - d ** 2) \
  87. / (2 * self.altitude_abs * d)
  88. # Ensure the value belongs to [-1, 1], which might not be the case because of float rouding
  89. sin_elev = max(min(sin_elev, 1), -1)
  90. return degrees(asin(sin_elev))
  91. class Meta:
  92. abstract = True
  93. @python_2_unicode_compatible
  94. class ReferencePoint(Point):
  95. """Reference point, to be used"""
  96. name = models.CharField(verbose_name=_("name"), max_length=255,
  97. help_text=_("Name of the point"))
  98. KIND_OTHER = 'other'
  99. KIND_SUBSCRIBER = 'subscriber'
  100. KIND_WAITING = 'waiting'
  101. KIND_CHOICES = (
  102. (KIND_WAITING, _('waiting')),
  103. (KIND_SUBSCRIBER, _('subscriber')),
  104. (KIND_OTHER, _('other')),
  105. )
  106. kind = models.CharField(verbose_name=_('kind'), max_length=255,
  107. choices=KIND_CHOICES, default=KIND_WAITING)
  108. def __str__(self):
  109. return self.name
  110. class Meta:
  111. verbose_name = _("reference point")
  112. verbose_name_plural = _("reference points")
  113. class Panorama(ReferencePoint):
  114. loop = models.BooleanField(default=False, verbose_name=_("360° panorama"),
  115. help_text=_("Whether the panorama loops around the edges"))
  116. image = models.ImageField(verbose_name=_("image"), upload_to="pano",
  117. width_field="image_width",
  118. height_field="image_height")
  119. image_width = models.PositiveIntegerField(default=0, verbose_name=_("image width"))
  120. image_height = models.PositiveIntegerField(default=0, verbose_name=_("image height"))
  121. # Set of references, i.e. reference points with information on how
  122. # they relate to this panorama.
  123. references = models.ManyToManyField(ReferencePoint, through='Reference',
  124. related_name="referenced_panorama",
  125. verbose_name=_("references"))
  126. def tiles_dir(self):
  127. return os.path.join(settings.MEDIA_ROOT, settings.PANORAMA_TILES_DIR,
  128. str(self.pk))
  129. def tiles_url(self):
  130. return os.path.join(settings.MEDIA_URL, settings.PANORAMA_TILES_DIR,
  131. str(self.pk))
  132. def has_tiles(self):
  133. return path_exists(self.tiles_dir()) and len(os.listdir(self.tiles_dir())) > 0
  134. has_tiles.boolean = True
  135. has_tiles.short_description = _("Tiles available?")
  136. def delete_tiles(self):
  137. """Delete all tiles and the tiles dir"""
  138. # If the directory doesn't exist, do nothing
  139. if not path_exists(self.tiles_dir()):
  140. return
  141. # Delete all tiles
  142. for filename in os.listdir(self.tiles_dir()):
  143. os.unlink(os.path.join(self.tiles_dir(), filename))
  144. os.rmdir(self.tiles_dir())
  145. def generate_tiles(self):
  146. makedirs(self.tiles_dir(), exist_ok=True)
  147. generate_tiles.delay(self.image.path, self.tiles_dir())
  148. def get_absolute_url(self, cap=None, ele=None, zoom=None):
  149. base_url = reverse('panorama:view_pano', args=[str(self.pk)])
  150. # Add parameters to point to the given direction, interpreted by
  151. # the js frontend
  152. if zoom is None:
  153. zoom = 0
  154. if not None in (zoom, cap, ele):
  155. return base_url + "#zoom={}/cap={}/ele={}".format(zoom, cap, ele)
  156. else:
  157. return base_url
  158. def tiles_data(self):
  159. """Hack to feed the current js code with tiles data (we should use the
  160. JSON API instead, and get rid of this function)"""
  161. data = dict()
  162. for zoomlevel in range(9):
  163. width = self.image_width >> zoomlevel
  164. height = self.image_height >> zoomlevel
  165. d = dict()
  166. d["tile_width"] = d["tile_height"] = 256
  167. # Python3-style division
  168. d["ntiles_x"] = int(ceil(width / 256))
  169. d["ntiles_y"] = int(ceil(height / 256))
  170. d["last_tile_width"] = width % 256
  171. d["last_tile_height"] = height % 256
  172. data[zoomlevel] = d
  173. return data
  174. def refpoints_data(self):
  175. """Similar hack, returns all reference points around the panorama."""
  176. def get_url(refpoint):
  177. """If the refpoint is also a panorama, returns its canonical URL"""
  178. if hasattr(refpoint, "panorama"):
  179. # Point towards the current panorama
  180. return refpoint.panorama.get_absolute_url(refpoint.bearing(self),
  181. refpoint.elevation(self))
  182. else:
  183. return ""
  184. refpoints = [refpoint for refpoint in ReferencePoint.objects.all()
  185. if self.great_circle_distance(refpoint) <= settings.PANORAMA_MAX_DISTANCE and refpoint.pk != self.pk]
  186. refpoints.sort(key=lambda r: r.name)
  187. return enumerate([{"id": r.pk,
  188. "name": r.name,
  189. "url": get_url(r),
  190. "cap": self.bearing(r),
  191. "elevation": self.elevation(r),
  192. "elevation_ground": self.elevation(Point(latitude=r.latitude, longitude=r.longitude, ground_altitude=r.ground_altitude, height_above_ground=0)),
  193. "distance": self.line_distance(r)}
  194. for r in refpoints])
  195. def references_data(self):
  196. """Similar hack, returns all references currently associated to the
  197. panorama."""
  198. return [{"id": r.pk,
  199. "name": r.reference_point.name,
  200. # Adapt to js-based coordinates (x between 0 and 1, y
  201. # between -0.5 and 0.5)
  202. "x": r.x / r.panorama.image_width,
  203. "y": (r.y / r.panorama.image_height) - 0.5,
  204. "cap": self.bearing(r.reference_point),
  205. "elevation": self.elevation(r.reference_point)}
  206. for r in self.panorama_references.all()]
  207. def is_visible(self, point):
  208. """Return True if the Panorama can see the point."""
  209. if self.great_circle_distance(point) > settings.PANORAMA_MAX_DISTANCE:
  210. return False
  211. if self.loop:
  212. return True
  213. cap = self.bearing(point) % 360
  214. cap_min = self.cap_min()
  215. cap_max = self.cap_max()
  216. # Not enough references
  217. if cap_min is None or cap_max is None:
  218. return False
  219. if cap_min < cap_max:
  220. # Nominal case
  221. return cap_min <= cap <= cap_max
  222. else:
  223. return cap_min <= cap or cap <= cap_max
  224. def cap_min(self):
  225. return self._cap_minmax(True)
  226. def cap_max(self):
  227. return self._cap_minmax(False)
  228. def _cap_minmax(self, ismin=True):
  229. """Return the cap on the border of the image.
  230. :param ismin: True if the min cap should be processed False if it is the
  231. max.
  232. @return None if the image is looping or if the image have less than two
  233. references.
  234. """
  235. if self.loop:
  236. return None
  237. it = self.panorama_references.order_by(
  238. 'x' if ismin else '-x').iterator()
  239. try:
  240. ref1 = next(it)
  241. ref2 = next(it)
  242. except StopIteration:
  243. return None
  244. cap1 = self.bearing(ref1.reference_point)
  245. cap2 = self.bearing(ref2.reference_point)
  246. target_x = 0 if ismin else self.image_width
  247. # For circulary issues
  248. if ismin and cap2 < cap1:
  249. cap2 += 360
  250. if (not ismin) and cap1 < cap2:
  251. cap1 += 360
  252. target_cap = cap1 + (target_x - ref1.x) * (cap2 - cap1) / \
  253. (ref2.x - ref1.x)
  254. return target_cap % 360
  255. class Meta:
  256. verbose_name = _("panorama")
  257. verbose_name_plural = _("panoramas")
  258. @python_2_unicode_compatible
  259. class Reference(models.Model):
  260. """A reference is made of a Panorama, a Reference Point, and the position
  261. (x, y) of the reference point inside the image. With enough
  262. references, the panorama is calibrated. That is, we can build a
  263. mapping between pixels of the image and directions in 3D space, which
  264. are represented by (azimuth, elevation) couples."""
  265. # Components of the ManyToMany relation
  266. reference_point = models.ForeignKey(ReferencePoint, related_name="refpoint_references",
  267. verbose_name=_("reference point"))
  268. panorama = models.ForeignKey(Panorama, related_name="panorama_references",
  269. verbose_name=_("panorama"))
  270. # Position of the reference point in the panorama image
  271. x = models.PositiveIntegerField()
  272. y = models.PositiveIntegerField()
  273. class Meta:
  274. # It makes no sense to have multiple references of the same
  275. # reference point on a given panorama.
  276. unique_together = (("reference_point", "panorama"),)
  277. verbose_name = _("reference")
  278. verbose_name_plural = _("references")
  279. def clean(self):
  280. # Check that the reference point and the panorama are different
  281. # (remember that panoramas can *also* be seen as reference points)
  282. if self.panorama.pk == self.reference_point.pk:
  283. raise ValidationError(_("A panorama can't reference itself."))
  284. # Check than the position is within the bounds of the image.
  285. w = self.panorama.image_width
  286. h = self.panorama.image_height
  287. if self.x >= w or self.y >= h:
  288. raise ValidationError(_("Position {xy} is outside the bounds "
  289. "of the image ({width}, {height}).").format(
  290. xy=(self.x, self.y),
  291. width=w,
  292. height=h))
  293. def __str__(self):
  294. return _('{refpoint} at {xy} in {pano}').format(
  295. pano=self.panorama.name,
  296. xy=(self.x, self.y),
  297. refpoint=self.reference_point.name,
  298. )