models.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals, division, print_function
  3. import subprocess
  4. import os
  5. from math import radians, degrees, sin, cos, asin, atan2, sqrt
  6. from django.db import models
  7. from django.conf import settings
  8. from django.core.exceptions import ValidationError
  9. from django.core.validators import MinValueValidator, MaxValueValidator
  10. from django.utils.encoding import python_2_unicode_compatible
  11. EARTH_RADIUS = 6371009
  12. class Point(models.Model):
  13. """Geographical point, with altitude."""
  14. latitude = models.FloatField(verbose_name="latitude", help_text="In degrees",
  15. validators=[MinValueValidator(-90),
  16. MaxValueValidator(90)])
  17. longitude = models.FloatField(verbose_name="longitude", help_text="In degrees",
  18. validators=[MinValueValidator(-180),
  19. MaxValueValidator(180)])
  20. altitude = models.FloatField(verbose_name="altitude", help_text="In meters",
  21. validators=[MinValueValidator(0.)])
  22. @property
  23. def latitude_rad(self):
  24. return radians(self.latitude)
  25. @property
  26. def longitude_rad(self):
  27. return radians(self.longitude)
  28. @property
  29. def altitude_abs(self):
  30. """Absolute distance to the center of Earth (in a spherical model)"""
  31. return EARTH_RADIUS + self.altitude
  32. def great_angle(self, other):
  33. """Returns the great angle, in radians, between the two given points. The
  34. great angle is the angle formed by the two points when viewed from
  35. the center of the Earth.
  36. """
  37. lon_delta = other.longitude_rad - self.longitude_rad
  38. a = (cos(other.latitude_rad) * sin(lon_delta)) ** 2 \
  39. + (cos(self.latitude_rad) * sin(other.latitude_rad) \
  40. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)) ** 2
  41. b = sin(self.latitude_rad) * sin(other.latitude_rad) \
  42. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)
  43. angle = atan2(sqrt(a), b)
  44. return angle
  45. def great_circle_distance(self, other):
  46. """Returns the great circle distance between two points, without taking
  47. into account their altitude. Don't use this to compute
  48. line-of-sight distance, see [line_distance] instead.
  49. """
  50. return EARTH_RADIUS * self.great_angle(other)
  51. def line_distance(self, other):
  52. """Distance of the straight line between two points on Earth, in meters.
  53. Note that this is only useful because we are considering
  54. line-of-sight links, where straight-line distance is the relevant
  55. distance. For arbitrary points on Earth, great-circle distance
  56. would most likely be preferred.
  57. """
  58. delta_lon = other.longitude_rad - self.longitude_rad
  59. # Cosine of the angle between the two points on their great circle.
  60. cos_angle = sin(self.latitude_rad) * sin(other.latitude_rad) \
  61. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  62. # Al-Kashi formula
  63. return sqrt(self.altitude_abs ** 2 \
  64. + other.altitude_abs ** 2 \
  65. - 2 * self.altitude_abs * other.altitude_abs * cos_angle)
  66. def bearing(self, other):
  67. """Bearing, in degrees, between this point and another point."""
  68. delta_lon = other.longitude_rad - self.longitude_rad
  69. y = sin(delta_lon) * cos(other.latitude_rad)
  70. x = cos(self.latitude_rad) * sin(other.latitude_rad) \
  71. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  72. return degrees(atan2(y, x))
  73. def elevation(self, other):
  74. """Elevation, in degrees, between this point and another point."""
  75. d = self.line_distance(other)
  76. sin_elev = (other.altitude_abs ** 2 - self.altitude_abs ** 2 - d ** 2) \
  77. / (2 * self.altitude_abs * d)
  78. return degrees(asin(sin_elev))
  79. class Meta:
  80. abstract = True
  81. @python_2_unicode_compatible
  82. class ReferencePoint(Point):
  83. """Reference point, to be used"""
  84. name = models.CharField(verbose_name="name", max_length=255,
  85. help_text="Name of the point")
  86. def __str__(self):
  87. return "Reference point : " + self.name
  88. @python_2_unicode_compatible
  89. class Panorama(ReferencePoint):
  90. loop = models.BooleanField(default=False, verbose_name="360° panorama",
  91. help_text="Whether the panorama loops around the edges")
  92. image = models.ImageField(verbose_name="image", upload_to="pano",
  93. width_field="image_width",
  94. height_field="image_height")
  95. image_width = models.PositiveIntegerField(default=0)
  96. image_height = models.PositiveIntegerField(default=0)
  97. # Set of references, i.e. reference points with information on how
  98. # they relate to this panorama.
  99. references = models.ManyToManyField(ReferencePoint, through='Reference',
  100. related_name="referenced_panorama")
  101. def tiles_dir(self):
  102. return os.path.join(settings.MEDIA_ROOT, settings.PANORAMA_TILES_DIR,
  103. str(self.pk))
  104. def tiles_url(self):
  105. return os.path.join(settings.MEDIA_URL, settings.PANORAMA_TILES_DIR,
  106. str(self.pk))
  107. def generate_tiles(self):
  108. # The trailing slash is necessary for the shell script.
  109. tiles_dir = self.tiles_dir() + "/"
  110. try:
  111. os.makedirs(tiles_dir)
  112. except OSError:
  113. pass
  114. script = os.path.join(settings.BASE_DIR, "panorama", "gen_tiles.sh")
  115. ret = subprocess.call([script, "-p", tiles_dir, self.image.path])
  116. return ret
  117. def __str__(self):
  118. return "Panorama : " + self.name
  119. class Reference(models.Model):
  120. """A reference is made of a Panorama, a Reference Point, and the position
  121. (x, y) of the reference point inside the image. With enough
  122. references, the panorama is calibrated. That is, we can build a
  123. mapping between pixels of the image and directions in 3D space, which
  124. are represented by (azimuth, elevation) couples."""
  125. # Components of the ManyToMany relation
  126. reference_point = models.ForeignKey(ReferencePoint, related_name="refpoint_references")
  127. panorama = models.ForeignKey(Panorama, related_name="panorama_references")
  128. # Position of the reference point in the panorama image
  129. x = models.PositiveIntegerField()
  130. y = models.PositiveIntegerField()
  131. class Meta:
  132. # It makes no sense to have multiple references of the same
  133. # reference point on a given panorama.
  134. unique_together = (("reference_point", "panorama"),)
  135. def clean(self):
  136. # Check that the reference point and the panorama are different
  137. # (remember that panoramas can *also* be seen as reference points)
  138. if self.panorama.pk == self.reference_point.pk:
  139. raise ValidationError("A panorama can't reference itself.")
  140. # Check than the position is within the bounds of the image.
  141. w = self.panorama.image_width
  142. h = self.panorama.image_height
  143. if self.x >= w or self.y >= h:
  144. raise ValidationError("Position ({x}, {y}) is outside the bounds "
  145. "of the image ({width}, {height}).".format(
  146. x=self.x,
  147. y=self.y,
  148. width=w,
  149. height=h))