models.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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.core.urlresolvers import reverse
  11. from django.utils.encoding import python_2_unicode_compatible
  12. from .tasks import generate_tiles
  13. EARTH_RADIUS = 6371009
  14. class Point(models.Model):
  15. """Geographical point, with altitude."""
  16. latitude = models.FloatField(verbose_name="latitude", help_text="In degrees",
  17. validators=[MinValueValidator(-90),
  18. MaxValueValidator(90)])
  19. longitude = models.FloatField(verbose_name="longitude", help_text="In degrees",
  20. validators=[MinValueValidator(-180),
  21. MaxValueValidator(180)])
  22. altitude = models.FloatField(verbose_name="altitude", help_text="In meters",
  23. validators=[MinValueValidator(0.)])
  24. @property
  25. def latitude_rad(self):
  26. return radians(self.latitude)
  27. @property
  28. def longitude_rad(self):
  29. return radians(self.longitude)
  30. @property
  31. def altitude_abs(self):
  32. """Absolute distance to the center of Earth (in a spherical model)"""
  33. return EARTH_RADIUS + self.altitude
  34. def great_angle(self, other):
  35. """Returns the great angle, in radians, between the two given points. The
  36. great angle is the angle formed by the two points when viewed from
  37. the center of the Earth.
  38. """
  39. lon_delta = other.longitude_rad - self.longitude_rad
  40. a = (cos(other.latitude_rad) * sin(lon_delta)) ** 2 \
  41. + (cos(self.latitude_rad) * sin(other.latitude_rad) \
  42. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)) ** 2
  43. b = sin(self.latitude_rad) * sin(other.latitude_rad) \
  44. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)
  45. angle = atan2(sqrt(a), b)
  46. return angle
  47. def great_circle_distance(self, other):
  48. """Returns the great circle distance between two points, without taking
  49. into account their altitude. Don't use this to compute
  50. line-of-sight distance, see [line_distance] instead.
  51. """
  52. return EARTH_RADIUS * self.great_angle(other)
  53. def line_distance(self, other):
  54. """Distance of the straight line between two points on Earth, in meters.
  55. Note that this is only useful because we are considering
  56. line-of-sight links, where straight-line distance is the relevant
  57. distance. For arbitrary points on Earth, great-circle distance
  58. would most likely be preferred.
  59. """
  60. delta_lon = other.longitude_rad - self.longitude_rad
  61. # Cosine of the angle between the two points on their great circle.
  62. cos_angle = sin(self.latitude_rad) * sin(other.latitude_rad) \
  63. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  64. # Al-Kashi formula
  65. return sqrt(self.altitude_abs ** 2 \
  66. + other.altitude_abs ** 2 \
  67. - 2 * self.altitude_abs * other.altitude_abs * cos_angle)
  68. def bearing(self, other):
  69. """Bearing, in degrees, between this point and another point."""
  70. delta_lon = other.longitude_rad - self.longitude_rad
  71. y = sin(delta_lon) * cos(other.latitude_rad)
  72. x = cos(self.latitude_rad) * sin(other.latitude_rad) \
  73. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  74. return degrees(atan2(y, x))
  75. def elevation(self, other):
  76. """Elevation, in degrees, between this point and another point."""
  77. d = self.line_distance(other)
  78. sin_elev = (other.altitude_abs ** 2 - self.altitude_abs ** 2 - d ** 2) \
  79. / (2 * self.altitude_abs * d)
  80. return degrees(asin(sin_elev))
  81. class Meta:
  82. abstract = True
  83. @python_2_unicode_compatible
  84. class ReferencePoint(Point):
  85. """Reference point, to be used"""
  86. name = models.CharField(verbose_name="name", max_length=255,
  87. help_text="Name of the point")
  88. def __str__(self):
  89. return "Reference point : " + self.name
  90. @python_2_unicode_compatible
  91. class Panorama(ReferencePoint):
  92. loop = models.BooleanField(default=False, verbose_name="360° panorama",
  93. help_text="Whether the panorama loops around the edges")
  94. image = models.ImageField(verbose_name="image", upload_to="pano",
  95. width_field="image_width",
  96. height_field="image_height")
  97. image_width = models.PositiveIntegerField(default=0)
  98. image_height = models.PositiveIntegerField(default=0)
  99. # Set of references, i.e. reference points with information on how
  100. # they relate to this panorama.
  101. references = models.ManyToManyField(ReferencePoint, through='Reference',
  102. related_name="referenced_panorama")
  103. def tiles_dir(self):
  104. return os.path.join(settings.MEDIA_ROOT, settings.PANORAMA_TILES_DIR,
  105. str(self.pk))
  106. def tiles_url(self):
  107. return os.path.join(settings.MEDIA_URL, settings.PANORAMA_TILES_DIR,
  108. str(self.pk))
  109. def generate_tiles(self):
  110. try:
  111. os.makedirs(self.tiles_dir())
  112. except OSError:
  113. pass
  114. generate_tiles.delay(self.image.path, self.tiles_dir())
  115. def get_absolute_url(self):
  116. return reverse('panorama:view_pano', args=[str(self.pk)])
  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))