test_render_meshes.py 70.3 KB
Newer Older
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
Patrick Labatut's avatar
Patrick Labatut committed
2
3
4
5
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
facebook-github-bot's avatar
facebook-github-bot committed
6
7
8
9
10


"""
Sanity checks for output images from the renderer.
"""
Georgia Gkioxari's avatar
Georgia Gkioxari committed
11
import os
facebook-github-bot's avatar
facebook-github-bot committed
12
import unittest
Nikhila Ravi's avatar
Nikhila Ravi committed
13
from collections import namedtuple
14

15
16
from itertools import product

17
import numpy as np
facebook-github-bot's avatar
facebook-github-bot committed
18
19
import torch
from PIL import Image
20
from pytorch3d.io import load_obj, load_objs_as_meshes
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
21
22
from pytorch3d.renderer import (
    AmbientLights,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
23
24
    FoVOrthographicCameras,
    FoVPerspectiveCameras,
25
    look_at_view_transform,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
26
27
28
29
    Materials,
    MeshRasterizer,
    MeshRenderer,
    MeshRendererWithFragments,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
30
31
    OrthographicCameras,
    PerspectiveCameras,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
32
33
34
35
36
    PointLights,
    RasterizationSettings,
    TexturesAtlas,
    TexturesUV,
    TexturesVertex,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
37
)
38
from pytorch3d.renderer.fisheyecameras import FishEyeCameras
facebook-github-bot's avatar
facebook-github-bot committed
39
40
from pytorch3d.renderer.mesh.shader import (
    BlendParams,
41
    HardFlatShader,
Patrick Labatut's avatar
Patrick Labatut committed
42
    HardGouraudShader,
43
    HardPhongShader,
44
    SoftPhongShader,
45
    SoftSilhouetteShader,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
46
    SplatterPhongShader,
47
    TexturedSoftPhongShader,
facebook-github-bot's avatar
facebook-github-bot committed
48
)
49
from pytorch3d.renderer.opengl import MeshRasterizerOpenGL
50
51
52
from pytorch3d.structures.meshes import (
    join_meshes_as_batch,
    join_meshes_as_scene,
53
    Meshes,
54
)
facebook-github-bot's avatar
facebook-github-bot committed
55
from pytorch3d.utils.ico_sphere import ico_sphere
56
from pytorch3d.utils.torus import torus
facebook-github-bot's avatar
facebook-github-bot committed
57

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
58
59
60
61
from .common_testing import (
    get_pytorch3d_dir,
    get_tests_dir,
    load_rgb_image,
62
    skip_opengl_requested,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
63
    TestCaseMixin,
64
    usesOpengl,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
65
66
)

Nikhila Ravi's avatar
Nikhila Ravi committed
67
# If DEBUG=True, save out images generated in the tests for debugging.
facebook-github-bot's avatar
facebook-github-bot committed
68
69
# All saved images have prefix DEBUG_
DEBUG = False
70
DATA_DIR = get_tests_dir() / "data"
71
TUTORIAL_DATA_DIR = get_pytorch3d_dir() / "docs/tutorials/data"
facebook-github-bot's avatar
facebook-github-bot committed
72

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
73
74
75
RasterizerTest = namedtuple(
    "RasterizerTest", ["rasterizer", "shader", "reference_name", "debug_name"]
)
Nikhila Ravi's avatar
Nikhila Ravi committed
76

facebook-github-bot's avatar
facebook-github-bot committed
77

Nikhila Ravi's avatar
Nikhila Ravi committed
78
class TestRenderMeshes(TestCaseMixin, unittest.TestCase):
79
    def test_simple_sphere(self, elevated_camera=False, check_depth=False):
facebook-github-bot's avatar
facebook-github-bot committed
80
        """
Patrick Labatut's avatar
Patrick Labatut committed
81
        Test output of phong and gouraud shading matches a reference image using
facebook-github-bot's avatar
facebook-github-bot committed
82
83
84
85
86
87
88
89
90
91
92
93
        the default values for the light sources.

        Args:
            elevated_camera: Defines whether the camera observing the scene should
                           have an elevation of 45 degrees.
        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
Nikhila Ravi's avatar
Nikhila Ravi committed
94
95
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
96
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)
facebook-github-bot's avatar
facebook-github-bot committed
97
98
99

        # Init rasterizer settings
        if elevated_camera:
100
101
            # Elevated and rotated camera
            R, T = look_at_view_transform(dist=2.7, elev=45.0, azim=45.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
102
            postfix = "_elevated_"
103
104
            # If y axis is up, the spot of light should
            # be on the bottom left of the sphere.
facebook-github-bot's avatar
facebook-github-bot committed
105
        else:
106
            # No elevation or azimuth rotation
facebook-github-bot's avatar
facebook-github-bot committed
107
            R, T = look_at_view_transform(2.7, 0.0, 0.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
108
109
110
111
112
113
            postfix = "_"
        for cam_type in (
            FoVPerspectiveCameras,
            FoVOrthographicCameras,
            PerspectiveCameras,
            OrthographicCameras,
114
            FishEyeCameras,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
115
        ):
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            if cam_type == FishEyeCameras:
                cam_kwargs = {
                    "radial_params": torch.tensor(
                        [
                            [-1, -2, -3, 0, 0, 1],
                        ],
                        dtype=torch.float32,
                    ),
                    "tangential_params": torch.tensor(
                        [[0.7002747019, -0.4005228974]], dtype=torch.float32
                    ),
                    "thin_prism_params": torch.tensor(
                        [
                            [-1.000134884, -1.000084822, -1.0009420014, -1.0001276838],
                        ],
                        dtype=torch.float32,
                    ),
                }
                cameras = cam_type(
                    device=device,
                    R=R,
                    T=T,
                    use_tangential=True,
                    use_radial=True,
                    use_thin_prism=True,
                    world_coordinates=True,
                    **cam_kwargs,
                )
            else:
                cameras = cam_type(device=device, R=R, T=T)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
146
147
148
149
150
151
152
153
154

            # Init shader settings
            materials = Materials(device=device)
            lights = PointLights(device=device)
            lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

            raster_settings = RasterizationSettings(
                image_size=512, blur_radius=0.0, faces_per_pixel=1
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
155
            blend_params = BlendParams(0.5, 1e-4, (0, 0, 0))
Georgia Gkioxari's avatar
Georgia Gkioxari committed
156
157

            # Test several shaders
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
158
159
160
161
162
163
            rasterizer_tests = [
                RasterizerTest(MeshRasterizer, HardPhongShader, "phong", "hard_phong"),
                RasterizerTest(
                    MeshRasterizer, HardGouraudShader, "gouraud", "hard_gouraud"
                ),
                RasterizerTest(MeshRasterizer, HardFlatShader, "flat", "hard_flat"),
Nikhila Ravi's avatar
Nikhila Ravi committed
164
            ]
165
166
167
168
169
170
171
172
173
            if not skip_opengl_requested():
                rasterizer_tests.append(
                    RasterizerTest(
                        MeshRasterizerOpenGL,
                        SplatterPhongShader,
                        "splatter",
                        "splatter_phong",
                    )
                )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
174
            for test in rasterizer_tests:
Nikhila Ravi's avatar
Nikhila Ravi committed
175
                shader = test.shader(
Georgia Gkioxari's avatar
Georgia Gkioxari committed
176
177
178
179
180
                    lights=lights,
                    cameras=cameras,
                    materials=materials,
                    blend_params=blend_params,
                )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
181
182
183
184
185
                if test.rasterizer == MeshRasterizer:
                    rasterizer = test.rasterizer(
                        cameras=cameras, raster_settings=raster_settings
                    )
                elif test.rasterizer == MeshRasterizerOpenGL:
186
187
188
189
190
                    if type(cameras) in [
                        PerspectiveCameras,
                        OrthographicCameras,
                        FishEyeCameras,
                    ]:
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
191
192
193
194
195
196
197
                        # MeshRasterizerOpenGL is only compatible with FoV cameras.
                        continue
                    rasterizer = test.rasterizer(
                        cameras=cameras,
                        raster_settings=raster_settings,
                    )

198
199
200
201
202
203
                if check_depth:
                    renderer = MeshRendererWithFragments(
                        rasterizer=rasterizer, shader=shader
                    )
                    images, fragments = renderer(sphere_mesh)
                    self.assertClose(fragments.zbuf, rasterizer(sphere_mesh).zbuf)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
204
205
206
207
208
209
210
211
                    # Check the alpha channel is the mask. For soft rasterizers, the
                    # boundary will not match exactly so we use quantiles to compare.
                    self.assertLess(
                        (
                            images[..., -1]
                            - (fragments.pix_to_face[..., 0] >= 0).float()
                        ).quantile(0.99),
                        0.005,
212
                    )
213
214
215
216
                else:
                    renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
                    images = renderer(sphere_mesh)

Georgia Gkioxari's avatar
Georgia Gkioxari committed
217
218
                rgb = images[0, ..., :3].squeeze().cpu()
                filename = "simple_sphere_light_%s%s%s.png" % (
Nikhila Ravi's avatar
Nikhila Ravi committed
219
                    test.reference_name,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
220
221
222
                    postfix,
                    cam_type.__name__,
                )
facebook-github-bot's avatar
facebook-github-bot committed
223

Georgia Gkioxari's avatar
Georgia Gkioxari committed
224
225
                image_ref = load_rgb_image("test_%s" % filename, DATA_DIR)
                if DEBUG:
Nikhila Ravi's avatar
Nikhila Ravi committed
226
227
228
229
230
231
                    debug_filename = "simple_sphere_light_%s%s%s.png" % (
                        test.debug_name,
                        postfix,
                        cam_type.__name__,
                    )
                    filename = "DEBUG_%s" % debug_filename
Georgia Gkioxari's avatar
Georgia Gkioxari committed
232
233
234
                    Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                        DATA_DIR / filename
                    )
235
                self.assertClose(rgb, image_ref, atol=0.05)
Nikhila Ravi's avatar
Nikhila Ravi committed
236

Georgia Gkioxari's avatar
Georgia Gkioxari committed
237
238
239
240
241
242
243
            ########################################################
            # Move the light to the +z axis in world space so it is
            # behind the sphere. Note that +Z is in, +Y up,
            # +X left for both world and camera space.
            ########################################################
            lights.location[..., 2] = -2.0
            phong_shader = HardPhongShader(
244
245
246
247
248
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
249
250
251
252
253
254
255
256
            if check_depth:
                phong_renderer = MeshRendererWithFragments(
                    rasterizer=rasterizer, shader=phong_shader
                )
                images, fragments = phong_renderer(sphere_mesh, lights=lights)
                self.assertClose(
                    fragments.zbuf, rasterizer(sphere_mesh, lights=lights).zbuf
                )
257
                # Check the alpha channel is the mask
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
258
259
260
261
262
                self.assertLess(
                    (
                        images[..., -1] - (fragments.pix_to_face[..., 0] >= 0).float()
                    ).quantile(0.99),
                    0.005,
263
                )
264
265
266
267
268
            else:
                phong_renderer = MeshRenderer(
                    rasterizer=rasterizer, shader=phong_shader
                )
                images = phong_renderer(sphere_mesh, lights=lights)
Nikhila Ravi's avatar
Nikhila Ravi committed
269
270
            rgb = images[0, ..., :3].squeeze().cpu()
            if DEBUG:
Georgia Gkioxari's avatar
Georgia Gkioxari committed
271
272
273
274
                filename = "DEBUG_simple_sphere_dark%s%s.png" % (
                    postfix,
                    cam_type.__name__,
                )
Nikhila Ravi's avatar
Nikhila Ravi committed
275
276
277
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / filename
                )
facebook-github-bot's avatar
facebook-github-bot committed
278

Georgia Gkioxari's avatar
Georgia Gkioxari committed
279
280
281
            image_ref_phong_dark = load_rgb_image(
                "test_simple_sphere_dark%s%s.png" % (postfix, cam_type.__name__),
                DATA_DIR,
facebook-github-bot's avatar
facebook-github-bot committed
282
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
283
284
285
            # Soft shaders (SplatterPhong) will have a different boundary than hard
            # ones, but should be identical otherwise.
            self.assertLess((rgb - image_ref_phong_dark).quantile(0.99), 0.005)
facebook-github-bot's avatar
facebook-github-bot committed
286
287
288

    def test_simple_sphere_elevated_camera(self):
        """
Patrick Labatut's avatar
Patrick Labatut committed
289
        Test output of phong and gouraud shading matches a reference image using
facebook-github-bot's avatar
facebook-github-bot committed
290
291
292
293
294
295
        the default values for the light sources.

        The rendering is performed with a camera that has non-zero elevation.
        """
        self.test_simple_sphere(elevated_camera=True)

296
297
298
299
300
301
302
303
304
    def test_simple_sphere_depth(self):
        """
        Test output of phong and gouraud shading matches a reference image using
        the default values for the light sources.

        The rendering is performed with a camera that has non-zero elevation.
        """
        self.test_simple_sphere(check_depth=True)

Georgia Gkioxari's avatar
Georgia Gkioxari committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    def test_simple_sphere_screen(self):
        """
        Test output when rendering with PerspectiveCameras & OrthographicCameras
        in NDC vs screen space.
        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)

        R, T = look_at_view_transform(2.7, 0.0, 0.0)

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
        lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

        raster_settings = RasterizationSettings(
            image_size=512, blur_radius=0.0, faces_per_pixel=1
        )
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
330
        half_half = (512.0 / 2.0, 512.0 / 2.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
331
332
333
334
335
        for cam_type in (PerspectiveCameras, OrthographicCameras):
            cameras = cam_type(
                device=device,
                R=R,
                T=T,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
336
337
                principal_point=(half_half,),
                focal_length=(half_half,),
Georgia Gkioxari's avatar
Georgia Gkioxari committed
338
                image_size=((512, 512),),
339
                in_ndc=False,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
            )
            rasterizer = MeshRasterizer(
                cameras=cameras, raster_settings=raster_settings
            )
            blend_params = BlendParams(1e-4, 1e-4, (0, 0, 0))

            shader = HardPhongShader(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            images = renderer(sphere_mesh)
            rgb = images[0, ..., :3].squeeze().cpu()
            filename = "test_simple_sphere_light_phong_%s.png" % cam_type.__name__
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
356
357
358
359
            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / f"{filename}_.png"
                )
Georgia Gkioxari's avatar
Georgia Gkioxari committed
360
361
362
363

            image_ref = load_rgb_image(filename, DATA_DIR)
            self.assertClose(rgb, image_ref, atol=0.05)

facebook-github-bot's avatar
facebook-github-bot committed
364
365
    def test_simple_sphere_batched(self):
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
366
        Test a mesh with vertex textures can be extended to form a batch, and
Nikhila Ravi's avatar
Nikhila Ravi committed
367
368
        is rendered correctly with Phong, Gouraud and Flat Shaders with batched
        lighting and hard and soft blending.
facebook-github-bot's avatar
facebook-github-bot committed
369
        """
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
370
        batch_size = 3
facebook-github-bot's avatar
facebook-github-bot committed
371
372
        device = torch.device("cuda:0")

Nikhila Ravi's avatar
Nikhila Ravi committed
373
        # Init mesh with vertex textures.
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
374
        sphere_meshes = ico_sphere(3, device).extend(batch_size)
facebook-github-bot's avatar
facebook-github-bot committed
375
376
        verts_padded = sphere_meshes.verts_padded()
        faces_padded = sphere_meshes.faces_padded()
Nikhila Ravi's avatar
Nikhila Ravi committed
377
378
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
facebook-github-bot's avatar
facebook-github-bot committed
379
380
381
382
383
        sphere_meshes = Meshes(
            verts=verts_padded, faces=faces_padded, textures=textures
        )

        # Init rasterizer settings
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
384
        dist = torch.tensor([2, 4, 6]).to(device)
facebook-github-bot's avatar
facebook-github-bot committed
385
386
387
        elev = torch.zeros_like(dist)
        azim = torch.zeros_like(dist)
        R, T = look_at_view_transform(dist, elev, azim)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
388
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
facebook-github-bot's avatar
facebook-github-bot committed
389
        raster_settings = RasterizationSettings(
Nikhila Ravi's avatar
Nikhila Ravi committed
390
            image_size=512, blur_radius=0.0, faces_per_pixel=4
facebook-github-bot's avatar
facebook-github-bot committed
391
392
393
394
        )

        # Init shader settings
        materials = Materials(device=device)
Nikhila Ravi's avatar
Nikhila Ravi committed
395
396
397
        lights_location = torch.tensor([0.0, 0.0, +2.0], device=device)
        lights_location = lights_location[None].expand(batch_size, -1)
        lights = PointLights(device=device, location=lights_location)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
398
        blend_params = BlendParams(0.5, 1e-4, (0, 0, 0))
facebook-github-bot's avatar
facebook-github-bot committed
399
400

        # Init renderer
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
401
402
403
404
405
406
        rasterizer_tests = [
            RasterizerTest(MeshRasterizer, HardPhongShader, "phong", "hard_phong"),
            RasterizerTest(
                MeshRasterizer, HardGouraudShader, "gouraud", "hard_gouraud"
            ),
            RasterizerTest(MeshRasterizer, HardFlatShader, "flat", "hard_flat"),
Nikhila Ravi's avatar
Nikhila Ravi committed
407
        ]
408
409
410
411
412
413
414
415
416
        if not skip_opengl_requested():
            rasterizer_tests.append(
                RasterizerTest(
                    MeshRasterizerOpenGL,
                    SplatterPhongShader,
                    "splatter",
                    "splatter_phong",
                )
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
417
        for test in rasterizer_tests:
Nikhila Ravi's avatar
Nikhila Ravi committed
418
419
            reference_name = test.reference_name
            debug_name = test.debug_name
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
420
421
422
423
            rasterizer = test.rasterizer(
                cameras=cameras, raster_settings=raster_settings
            )

Nikhila Ravi's avatar
Nikhila Ravi committed
424
            shader = test.shader(
425
426
427
428
429
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
430
431
432
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            images = renderer(sphere_meshes)
            for i in range(batch_size):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
433
434
435
436
437
                image_ref = load_rgb_image(
                    "test_simple_sphere_batched_%s_%s_%s.png"
                    % (reference_name, type(cameras).__name__, i),
                    DATA_DIR,
                )
Nikhila Ravi's avatar
Nikhila Ravi committed
438
                rgb = images[i, ..., :3].squeeze().cpu()
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
439
440
                if DEBUG:
                    filename = "DEBUG_simple_sphere_batched_%s_%s_%s.png" % (
Nikhila Ravi's avatar
Nikhila Ravi committed
441
                        debug_name,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
442
                        type(cameras).__name__,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
443
                        i,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
444
                    )
Nikhila Ravi's avatar
Nikhila Ravi committed
445
446
447
                    Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                        DATA_DIR / filename
                    )
Nikhila Ravi's avatar
Nikhila Ravi committed
448
                self.assertClose(rgb, image_ref, atol=0.05)
facebook-github-bot's avatar
facebook-github-bot committed
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463

    def test_silhouette_with_grad(self):
        """
        Test silhouette blending. Also check that gradient calculation works.
        """
        device = torch.device("cuda:0")
        sphere_mesh = ico_sphere(5, device)
        verts, faces = sphere_mesh.get_mesh_verts_faces(0)
        sphere_mesh = Meshes(verts=[verts], faces=[faces])

        blend_params = BlendParams(sigma=1e-4, gamma=1e-4)
        raster_settings = RasterizationSettings(
            image_size=512,
            blur_radius=np.log(1.0 / 1e-4 - 1.0) * blend_params.sigma,
            faces_per_pixel=80,
464
            clip_barycentric_coords=True,
facebook-github-bot's avatar
facebook-github-bot committed
465
466
467
        )

        # Init rasterizer settings
468
        R, T = look_at_view_transform(2.7, 0, 0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
469
470
471
472
473
        for cam_type in (
            FoVPerspectiveCameras,
            FoVOrthographicCameras,
            PerspectiveCameras,
            OrthographicCameras,
474
            FishEyeCameras,
Georgia Gkioxari's avatar
Georgia Gkioxari committed
475
        ):
476
477
478
479
480
481
482
483
484
485
486
487
            if cam_type == FishEyeCameras:
                cameras = cam_type(
                    device=device,
                    R=R,
                    T=T,
                    use_tangential=False,
                    use_radial=False,
                    use_thin_prism=False,
                    world_coordinates=True,
                )
            else:
                cameras = cam_type(device=device, R=R, T=T)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
488
489
490
491
492
493
494

            # Init renderer
            renderer = MeshRenderer(
                rasterizer=MeshRasterizer(
                    cameras=cameras, raster_settings=raster_settings
                ),
                shader=SoftSilhouetteShader(blend_params=blend_params),
facebook-github-bot's avatar
facebook-github-bot committed
495
            )
Georgia Gkioxari's avatar
Georgia Gkioxari committed
496
497
498
499
500
501
502
503
504
            images = renderer(sphere_mesh)
            alpha = images[0, ..., 3].squeeze().cpu()
            if DEBUG:
                filename = os.path.join(
                    DATA_DIR, "DEBUG_%s_silhouette.png" % (cam_type.__name__)
                )
                Image.fromarray((alpha.detach().numpy() * 255).astype(np.uint8)).save(
                    filename
                )
facebook-github-bot's avatar
facebook-github-bot committed
505

Georgia Gkioxari's avatar
Georgia Gkioxari committed
506
507
508
509
            ref_filename = "test_%s_silhouette.png" % (cam_type.__name__)
            image_ref_filename = DATA_DIR / ref_filename
            with Image.open(image_ref_filename) as raw_image_ref:
                image_ref = torch.from_numpy(np.array(raw_image_ref))
Nikhila Ravi's avatar
Nikhila Ravi committed
510

Georgia Gkioxari's avatar
Georgia Gkioxari committed
511
512
            image_ref = image_ref.to(dtype=torch.float32) / 255.0
            self.assertClose(alpha, image_ref, atol=0.055)
facebook-github-bot's avatar
facebook-github-bot committed
513

Georgia Gkioxari's avatar
Georgia Gkioxari committed
514
515
516
517
518
519
            # Check grad exist
            verts.requires_grad = True
            sphere_mesh = Meshes(verts=[verts], faces=[faces])
            images = renderer(sphere_mesh)
            images[0, ...].sum().backward()
            self.assertIsNotNone(verts.grad)
facebook-github-bot's avatar
facebook-github-bot committed
520
521
522

    def test_texture_map(self):
        """
523
524
        Test a mesh with a texture map is loaded and rendered correctly.
        The pupils in the eyes of the cow should always be looking to the left.
facebook-github-bot's avatar
facebook-github-bot committed
525
        """
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
526
527
        self._texture_map_per_rasterizer(MeshRasterizer)

528
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
529
530
531
532
533
534
535
536
    def test_texture_map_opengl(self):
        """
        Test a mesh with a texture map is loaded and rendered correctly.
        The pupils in the eyes of the cow should always be looking to the left.
        """
        self._texture_map_per_rasterizer(MeshRasterizerOpenGL)

    def _texture_map_per_rasterizer(self, rasterizer_type):
facebook-github-bot's avatar
facebook-github-bot committed
537
        device = torch.device("cuda:0")
538
539

        obj_filename = TUTORIAL_DATA_DIR / "cow_mesh/cow.obj"
facebook-github-bot's avatar
facebook-github-bot committed
540
541

        # Load mesh + texture
Nikhila Ravi's avatar
Nikhila Ravi committed
542
543
544
545
546
547
548
549
550
        verts, faces, aux = load_obj(
            obj_filename, device=device, load_textures=True, texture_wrap=None
        )
        tex_map = list(aux.texture_images.values())[0]
        tex_map = tex_map[None, ...].to(faces.textures_idx.device)
        textures = TexturesUV(
            maps=tex_map, faces_uvs=[faces.textures_idx], verts_uvs=[aux.verts_uvs]
        )
        mesh = Meshes(verts=[verts], faces=[faces.verts_idx], textures=textures)
facebook-github-bot's avatar
facebook-github-bot committed
551
552

        # Init rasterizer settings
553
        R, T = look_at_view_transform(2.7, 0, 0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
554
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
Nikhila Ravi's avatar
Nikhila Ravi committed
555

facebook-github-bot's avatar
facebook-github-bot committed
556
        raster_settings = RasterizationSettings(
Nikhila Ravi's avatar
Nikhila Ravi committed
557
            image_size=512, blur_radius=0.0, faces_per_pixel=1
facebook-github-bot's avatar
facebook-github-bot committed
558
559
560
561
562
        )

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
563
564
565
566

        # Place light behind the cow in world space. The front of
        # the cow is facing the -z direction.
        lights.location = torch.tensor([0.0, 0.0, 2.0], device=device)[None]
facebook-github-bot's avatar
facebook-github-bot committed
567

568
        blend_params = BlendParams(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
569
            sigma=1e-1 if rasterizer_type == MeshRasterizer else 0.5,
570
571
572
            gamma=1e-4,
            background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
        )
facebook-github-bot's avatar
facebook-github-bot committed
573
        # Init renderer
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
574
575
576
        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            shader = TexturedSoftPhongShader(
577
578
579
580
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
581
582
583
584
585
586
587
588
589
            )
        elif rasterizer_type == MeshRasterizerOpenGL:
            shader = SplatterPhongShader(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
        renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
facebook-github-bot's avatar
facebook-github-bot committed
590
591

        # Load reference image
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
592
593
594
        image_ref = load_rgb_image(
            f"test_texture_map_back_{rasterizer_type.__name__}.png", DATA_DIR
        )
facebook-github-bot's avatar
facebook-github-bot committed
595

Nikhila Ravi's avatar
Nikhila Ravi committed
596
        for bin_size in [0, None]:
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
597
598
599
            if rasterizer_type == MeshRasterizerOpenGL and bin_size == 0:
                # MeshRasterizerOpenGL does not use this parameter.
                continue
Nikhila Ravi's avatar
Nikhila Ravi committed
600
601
602
603
            # Check both naive and coarse to fine produce the same output.
            renderer.rasterizer.raster_settings.bin_size = bin_size
            images = renderer(mesh)
            rgb = images[0, ..., :3].squeeze().cpu()
facebook-github-bot's avatar
facebook-github-bot committed
604

Nikhila Ravi's avatar
Nikhila Ravi committed
605
606
            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
607
                    DATA_DIR / f"DEBUG_texture_map_back_{rasterizer_type.__name__}.png"
Nikhila Ravi's avatar
Nikhila Ravi committed
608
609
610
611
612
613
                )

            # NOTE some pixels can be flaky and will not lead to
            # `cond1` being true. Add `cond2` and check `cond1 or cond2`
            cond1 = torch.allclose(rgb, image_ref, atol=0.05)
            cond2 = ((rgb - image_ref).abs() > 0.05).sum() < 5
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
614
            # self.assertTrue(cond1 or cond2)
facebook-github-bot's avatar
facebook-github-bot committed
615
616

        # Check grad exists
617
        [verts] = mesh.verts_list()
facebook-github-bot's avatar
facebook-github-bot committed
618
        verts.requires_grad = True
619
        mesh2 = Meshes(verts=[verts], faces=mesh.faces_list(), textures=mesh.textures)
620
        images = renderer(mesh2)
facebook-github-bot's avatar
facebook-github-bot committed
621
622
        images[0, ...].sum().backward()
        self.assertIsNotNone(verts.grad)
623

624
625
626
627
628
        ##########################################
        # Check rendering of the front of the cow
        ##########################################

        R, T = look_at_view_transform(2.7, 0, 180)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
629
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
630
631
632
633
634

        # Move light to the front of the cow in world space
        lights.location = torch.tensor([0.0, 0.0, -2.0], device=device)[None]

        # Load reference image
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
635
636
637
        image_ref = load_rgb_image(
            f"test_texture_map_front_{rasterizer_type.__name__}.png", DATA_DIR
        )
638

Nikhila Ravi's avatar
Nikhila Ravi committed
639
        for bin_size in [0, None]:
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
640
641
642
            if rasterizer == MeshRasterizerOpenGL and bin_size == 0:
                # MeshRasterizerOpenGL does not use this parameter.
                continue
Nikhila Ravi's avatar
Nikhila Ravi committed
643
644
645
646
647
648
649
650
            # Check both naive and coarse to fine produce the same output.
            renderer.rasterizer.raster_settings.bin_size = bin_size

            images = renderer(mesh, cameras=cameras, lights=lights)
            rgb = images[0, ..., :3].squeeze().cpu()

            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
651
                    DATA_DIR / f"DEBUG_texture_map_front_{rasterizer_type.__name__}.png"
Nikhila Ravi's avatar
Nikhila Ravi committed
652
653
654
655
656
657
658
                )

            # NOTE some pixels can be flaky and will not lead to
            # `cond1` being true. Add `cond2` and check `cond1 or cond2`
            cond1 = torch.allclose(rgb, image_ref, atol=0.05)
            cond2 = ((rgb - image_ref).abs() > 0.05).sum() < 5
            self.assertTrue(cond1 or cond2)
659

660
661
662
        #################################
        # Add blurring to rasterization
        #################################
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
        if rasterizer_type == MeshRasterizer:
            # Note that MeshRasterizer can blur the images arbitrarily, however
            # MeshRasterizerOpenGL is limited by its kernel size (currently 3 px^2),
            # so this test only makes sense for MeshRasterizer.
            R, T = look_at_view_transform(2.7, 0, 180)
            cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
            # For MeshRasterizer, blurring is controlled by blur_radius. For
            # MeshRasterizerOpenGL, by sigma.
            blend_params = BlendParams(sigma=5e-4, gamma=1e-4)
            raster_settings = RasterizationSettings(
                image_size=512,
                blur_radius=np.log(1.0 / 1e-4 - 1.0) * blend_params.sigma,
                faces_per_pixel=100,
                clip_barycentric_coords=True,
                perspective_correct=rasterizer_type.__name__ == "MeshRasterizerOpenGL",
            )
679

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
680
681
            # Load reference image
            image_ref = load_rgb_image("test_blurry_textured_rendering.png", DATA_DIR)
Nikhila Ravi's avatar
Nikhila Ravi committed
682

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
683
684
685
            for bin_size in [0, None]:
                # Check both naive and coarse to fine produce the same output.
                renderer.rasterizer.raster_settings.bin_size = bin_size
Nikhila Ravi's avatar
Nikhila Ravi committed
686

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
687
688
689
690
691
                images = renderer(
                    mesh.clone(),
                    cameras=cameras,
                    raster_settings=raster_settings,
                    blend_params=blend_params,
Nikhila Ravi's avatar
Nikhila Ravi committed
692
                )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
693
                rgb = images[0, ..., :3].squeeze().cpu()
694

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
695
696
697
698
699
700
                if DEBUG:
                    Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                        DATA_DIR / "DEBUG_blurry_textured_rendering.png"
                    )

                self.assertClose(rgb, image_ref, atol=0.05)
701

702
    def test_batch_uvs(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
703
704
        self._batch_uvs(MeshRasterizer)

705
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
706
707
708
709
    def test_batch_uvs_opengl(self):
        self._batch_uvs(MeshRasterizer)

    def _batch_uvs(self, rasterizer_type):
710
711
712
        """Test that two random tori with TexturesUV render the same as each individually."""
        torch.manual_seed(1)
        device = torch.device("cuda:0")
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
713

714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
        plain_torus = torus(r=1, R=4, sides=10, rings=10, device=device)
        [verts] = plain_torus.verts_list()
        [faces] = plain_torus.faces_list()
        nocolor = torch.zeros((100, 100), device=device)
        color_gradient = torch.linspace(0, 1, steps=100, device=device)
        color_gradient1 = color_gradient[None].expand_as(nocolor)
        color_gradient2 = color_gradient[:, None].expand_as(nocolor)
        colors1 = torch.stack([nocolor, color_gradient1, color_gradient2], dim=2)
        colors2 = torch.stack([color_gradient1, color_gradient2, nocolor], dim=2)
        verts_uvs1 = torch.rand(size=(verts.shape[0], 2), device=device)
        verts_uvs2 = torch.rand(size=(verts.shape[0], 2), device=device)

        textures1 = TexturesUV(
            maps=[colors1], faces_uvs=[faces], verts_uvs=[verts_uvs1]
        )
        textures2 = TexturesUV(
            maps=[colors2], faces_uvs=[faces], verts_uvs=[verts_uvs2]
        )
        mesh1 = Meshes(verts=[verts], faces=[faces], textures=textures1)
        mesh2 = Meshes(verts=[verts], faces=[faces], textures=textures2)
        mesh_both = join_meshes_as_batch([mesh1, mesh2])

        R, T = look_at_view_transform(10, 10, 0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)

        raster_settings = RasterizationSettings(
            image_size=128, blur_radius=0.0, faces_per_pixel=1
        )

        # Init shader settings
        lights = PointLights(device=device)
        lights.location = torch.tensor([0.0, 0.0, 2.0], device=device)[None]

        blend_params = BlendParams(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
748
            sigma=0.5,
749
750
751
752
            gamma=1e-4,
            background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
        )
        # Init renderer
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
753
754
755
        rasterizer = MeshRasterizer(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            shader = HardPhongShader(
756
                device=device, lights=lights, cameras=cameras, blend_params=blend_params
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
757
758
759
760
761
762
763
            )
        else:
            shader = SplatterPhongShader(
                device=device, lights=lights, cameras=cameras, blend_params=blend_params
            )

        renderer = MeshRenderer(rasterizer, shader)
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794

        outputs = []
        for meshes in [mesh_both, mesh1, mesh2]:
            outputs.append(renderer(meshes))

        if DEBUG:
            Image.fromarray(
                (outputs[0][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
            ).save(DATA_DIR / "test_batch_uvs0.png")
            Image.fromarray(
                (outputs[1][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
            ).save(DATA_DIR / "test_batch_uvs1.png")
            Image.fromarray(
                (outputs[0][1, ..., :3].cpu().numpy() * 255).astype(np.uint8)
            ).save(DATA_DIR / "test_batch_uvs2.png")
            Image.fromarray(
                (outputs[2][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
            ).save(DATA_DIR / "test_batch_uvs3.png")

            diff = torch.abs(outputs[0][0, ..., :3] - outputs[1][0, ..., :3])
            Image.fromarray(((diff > 1e-5).cpu().numpy().astype(np.uint8) * 255)).save(
                DATA_DIR / "test_batch_uvs01.png"
            )
            diff = torch.abs(outputs[0][1, ..., :3] - outputs[2][0, ..., :3])
            Image.fromarray(((diff > 1e-5).cpu().numpy().astype(np.uint8) * 255)).save(
                DATA_DIR / "test_batch_uvs23.png"
            )

        self.assertClose(outputs[0][0, ..., :3], outputs[1][0, ..., :3], atol=1e-5)
        self.assertClose(outputs[0][1, ..., :3], outputs[2][0, ..., :3], atol=1e-5)

795
    def test_join_uvs(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
796
797
        self._join_uvs(MeshRasterizer)

798
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
799
800
801
802
    def test_join_uvs_opengl(self):
        self._join_uvs(MeshRasterizerOpenGL)

    def _join_uvs(self, rasterizer_type):
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
        """Meshes with TexturesUV joined into a scene"""
        # Test the result of rendering three tori with separate textures.
        # The expected result is consistent with rendering them each alone.
        # This tests TexturesUV.join_scene with rectangle flipping,
        # and we check the form of the merged map as well.
        torch.manual_seed(1)
        device = torch.device("cuda:0")

        R, T = look_at_view_transform(18, 0, 0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)

        raster_settings = RasterizationSettings(
            image_size=256, blur_radius=0.0, faces_per_pixel=1
        )

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
818
        lights = AmbientLights(device=device)
819
        blend_params = BlendParams(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
820
            sigma=0.5,
821
822
823
            gamma=1e-4,
            background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
        )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
824
825
826
        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            shader = HardPhongShader(
827
                device=device, blend_params=blend_params, cameras=cameras, lights=lights
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
828
829
830
831
832
833
            )
        else:
            shader = SplatterPhongShader(
                device=device, blend_params=blend_params, cameras=cameras, lights=lights
            )
        renderer = MeshRenderer(rasterizer, shader)
834
835
836
837
838
839
840
841
842

        plain_torus = torus(r=1, R=4, sides=5, rings=6, device=device)
        [verts] = plain_torus.verts_list()
        verts_shifted1 = verts.clone()
        verts_shifted1 *= 0.5
        verts_shifted1[:, 1] += 7
        verts_shifted2 = verts.clone()
        verts_shifted2 *= 0.5
        verts_shifted2[:, 1] -= 7
843
844
845
        verts_shifted3 = verts.clone()
        verts_shifted3 *= 0.5
        verts_shifted3[:, 1] -= 700
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890

        [faces] = plain_torus.faces_list()
        nocolor = torch.zeros((100, 100), device=device)
        color_gradient = torch.linspace(0, 1, steps=100, device=device)
        color_gradient1 = color_gradient[None].expand_as(nocolor)
        color_gradient2 = color_gradient[:, None].expand_as(nocolor)
        colors1 = torch.stack([nocolor, color_gradient1, color_gradient2], dim=2)
        colors2 = torch.stack([color_gradient1, color_gradient2, nocolor], dim=2)
        verts_uvs1 = torch.rand(size=(verts.shape[0], 2), device=device)
        verts_uvs2 = torch.rand(size=(verts.shape[0], 2), device=device)

        for i, align_corners, padding_mode in [
            (0, True, "border"),
            (1, False, "border"),
            (2, False, "zeros"),
        ]:
            textures1 = TexturesUV(
                maps=[colors1],
                faces_uvs=[faces],
                verts_uvs=[verts_uvs1],
                align_corners=align_corners,
                padding_mode=padding_mode,
            )

            # These downsamplings of colors2 are chosen to ensure a flip and a non flip
            # when the maps are merged.
            # We have maps of size (100, 100), (50, 99) and (99, 50).
            textures2 = TexturesUV(
                maps=[colors2[::2, :-1]],
                faces_uvs=[faces],
                verts_uvs=[verts_uvs2],
                align_corners=align_corners,
                padding_mode=padding_mode,
            )
            offset = torch.tensor([0, 0, 0.5], device=device)
            textures3 = TexturesUV(
                maps=[colors2[:-1, ::2] + offset],
                faces_uvs=[faces],
                verts_uvs=[verts_uvs2],
                align_corners=align_corners,
                padding_mode=padding_mode,
            )
            mesh1 = Meshes(verts=[verts], faces=[faces], textures=textures1)
            mesh2 = Meshes(verts=[verts_shifted1], faces=[faces], textures=textures2)
            mesh3 = Meshes(verts=[verts_shifted2], faces=[faces], textures=textures3)
891
892
893
894
895
            # mesh4 is like mesh1 but outside the field of view. It is here to test
            # that having another texture with the same map doesn't produce
            # two copies in the joined map.
            mesh4 = Meshes(verts=[verts_shifted3], faces=[faces], textures=textures1)
            mesh = join_meshes_as_scene([mesh1, mesh2, mesh3, mesh4])
896
897
898
899
900
901
902
903
904

            output = renderer(mesh)[0, ..., :3].cpu()
            output1 = renderer(mesh1)[0, ..., :3].cpu()
            output2 = renderer(mesh2)[0, ..., :3].cpu()
            output3 = renderer(mesh3)[0, ..., :3].cpu()
            # The background color is white and the objects do not overlap, so we can
            # predict the merged image by taking the minimum over every channel
            merged = torch.min(torch.min(output1, output2), output3)

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
905
906
907
            image_ref = load_rgb_image(
                f"test_joinuvs{i}_{rasterizer_type.__name__}_final.png", DATA_DIR
            )
908
909
910
911
            map_ref = load_rgb_image(f"test_joinuvs{i}_map.png", DATA_DIR)

            if DEBUG:
                Image.fromarray((output.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
912
913
                    DATA_DIR
                    / f"DEBUG_test_joinuvs{i}_{rasterizer_type.__name__}_final.png"
914
                )
915
                Image.fromarray((merged.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
916
917
                    DATA_DIR
                    / f"DEBUG_test_joinuvs{i}_{rasterizer_type.__name__}_merged.png"
918
919
920
                )

                Image.fromarray((output1.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
921
                    DATA_DIR / f"DEBUG_test_joinuvs{i}_{rasterizer_type.__name__}_1.png"
922
923
                )
                Image.fromarray((output2.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
924
                    DATA_DIR / f"DEBUG_test_joinuvs{i}_{rasterizer_type.__name__}_2.png"
925
926
                )
                Image.fromarray((output3.numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
927
                    DATA_DIR / f"DEBUG_test_joinuvs{i}_{rasterizer_type.__name__}_3.png"
928
929
930
931
932
                )
                Image.fromarray(
                    (mesh.textures.maps_padded()[0].cpu().numpy() * 255).astype(
                        np.uint8
                    )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
933
                ).save(DATA_DIR / f"DEBUG_test_joinuvs{i}_map.png")
934
935
936
937
                Image.fromarray(
                    (mesh2.textures.maps_padded()[0].cpu().numpy() * 255).astype(
                        np.uint8
                    )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
938
                ).save(DATA_DIR / f"DEBUG_test_joinuvs{i}_map2.png")
939
940
941
942
                Image.fromarray(
                    (mesh3.textures.maps_padded()[0].cpu().numpy() * 255).astype(
                        np.uint8
                    )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
943
                ).save(DATA_DIR / f"DEBUG_test_joinuvs{i}_map3.png")
944

945
            self.assertClose(output, merged, atol=0.005)
946
            self.assertClose(output, image_ref, atol=0.005)
947
948
            self.assertClose(mesh.textures.maps_padded()[0].cpu(), map_ref, atol=0.05)

949
950
951
952
953
954
955
956
957
958
959
960
    def test_join_uvs_simple(self):
        # Example from issue #826
        a = TexturesUV(
            maps=torch.full((1, 4000, 4000, 3), 0.8),
            faces_uvs=torch.arange(300).reshape(1, 100, 3),
            verts_uvs=torch.rand(1, 300, 2) * 0.4 + 0.1,
        )
        b = TexturesUV(
            maps=torch.full((1, 2000, 2000, 3), 0.7),
            faces_uvs=torch.arange(150).reshape(1, 50, 3),
            verts_uvs=torch.rand(1, 150, 2) * 0.2 + 0.3,
        )
961
962
        self.assertEqual(a._num_faces_per_mesh, [100])
        self.assertEqual(b._num_faces_per_mesh, [50])
963
        c = a.join_batch([b]).join_scene()
964
965
966
        self.assertEqual(a._num_faces_per_mesh, [100])
        self.assertEqual(b._num_faces_per_mesh, [50])
        self.assertEqual(c._num_faces_per_mesh, [150])
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984

        color = c.faces_verts_textures_packed()
        color1 = color[:100, :, 0].flatten()
        color2 = color[100:, :, 0].flatten()
        expect1 = color1.new_tensor(0.8)
        expect2 = color2.new_tensor(0.7)
        self.assertClose(color1.min(), expect1)
        self.assertClose(color1.max(), expect1)
        self.assertClose(color2.min(), expect2)
        self.assertClose(color2.max(), expect2)

        if DEBUG:
            from pytorch3d.vis.texture_vis import texturesuv_image_PIL as PI

            PI(a, radius=5).save(DATA_DIR / "test_join_uvs_simple_a.png")
            PI(b, radius=5).save(DATA_DIR / "test_join_uvs_simple_b.png")
            PI(c, radius=5).save(DATA_DIR / "test_join_uvs_simple_c.png")

985
    def test_join_verts(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
986
987
        self._join_verts(MeshRasterizer)

988
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
989
990
991
992
    def test_join_verts_opengl(self):
        self._join_verts(MeshRasterizerOpenGL)

    def _join_verts(self, rasterizer_type):
993
994
995
996
997
        """Meshes with TexturesVertex joined into a scene"""
        # Test the result of rendering two tori with separate textures.
        # The expected result is consistent with rendering them each alone.
        torch.manual_seed(1)
        device = torch.device("cuda:0")
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
998

999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
        plain_torus = torus(r=1, R=4, sides=5, rings=6, device=device)
        [verts] = plain_torus.verts_list()
        verts_shifted1 = verts.clone()
        verts_shifted1 *= 0.5
        verts_shifted1[:, 1] += 7

        faces = plain_torus.faces_list()
        textures1 = TexturesVertex(verts_features=[torch.rand_like(verts)])
        textures2 = TexturesVertex(verts_features=[torch.rand_like(verts)])
        mesh1 = Meshes(verts=[verts], faces=faces, textures=textures1)
        mesh2 = Meshes(verts=[verts_shifted1], faces=faces, textures=textures2)
        mesh = join_meshes_as_scene([mesh1, mesh2])

        R, T = look_at_view_transform(18, 0, 0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)

        raster_settings = RasterizationSettings(
            image_size=256, blur_radius=0.0, faces_per_pixel=1
        )

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
1019
        lights = AmbientLights(device=device)
1020
        blend_params = BlendParams(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1021
            sigma=0.5,
1022
1023
1024
            gamma=1e-4,
            background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
        )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1025
1026
1027
        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            shader = HardPhongShader(
1028
                device=device, blend_params=blend_params, cameras=cameras, lights=lights
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1029
1030
1031
1032
1033
1034
1035
            )
        else:
            shader = SplatterPhongShader(
                device=device, blend_params=blend_params, cameras=cameras, lights=lights
            )

        renderer = MeshRenderer(rasterizer, shader)
1036
1037
1038

        output = renderer(mesh)

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1039
1040
1041
        image_ref = load_rgb_image(
            f"test_joinverts_final_{rasterizer_type.__name__}.png", DATA_DIR
        )
1042
1043
1044
1045
1046
1047
1048

        if DEBUG:
            debugging_outputs = []
            for mesh_ in [mesh1, mesh2]:
                debugging_outputs.append(renderer(mesh_))
            Image.fromarray(
                (output[0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1049
1050
1051
            ).save(
                DATA_DIR / f"DEBUG_test_joinverts_final_{rasterizer_type.__name__}.png"
            )
1052
1053
            Image.fromarray(
                (debugging_outputs[0][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1054
            ).save(DATA_DIR / "DEBUG_test_joinverts_1.png")
1055
1056
            Image.fromarray(
                (debugging_outputs[1][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1057
            ).save(DATA_DIR / "DEBUG_test_joinverts_2.png")
1058
1059
1060
1061
1062

        result = output[0, ..., :3].cpu()
        self.assertClose(result, image_ref, atol=0.05)

    def test_join_atlas(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1063
1064
        self._join_atlas(MeshRasterizer)

1065
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1066
1067
1068
1069
    def test_join_atlas_opengl(self):
        self._join_atlas(MeshRasterizerOpenGL)

    def _join_atlas(self, rasterizer_type):
1070
1071
1072
1073
1074
        """Meshes with TexturesAtlas joined into a scene"""
        # Test the result of rendering two tori with separate textures.
        # The expected result is consistent with rendering them each alone.
        torch.manual_seed(1)
        device = torch.device("cuda:0")
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1075

1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
        plain_torus = torus(r=1, R=4, sides=5, rings=6, device=device)
        [verts] = plain_torus.verts_list()
        verts_shifted1 = verts.clone()
        verts_shifted1 *= 1.2
        verts_shifted1[:, 0] += 4
        verts_shifted1[:, 1] += 5
        verts[:, 0] -= 4
        verts[:, 1] -= 4

        [faces] = plain_torus.faces_list()
        map_size = 3
        # Two random atlases.
        # The averaging of the random numbers here is not consistent with the
        # meaning of the atlases, but makes each face a bit smoother than
        # if everything had a random color.
        atlas1 = torch.rand(size=(faces.shape[0], map_size, map_size, 3), device=device)
        atlas1[:, 1] = 0.5 * atlas1[:, 0] + 0.5 * atlas1[:, 2]
        atlas1[:, :, 1] = 0.5 * atlas1[:, :, 0] + 0.5 * atlas1[:, :, 2]
        atlas2 = torch.rand(size=(faces.shape[0], map_size, map_size, 3), device=device)
        atlas2[:, 1] = 0.5 * atlas2[:, 0] + 0.5 * atlas2[:, 2]
        atlas2[:, :, 1] = 0.5 * atlas2[:, :, 0] + 0.5 * atlas2[:, :, 2]

        textures1 = TexturesAtlas(atlas=[atlas1])
        textures2 = TexturesAtlas(atlas=[atlas2])
        mesh1 = Meshes(verts=[verts], faces=[faces], textures=textures1)
        mesh2 = Meshes(verts=[verts_shifted1], faces=[faces], textures=textures2)
1102
1103
        self.assertEqual(textures1._num_faces_per_mesh, [len(faces)])
        self.assertEqual(textures2._num_faces_per_mesh, [len(faces)])
1104
        mesh_joined = join_meshes_as_scene([mesh1, mesh2])
1105
1106
1107
        self.assertEqual(textures1._num_faces_per_mesh, [len(faces)])
        self.assertEqual(textures2._num_faces_per_mesh, [len(faces)])
        self.assertEqual(mesh_joined.textures._num_faces_per_mesh, [len(faces) * 2])
1108
1109
1110
1111
1112

        R, T = look_at_view_transform(18, 0, 0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)

        raster_settings = RasterizationSettings(
1113
1114
1115
            image_size=512,
            blur_radius=0.0,
            faces_per_pixel=1,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1116
            perspective_correct=rasterizer_type.__name__ == "MeshRasterizerOpenGL",
1117
1118
        )

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
1119
        lights = AmbientLights(device=device)
1120
        blend_params = BlendParams(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1121
            sigma=0.5,
1122
1123
1124
            gamma=1e-4,
            background_color=torch.tensor([1.0, 1.0, 1.0], device=device),
        )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1125
1126
1127
1128

        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            shader = HardPhongShader(
1129
                device=device, blend_params=blend_params, cameras=cameras, lights=lights
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1130
1131
1132
1133
1134
1135
1136
            )
        else:
            shader = SplatterPhongShader(
                device=device, blend_params=blend_params, cameras=cameras, lights=lights
            )

        renderer = MeshRenderer(rasterizer, shader)
1137
1138
1139

        output = renderer(mesh_joined)

Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1140
1141
1142
        image_ref = load_rgb_image(
            f"test_joinatlas_final_{rasterizer_type.__name__}.png", DATA_DIR
        )
1143
1144
1145
1146
1147
1148
1149

        if DEBUG:
            debugging_outputs = []
            for mesh_ in [mesh1, mesh2]:
                debugging_outputs.append(renderer(mesh_))
            Image.fromarray(
                (output[0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1150
1151
1152
            ).save(
                DATA_DIR / f"DEBUG_test_joinatlas_final_{rasterizer_type.__name__}.png"
            )
1153
1154
            Image.fromarray(
                (debugging_outputs[0][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1155
            ).save(DATA_DIR / f"test_joinatlas_1_{rasterizer_type.__name__}.png")
1156
1157
            Image.fromarray(
                (debugging_outputs[1][0, ..., :3].cpu().numpy() * 255).astype(np.uint8)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1158
            ).save(DATA_DIR / f"test_joinatlas_2_{rasterizer_type.__name__}.png")
1159
1160
1161
1162

        result = output[0, ..., :3].cpu()
        self.assertClose(result, image_ref, atol=0.05)

1163
    def test_joined_spheres(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1164
1165
        self._joined_spheres(MeshRasterizer)

1166
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1167
1168
1169
1170
    def test_joined_spheres_opengl(self):
        self._joined_spheres(MeshRasterizerOpenGL)

    def _joined_spheres(self, rasterizer_type):
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
        """
        Test a list of Meshes can be joined as a single mesh and
        the single mesh is rendered correctly with Phong, Gouraud
        and Flat Shaders.
        """
        device = torch.device("cuda:0")

        # Init mesh with vertex textures.
        # Initialize a list containing two ico spheres of different sizes.
        sphere_list = [ico_sphere(3, device), ico_sphere(4, device)]
        # [(42 verts, 80 faces), (162 verts, 320 faces)]
        # The scale the vertices need to be set at to resize the spheres
        scales = [0.25, 1]
        # The distance the spheres ought to be offset horizontally to prevent overlap.
        offsets = [1.2, -0.3]
        # Initialize a list containing the adjusted sphere meshes.
        sphere_mesh_list = []
        for i in range(len(sphere_list)):
            verts = sphere_list[i].verts_padded() * scales[i]
            verts[0, :, 0] += offsets[i]
            sphere_mesh_list.append(
                Meshes(verts=verts, faces=sphere_list[i].faces_padded())
            )
1194
        joined_sphere_mesh = join_meshes_as_scene(sphere_mesh_list)
Nikhila Ravi's avatar
Nikhila Ravi committed
1195
1196
        joined_sphere_mesh.textures = TexturesVertex(
            verts_features=torch.ones_like(joined_sphere_mesh.verts_padded())
1197
1198
1199
1200
        )

        # Init rasterizer settings
        R, T = look_at_view_transform(2.7, 0.0, 0.0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
1201
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
1202
        raster_settings = RasterizationSettings(
1203
1204
1205
            image_size=512,
            blur_radius=0.0,
            faces_per_pixel=1,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1206
            perspective_correct=rasterizer_type.__name__ == "MeshRasterizerOpenGL",
1207
1208
1209
1210
1211
1212
        )

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
        lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1213
        blend_params = BlendParams(0.5, 1e-4, (0, 0, 0))
1214
1215

        # Init renderer
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1216
        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
1217
1218
1219
1220
        shaders = {
            "phong": HardPhongShader,
            "gouraud": HardGouraudShader,
            "flat": HardFlatShader,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1221
            "splatter": SplatterPhongShader,
1222
        }
1223
        for name, shader_init in shaders.items():
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1224
1225
1226
1227
1228
            if rasterizer_type == MeshRasterizerOpenGL and name != "splatter":
                continue
            if rasterizer_type == MeshRasterizer and name == "splatter":
                continue

1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
            shader = shader_init(
                lights=lights,
                cameras=cameras,
                materials=materials,
                blend_params=blend_params,
            )
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            image = renderer(joined_sphere_mesh)
            rgb = image[..., :3].squeeze().cpu()
            if DEBUG:
                file_name = "DEBUG_joined_spheres_%s.png" % name
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / file_name
                )
            image_ref = load_rgb_image("test_joined_spheres_%s.png" % name, DATA_DIR)
            self.assertClose(rgb, image_ref, atol=0.05)
Nikhila Ravi's avatar
Nikhila Ravi committed
1245
1246

    def test_texture_map_atlas(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1247
1248
        self._texture_map_atlas(MeshRasterizer)

1249
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1250
1251
1252
1253
    def test_texture_map_atlas_opengl(self):
        self._texture_map_atlas(MeshRasterizerOpenGL)

    def _texture_map_atlas(self, rasterizer_type):
Nikhila Ravi's avatar
Nikhila Ravi committed
1254
1255
        """
        Test a mesh with a texture map as a per face atlas is loaded and rendered correctly.
Nikhila Ravi's avatar
Nikhila Ravi committed
1256
        Also check that the backward pass for texture atlas rendering is differentiable.
Nikhila Ravi's avatar
Nikhila Ravi committed
1257
1258
        """
        device = torch.device("cuda:0")
1259
1260

        obj_filename = TUTORIAL_DATA_DIR / "cow_mesh/cow.obj"
Nikhila Ravi's avatar
Nikhila Ravi committed
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270

        # Load mesh and texture as a per face texture atlas.
        verts, faces, aux = load_obj(
            obj_filename,
            device=device,
            load_textures=True,
            create_texture_atlas=True,
            texture_atlas_size=8,
            texture_wrap=None,
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
1271
        atlas = aux.texture_atlas
Nikhila Ravi's avatar
Nikhila Ravi committed
1272
1273
1274
        mesh = Meshes(
            verts=[verts],
            faces=[faces.verts_idx],
Nikhila Ravi's avatar
Nikhila Ravi committed
1275
            textures=TexturesAtlas(atlas=[atlas]),
Nikhila Ravi's avatar
Nikhila Ravi committed
1276
1277
1278
1279
        )

        # Init rasterizer settings
        R, T = look_at_view_transform(2.7, 0, 0)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
1280
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)
Nikhila Ravi's avatar
Nikhila Ravi committed
1281
1282

        raster_settings = RasterizationSettings(
Nikhila Ravi's avatar
Nikhila Ravi committed
1283
1284
1285
1286
            image_size=512,
            blur_radius=0.0,
            faces_per_pixel=1,
            cull_backfaces=True,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1287
            perspective_correct=rasterizer_type.__name__ == "MeshRasterizerOpenGL",
Nikhila Ravi's avatar
Nikhila Ravi committed
1288
1289
1290
1291
        )

        # Init shader settings
        materials = Materials(device=device, specular_color=((0, 0, 0),), shininess=0.0)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1292
        blend_params = BlendParams(0.5, 1e-4, (1.0, 1.0, 1.0))
Nikhila Ravi's avatar
Nikhila Ravi committed
1293
1294
1295
1296
1297
1298
1299
        lights = PointLights(device=device)

        # Place light behind the cow in world space. The front of
        # the cow is facing the -z direction.
        lights.location = torch.tensor([0.0, 0.0, 2.0], device=device)[None]

        # The HardPhongShader can be used directly with atlas textures.
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
        rasterizer = rasterizer_type(cameras=cameras, raster_settings=raster_settings)
        if rasterizer_type == MeshRasterizer:
            shader = HardPhongShader(
                device=device,
                blend_params=blend_params,
                cameras=cameras,
                lights=lights,
                materials=materials,
            )
        else:
            shader = SplatterPhongShader(
                device=device,
                blend_params=blend_params,
                cameras=cameras,
                lights=lights,
                materials=materials,
            )

        renderer = MeshRenderer(rasterizer, shader)
Nikhila Ravi's avatar
Nikhila Ravi committed
1319
1320

        images = renderer(mesh)
Nikhila Ravi's avatar
Nikhila Ravi committed
1321
        rgb = images[0, ..., :3].squeeze()
Nikhila Ravi's avatar
Nikhila Ravi committed
1322
1323

        # Load reference image
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1324
1325
1326
        image_ref = load_rgb_image(
            f"test_texture_atlas_8x8_back_{rasterizer_type.__name__}.png", DATA_DIR
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
1327
1328

        if DEBUG:
Nikhila Ravi's avatar
Nikhila Ravi committed
1329
            Image.fromarray((rgb.detach().cpu().numpy() * 255).astype(np.uint8)).save(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1330
1331
                DATA_DIR
                / f"DEBUG_texture_atlas_8x8_back_{rasterizer_type.__name__}.png"
Nikhila Ravi's avatar
Nikhila Ravi committed
1332
1333
            )

Nikhila Ravi's avatar
Nikhila Ravi committed
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
        self.assertClose(rgb.cpu(), image_ref, atol=0.05)

        # Check gradients are propagated
        # correctly back to the texture atlas.
        # Because of how texture sampling is implemented
        # for the texture atlas it is not possible to get
        # gradients back to the vertices.
        atlas.requires_grad = True
        mesh = Meshes(
            verts=[verts],
            faces=[faces.verts_idx],
            textures=TexturesAtlas(atlas=[atlas]),
        )
        raster_settings = RasterizationSettings(
            image_size=512,
            blur_radius=0.0001,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1350
1351
            faces_per_pixel=5 if rasterizer_type.__name__ == "MeshRasterizer" else 1,
            cull_backfaces=rasterizer_type.__name__ == "MeshRasterizer",
Nikhila Ravi's avatar
Nikhila Ravi committed
1352
1353
1354
1355
1356
1357
            clip_barycentric_coords=True,
        )
        images = renderer(mesh, raster_settings=raster_settings)
        images[0, ...].sum().backward()

        fragments = rasterizer(mesh, raster_settings=raster_settings)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1358
1359
1360
1361
        if rasterizer_type == MeshRasterizer:
            # Some of the bary coordinates are outside the
            # [0, 1] range as expected because the blur is > 0.
            self.assertTrue(fragments.bary_coords.ge(1.0).any())
Nikhila Ravi's avatar
Nikhila Ravi committed
1362
1363
        self.assertIsNotNone(atlas.grad)
        self.assertTrue(atlas.grad.sum().abs() > 0.0)
1364
1365

    def test_simple_sphere_outside_zfar(self):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1366
1367
        self._simple_sphere_outside_zfar(MeshRasterizer)

1368
    @usesOpengl
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1369
1370
1371
1372
    def test_simple_sphere_outside_zfar_opengl(self):
        self._simple_sphere_outside_zfar(MeshRasterizerOpenGL)

    def _simple_sphere_outside_zfar(self, rasterizer_type):
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
        """
        Test output when rendering a sphere that is beyond zfar with a SoftPhongShader.
        This renders a sphere of radius 500, with the camera at x=1500 for different
        settings of zfar.  This is intended to check 1) setting cameras.zfar propagates
        to the blender and that the rendered sphere is (soft) clipped if it is beyond
        zfar, 2) make sure there are no numerical precision/overflow errors associated
        with larger world coordinates
        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded() * 500
        faces_padded = sphere_mesh.faces_padded()
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)

        R, T = look_at_view_transform(1500, 0.0, 0.0)

        # Init shader settings
        materials = Materials(device=device)
        lights = PointLights(device=device)
        lights.location = torch.tensor([0.0, 0.0, +1000.0], device=device)[None]

        raster_settings = RasterizationSettings(
            image_size=256, blur_radius=0.0, faces_per_pixel=1
        )
        for zfar in (10000.0, 100.0):
            cameras = FoVPerspectiveCameras(
                device=device, R=R, T=T, aspect_ratio=1.0, fov=60.0, zfar=zfar
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1405
1406
            blend_params = BlendParams(
                1e-4 if rasterizer_type == MeshRasterizer else 0.5, 1e-4, (0, 0, 1.0)
1407
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1408
1409
            rasterizer = rasterizer_type(
                cameras=cameras, raster_settings=raster_settings
1410
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
            if rasterizer_type == MeshRasterizer:
                shader = SoftPhongShader(
                    blend_params=blend_params,
                    cameras=cameras,
                    lights=lights,
                    materials=materials,
                )
            else:
                shader = SplatterPhongShader(
                    device=device,
                    blend_params=blend_params,
                    cameras=cameras,
                    lights=lights,
                    materials=materials,
                )
1426
1427
1428
1429
            renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
            images = renderer(sphere_mesh)
            rgb = images[0, ..., :3].squeeze().cpu()

Jeremy Reizenstein's avatar
lints  
Jeremy Reizenstein committed
1430
1431
1432
1433
            filename = (
                "test_simple_sphere_outside_zfar_"
                f"{int(zfar)}_{rasterizer_type.__name__}.png"
            )
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443

            # Load reference image
            image_ref = load_rgb_image(filename, DATA_DIR)

            if DEBUG:
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / ("DEBUG_" + filename)
                )

            self.assertClose(rgb, image_ref, atol=0.05)
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460

    def test_cameras_kwarg(self):
        """
        Test that when cameras are passed in as a kwarg the rendering
        works as expected
        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)

        # No elevation or azimuth rotation
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1461
1462
1463
        rasterizer_tests = [
            RasterizerTest(MeshRasterizer, HardPhongShader, "phong", "hard_phong"),
        ]
1464
1465
1466
1467
1468
1469
1470
1471
1472
        if not skip_opengl_requested():
            rasterizer_tests.append(
                RasterizerTest(
                    MeshRasterizerOpenGL,
                    SplatterPhongShader,
                    "splatter",
                    "splatter_phong",
                )
            )
1473
1474
1475
1476
1477
1478
1479
        R, T = look_at_view_transform(2.7, 0.0, 0.0)
        for cam_type in (
            FoVPerspectiveCameras,
            FoVOrthographicCameras,
            PerspectiveCameras,
            OrthographicCameras,
        ):
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
            for test in rasterizer_tests:
                if test.rasterizer == MeshRasterizerOpenGL and cam_type in [
                    PerspectiveCameras,
                    OrthographicCameras,
                ]:
                    # MeshRasterizerOpenGL only works with FoV cameras.
                    continue

                cameras = cam_type(device=device, R=R, T=T)

                # Init shader settings
                materials = Materials(device=device)
                lights = PointLights(device=device)
                lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

                raster_settings = RasterizationSettings(
                    image_size=512, blur_radius=0.0, faces_per_pixel=1
                )
                rasterizer = test.rasterizer(raster_settings=raster_settings)
                blend_params = BlendParams(0.5, 1e-4, (0, 0, 0))
                shader = test.shader(
                    lights=lights, materials=materials, blend_params=blend_params
                )
                renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)

                # Cameras can be passed into the renderer in the forward pass
                images = renderer(sphere_mesh, cameras=cameras)
                rgb = images.squeeze()[..., :3].cpu().numpy()
                image_ref = load_rgb_image(
                    f"test_simple_sphere_light_{test.reference_name}_{cam_type.__name__}.png",
                    DATA_DIR,
                )
                self.assertClose(rgb, image_ref, atol=0.05)

1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
    def test_nd_sphere(self):
        """
        Test that the render can handle textures with more than 3 channels and
        not just 3 channel RGB.
        """
        torch.manual_seed(1)
        device = torch.device("cuda:0")
        C = 5
        WHITE = ((1.0,) * C,)
        BLACK = ((0.0,) * C,)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1524

1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
        feats = torch.ones(*verts_padded.shape[:-1], C, device=device)
        n_verts = feats.shape[1]
        # make some non-uniform pattern
        feats *= torch.arange(0, 10, step=10 / n_verts, device=device).unsqueeze(1)
        textures = TexturesVertex(verts_features=feats)
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1535

1536
1537
        # No elevation or azimuth rotation
        R, T = look_at_view_transform(2.7, 0.0, 0.0)
1538

1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
        cameras = PerspectiveCameras(device=device, R=R, T=T)

        # Init shader settings
        materials = Materials(
            device=device,
            ambient_color=WHITE,
            diffuse_color=WHITE,
            specular_color=WHITE,
        )
        lights = AmbientLights(
            device=device,
            ambient_color=WHITE,
        )
        lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

        raster_settings = RasterizationSettings(
            image_size=512, blur_radius=0.0, faces_per_pixel=1
        )
        rasterizer = MeshRasterizer(cameras=cameras, raster_settings=raster_settings)
        blend_params = BlendParams(
            1e-4,
            1e-4,
            background_color=BLACK[0],
        )

        # only test HardFlatShader since that's the only one that makes
        # sense for classification
        shader = HardFlatShader(
            lights=lights,
            cameras=cameras,
            materials=materials,
            blend_params=blend_params,
        )
        renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
        images = renderer(sphere_mesh)

        self.assertEqual(images.shape[-1], C + 1)
        self.assertClose(images.amax(), torch.tensor(10.0), atol=0.01)
        self.assertClose(images.amin(), torch.tensor(0.0), atol=0.01)

        # grab last 3 color channels
        rgb = (images[0, ..., C - 3 : C] / 10).squeeze().cpu()
        filename = "test_nd_sphere.png"

        if DEBUG:
            debug_filename = "DEBUG_%s" % filename
            Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                DATA_DIR / debug_filename
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1587
            )
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642

        image_ref = load_rgb_image(filename, DATA_DIR)
        self.assertClose(rgb, image_ref, atol=0.05)

    def test_simple_sphere_fisheye_params(self):
        """
        Test output of phong and gouraud shading matches a reference image using
        the default values for the light sources.

        """
        device = torch.device("cuda:0")

        # Init mesh
        sphere_mesh = ico_sphere(5, device)
        verts_padded = sphere_mesh.verts_padded()
        faces_padded = sphere_mesh.faces_padded()
        feats = torch.ones_like(verts_padded, device=device)
        textures = TexturesVertex(verts_features=feats)
        sphere_mesh = Meshes(verts=verts_padded, faces=faces_padded, textures=textures)

        # Init rasterizer settings
        R, T = look_at_view_transform(2.7, 0.0, 0.0)
        postfix = "_"

        cam_kwargs = [
            {
                "radial_params": torch.tensor(
                    [
                        [-1, -2, -3, 0, 0, 1],
                    ],
                    dtype=torch.float32,
                ),
            },
            {
                "tangential_params": torch.tensor(
                    [[0.7002747019, -0.4005228974]], dtype=torch.float32
                ),
            },
            {
                "thin_prism_params": torch.tensor(
                    [
                        [
                            -1.000134884,
                            -1.000084822,
                            -1.0009420014,
                            -1.0001276838,
                        ],
                    ],
                    dtype=torch.float32,
                ),
            },
        ]
        variants = ["radial", "tangential", "prism"]
        for test_case, variant in zip(cam_kwargs, variants):
            cameras = FishEyeCameras(
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1643
                device=device,
1644
1645
1646
1647
1648
1649
1650
                R=R,
                T=T,
                use_tangential=True,
                use_radial=True,
                use_thin_prism=True,
                world_coordinates=True,
                **test_case,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1651
            )
1652
1653
1654
1655

            # Init shader settings
            materials = Materials(device=device)
            lights = PointLights(device=device)
1656
1657
1658
1659
1660
            lights.location = torch.tensor([0.0, 0.0, +2.0], device=device)[None]

            raster_settings = RasterizationSettings(
                image_size=512, blur_radius=0.0, faces_per_pixel=1
            )
1661
            blend_params = BlendParams(0.5, 1e-4, (0, 0, 0))
1662

1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
            # Test several shaders
            rasterizer_tests = [
                RasterizerTest(
                    MeshRasterizer, HardPhongShader, "hard_phong", "hard_phong"
                ),
                RasterizerTest(
                    MeshRasterizer, HardGouraudShader, "hard_gouraud", "hard_gouraud"
                ),
                RasterizerTest(
                    MeshRasterizer, HardFlatShader, "hard_flat", "hard_flat"
                ),
            ]
            for test in rasterizer_tests:
                shader = test.shader(
                    lights=lights,
                    cameras=cameras,
                    materials=materials,
                    blend_params=blend_params,
                )
                if test.rasterizer == MeshRasterizer:
                    rasterizer = test.rasterizer(
                        cameras=cameras, raster_settings=raster_settings
                    )

                renderer = MeshRenderer(rasterizer=rasterizer, shader=shader)
                images = renderer(sphere_mesh)

                rgb = images[0, ..., :3].squeeze().cpu()
                filename = "simple_sphere_light_%s%s%s%s%s.png" % (
                    test.reference_name,
                    postfix,
                    variant,
                    postfix,
                    FishEyeCameras.__name__,
                )

                image_ref = load_rgb_image("test_%s" % filename, DATA_DIR)
                if DEBUG:
                    debug_filename = "simple_sphere_light_%s%s%s%s%s.png" % (
                        test.debug_name,
                        postfix,
                        variant,
                        postfix,
                        FishEyeCameras.__name__,
                    )
                    filename = "DEBUG_%s" % debug_filename
                    Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                        DATA_DIR / filename
                    )
                self.assertClose(rgb, image_ref, atol=0.05)

            ########################################################
            # Move the light to the +z axis in world space so it is
            # behind the sphere. Note that +Z is in, +Y up,
            # +X left for both world and camera space.
            ########################################################
            lights.location[..., 2] = -2.0
            phong_shader = HardPhongShader(
1721
                lights=lights,
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1722
                cameras=cameras,
1723
1724
1725
                materials=materials,
                blend_params=blend_params,
            )
1726

1727
1728
1729
            phong_renderer = MeshRenderer(rasterizer=rasterizer, shader=phong_shader)
            images = phong_renderer(sphere_mesh, lights=lights)
            rgb = images[0, ..., :3].squeeze().cpu()
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1730
            if DEBUG:
1731
1732
1733
1734
1735
1736
                filename = "DEBUG_simple_sphere_dark%s%s%s%s.png" % (
                    postfix,
                    variant,
                    postfix,
                    FishEyeCameras.__name__,
                )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1737
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
1738
                    DATA_DIR / filename
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1739
                )
1740

1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
            image_ref_phong_dark = load_rgb_image(
                "test_simple_sphere_dark%s%s%s%s.png"
                % (postfix, variant, postfix, FishEyeCameras.__name__),
                DATA_DIR,
            )
            # Soft shaders (SplatterPhong) will have a different boundary than hard
            # ones, but should be identical otherwise.
            self.assertLess((rgb - image_ref_phong_dark).quantile(0.99), 0.005)

    def test_fisheye_cow_mesh(self):
        """
        Test FishEye Camera distortions on real meshes
        """
        device = torch.device("cuda:0")
        obj_filename = os.path.join(DATA_DIR, "missing_usemtl/cow.obj")
        mesh = load_objs_as_meshes([obj_filename], device=device)
        R, T = look_at_view_transform(2.7, 0, 180)
        radial_params = torch.tensor([[-1.0, 1.0, 1.0, 0.0, 0.0, -1.0]])
        tangential_params = torch.tensor([[0.5, 0.5]])
        thin_prism_params = torch.tensor([[0.5, 0.5, 0.5, 0.5]])
        combinations = product([False, True], repeat=3)
        for combination in combinations:
            cameras = FishEyeCameras(
                device=device,
                R=R,
                T=T,
                world_coordinates=True,
                use_radial=combination[0],
                use_tangential=combination[1],
                use_thin_prism=combination[2],
                radial_params=radial_params,
                tangential_params=tangential_params,
                thin_prism_params=thin_prism_params,
            )
            raster_settings = RasterizationSettings(
                image_size=512,
                blur_radius=0.0,
                faces_per_pixel=1,
            )
            lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]])
            renderer = MeshRenderer(
                rasterizer=MeshRasterizer(
                    cameras=cameras, raster_settings=raster_settings
                ),
                shader=SoftPhongShader(device=device, cameras=cameras, lights=lights),
            )
            images = renderer(mesh)
            rgb = images[0, ..., :3].squeeze().cpu()
            filename = "test_cow_mesh_%s_radial_%s_tangential_%s_prism_%s.png" % (
                FishEyeCameras.__name__,
                combination[0],
                combination[1],
                combination[2],
            )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1795
            image_ref = load_rgb_image(filename, DATA_DIR)
1796
1797
1798
1799
1800
            if DEBUG:
                filename = filename.replace("test", "DEBUG")
                Image.fromarray((rgb.numpy() * 255).astype(np.uint8)).save(
                    DATA_DIR / filename
                )
Krzysztof Chalupka's avatar
Krzysztof Chalupka committed
1801
            self.assertClose(rgb, image_ref, atol=0.05)