|
| 1 | +""" |
| 2 | +Module for rendering a scene with respect to a geometry. |
| 3 | +The data is rendered first and filters may be applied afterwards. |
| 4 | +""" |
| 5 | + |
| 6 | +from typing import Optional, NewType |
| 7 | + |
| 8 | +from abc import ABC, abstractmethod |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +from PIL import Image |
| 12 | + |
| 13 | +from nerte.values.color import Color, Colors |
| 14 | +from nerte.values.intersection_info import IntersectionInfo, IntersectionInfos |
| 15 | +from nerte.world.camera import Camera |
| 16 | +from nerte.world.object import Object |
| 17 | +from nerte.world.scene import Scene |
| 18 | +from nerte.geometry.geometry import Geometry |
| 19 | +from nerte.render.image_renderer import ImageRenderer |
| 20 | +from nerte.render.projection import ProjectionMode |
| 21 | + |
| 22 | +# TODO: provide proper container type |
| 23 | +IntersectionInfoMatrix = NewType( |
| 24 | + "IntersectionInfoMatrix", list[list[IntersectionInfo]] |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +def color_for_normalized_value(value: float) -> Color: |
| 29 | + """ |
| 30 | + Returns color assosiated with a value from 0.0 to 1.0 value. |
| 31 | + """ |
| 32 | + if not 0.0 <= value <= 1.0: |
| 33 | + raise ValueError( |
| 34 | + f"Cannot obtain color from normalized value {value}." |
| 35 | + f" Value must be between 0.0 and 1.0 inf or nan." |
| 36 | + ) |
| 37 | + level = int(value * 255) |
| 38 | + return Color(level, level, level) |
| 39 | + |
| 40 | + |
| 41 | +def color_miss_reason(miss_reason: IntersectionInfo.MissReason) -> Color: |
| 42 | + """ |
| 43 | + Returns a color for a pixel to denote a ray failing to hit a surface. |
| 44 | + """ |
| 45 | + if miss_reason is IntersectionInfo.MissReason.UNINIALIZED: |
| 46 | + return Color(0, 0, 0) |
| 47 | + if miss_reason is IntersectionInfo.MissReason.NO_INTERSECTION: |
| 48 | + return Color(0, 0, 255) |
| 49 | + if miss_reason is IntersectionInfo.MissReason.RAY_LEFT_MANIFOLD: |
| 50 | + return Color(0, 255, 0) |
| 51 | + if ( |
| 52 | + miss_reason |
| 53 | + is IntersectionInfo.MissReason.RAY_INITIALIZED_OUTSIDE_MANIFOLD |
| 54 | + ): |
| 55 | + return Color(255, 255, 0) |
| 56 | + raise NotImplementedError( |
| 57 | + f"Cannot pick color for miss reason {miss_reason}." |
| 58 | + f"No color was implemented." |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | +class Filter(ABC): |
| 63 | + # pylint: disable=R0903 |
| 64 | + """ |
| 65 | + Interface for filters which convert the raw intersctio information of a |
| 66 | + ray into a color |
| 67 | + .""" |
| 68 | + |
| 69 | + @abstractmethod |
| 70 | + def apply( |
| 71 | + self, |
| 72 | + info_matrix: IntersectionInfoMatrix, |
| 73 | + ) -> Image: |
| 74 | + """ |
| 75 | + Returns color for pixel based. |
| 76 | +
|
| 77 | + WARNING: Results are only valid if analyze was run first. |
| 78 | + """ |
| 79 | + # pylint: disable=W0107 |
| 80 | + pass |
| 81 | + |
| 82 | + |
| 83 | +class HitFilter(Filter): |
| 84 | + """ |
| 85 | + False color filter for displaying rays based on whether they hit a surface |
| 86 | + or missed it. |
| 87 | +
|
| 88 | + The details about the miss are encoded into (unique) colors. |
| 89 | + """ |
| 90 | + |
| 91 | + def color_hit(self) -> Color: |
| 92 | + """Returns a color for a pixel to denote a ray hitting a surface.""" |
| 93 | + # pylint: disable=R0201 |
| 94 | + return Color(128, 128, 128) |
| 95 | + |
| 96 | + def color_for_info( |
| 97 | + self, |
| 98 | + info: IntersectionInfo, |
| 99 | + ) -> Color: |
| 100 | + """Returns color associated with the intersection info.""" |
| 101 | + |
| 102 | + if info.hits(): |
| 103 | + return self.color_hit() |
| 104 | + miss_reason = info.miss_reason() |
| 105 | + if miss_reason is None: |
| 106 | + raise RuntimeError( |
| 107 | + f"Cannot pick color for intersectio info {info}." |
| 108 | + " No miss reason specified despite ray is missing." |
| 109 | + ) |
| 110 | + return color_miss_reason(miss_reason) |
| 111 | + |
| 112 | + def apply(self, info_matrix: IntersectionInfoMatrix) -> Image: |
| 113 | + if len(info_matrix) == 0 or len(info_matrix[0]) == 0: |
| 114 | + raise ValueError( |
| 115 | + "Cannot apply hit filter. Intersection info matrix is empty." |
| 116 | + ) |
| 117 | + width = len(info_matrix) |
| 118 | + height = len(info_matrix[0]) |
| 119 | + |
| 120 | + # initialize image with pink background |
| 121 | + image = Image.new( |
| 122 | + mode="RGB", size=(width, height), color=Colors.BLACK.rgb |
| 123 | + ) |
| 124 | + |
| 125 | + # paint-in pixels |
| 126 | + for pixel_x in range(width): |
| 127 | + for pixel_y in range(height): |
| 128 | + pixel_location = (pixel_x, pixel_y) |
| 129 | + info = info_matrix[pixel_x][pixel_y] |
| 130 | + pixel_color = self.color_for_info(info) |
| 131 | + image.putpixel(pixel_location, pixel_color.rgb) |
| 132 | + |
| 133 | + return image |
| 134 | + |
| 135 | + |
| 136 | +class ImageFilterRenderer(ImageRenderer): |
| 137 | + """ |
| 138 | + Renderer which renders the data first and allows to apply filters after. |
| 139 | +
|
| 140 | + This workflow costs more resources during rendering but also allows for |
| 141 | + more experimentation. |
| 142 | + """ |
| 143 | + |
| 144 | + def __init__( |
| 145 | + self, |
| 146 | + projection_mode: ProjectionMode, |
| 147 | + filtr: Filter, |
| 148 | + print_warings: bool = True, |
| 149 | + auto_apply_filter: bool = True, |
| 150 | + ): |
| 151 | + |
| 152 | + ImageRenderer.__init__( |
| 153 | + self, projection_mode, print_warings=print_warings |
| 154 | + ) |
| 155 | + |
| 156 | + self._filter = filtr |
| 157 | + self.auto_apply_filter = auto_apply_filter |
| 158 | + self._last_info_matrix: Optional[IntersectionInfoMatrix] = None |
| 159 | + |
| 160 | + def has_render_data(self) -> bool: |
| 161 | + """Returns True, iff render was called previously.""" |
| 162 | + |
| 163 | + return self._last_info_matrix is not None |
| 164 | + |
| 165 | + def filter(self) -> Filter: |
| 166 | + """Returns the filter currently used.""" |
| 167 | + return self._filter |
| 168 | + |
| 169 | + def change_filter(self, filtr: Filter) -> None: |
| 170 | + """ |
| 171 | + Changes the filter to a new one. |
| 172 | +
|
| 173 | + Note: This may cause the filter to be applied automatically if |
| 174 | + auto_apply_filter is enabled. Otherwise apply_filter must be |
| 175 | + called manually to apply the filter. Results may be outdated |
| 176 | + until then. |
| 177 | + """ |
| 178 | + self._filter = filtr |
| 179 | + if self.auto_apply_filter and self.has_render_data(): |
| 180 | + self.apply_filter() |
| 181 | + |
| 182 | + def render_pixel_intersection_info( |
| 183 | + self, |
| 184 | + camera: Camera, |
| 185 | + geometry: Geometry, |
| 186 | + objects: list[Object], |
| 187 | + pixel_location: tuple[int, int], |
| 188 | + ) -> IntersectionInfo: |
| 189 | + """ |
| 190 | + Returns the intersection info of the ray cast for the pixel. |
| 191 | + """ |
| 192 | + |
| 193 | + ray = self.ray_for_pixel(camera, geometry, pixel_location) |
| 194 | + if ray is None: |
| 195 | + return IntersectionInfos.RAY_INITIALIZED_OUTSIDE_MANIFOLD |
| 196 | + |
| 197 | + # detect intersections with objects |
| 198 | + current_depth = np.inf |
| 199 | + current_info = IntersectionInfos.NO_INTERSECTION |
| 200 | + for obj in objects: |
| 201 | + for face in obj.faces(): |
| 202 | + intersection_info = ray.intersection_info(face) |
| 203 | + if intersection_info.hits(): |
| 204 | + # update intersection info to closest |
| 205 | + if intersection_info.ray_depth() < current_depth: |
| 206 | + current_depth = intersection_info.ray_depth() |
| 207 | + current_info = intersection_info |
| 208 | + else: |
| 209 | + # update intersection info to ray left manifold |
| 210 | + # if no face was intersected yet and ray left manifold |
| 211 | + if ( |
| 212 | + current_info is IntersectionInfos.NO_INTERSECTION |
| 213 | + and intersection_info.miss_reason() |
| 214 | + is IntersectionInfo.MissReason.RAY_LEFT_MANIFOLD |
| 215 | + ): |
| 216 | + current_info = IntersectionInfos.RAY_LEFT_MANIFOLD |
| 217 | + return current_info |
| 218 | + |
| 219 | + def render_intersection_info( |
| 220 | + self, scene: Scene, geometry: Geometry |
| 221 | + ) -> IntersectionInfoMatrix: |
| 222 | + """ |
| 223 | + Returns matrix with intersection infos per pixel. |
| 224 | + """ |
| 225 | + |
| 226 | + width, height = scene.camera.canvas_dimensions |
| 227 | + # initialize background with nan |
| 228 | + info_matrix: IntersectionInfoMatrix = IntersectionInfoMatrix( |
| 229 | + [ |
| 230 | + [IntersectionInfos.UNINIALIZED for _ in range(height)] |
| 231 | + for _ in range(width) |
| 232 | + ] |
| 233 | + ) |
| 234 | + # obtain pixel ray info |
| 235 | + for pixel_x in range(width): |
| 236 | + for pixel_y in range(height): |
| 237 | + pixel_location = (pixel_x, pixel_y) |
| 238 | + pixel_info = self.render_pixel_intersection_info( |
| 239 | + scene.camera, |
| 240 | + geometry, |
| 241 | + scene.objects(), |
| 242 | + pixel_location, |
| 243 | + ) |
| 244 | + info_matrix[pixel_x][pixel_y] = pixel_info |
| 245 | + return info_matrix |
| 246 | + |
| 247 | + def render(self, scene: Scene, geometry: Geometry) -> None: |
| 248 | + """ |
| 249 | + Renders ray intersection information. |
| 250 | +
|
| 251 | + First stage in processing. Apply a filter next. |
| 252 | +
|
| 253 | + Note: Filter may be applied automatically if auto_apply_filter is True. |
| 254 | + Else apply_filter must be called manually. |
| 255 | + """ |
| 256 | + # obtain ray depth information and normalize it |
| 257 | + info_matrix = self.render_intersection_info( |
| 258 | + scene=scene, geometry=geometry |
| 259 | + ) |
| 260 | + self._last_info_matrix = info_matrix |
| 261 | + |
| 262 | + if self.auto_apply_filter: |
| 263 | + self.apply_filter() |
| 264 | + |
| 265 | + def apply_filter(self) -> None: |
| 266 | + """ |
| 267 | + Convert intersection information into an image. |
| 268 | +
|
| 269 | + Second and last stage in processing. Must have rendererd first. |
| 270 | +
|
| 271 | + Note: This method may be called automatically depending on |
| 272 | + auto_apply_filter. If not apply_filter must be called manually. |
| 273 | + """ |
| 274 | + if self._last_info_matrix is None: |
| 275 | + print( |
| 276 | + "WARNING: Cannot apply filter without rendering first." |
| 277 | + " No intersection info matrix found." |
| 278 | + ) |
| 279 | + return |
| 280 | + self._last_image = self._filter.apply(self._last_info_matrix) |
| 281 | + |
| 282 | + def last_image(self) -> Optional[Image.Image]: |
| 283 | + """Returns the last image rendered iff it exists or else None.""" |
| 284 | + return self._last_image |
0 commit comments