1#!/usr/bin/env python
2#
3# This file is part of libigl, a simple c++ geometry processing library.
4#
5# Copyright (C) 2017 Sebastian Koch <s.koch@tu-berlin.de> and Daniele Panozzo <daniele.panozzo@gmail.com>
6#
7# This Source Code Form is subject to the terms of the Mozilla Public License
8# v. 2.0. If a copy of the MPL was not distributed with this file, You can
9# obtain one at http://mozilla.org/MPL/2.0/.
10import sys, os
11
12# Add the igl library to the modules search path
13sys.path.insert(0, os.getcwd() + "/../")
14import pyigl as igl
15
16from shared import TUTORIAL_SHARED_PATH, check_dependencies
17
18dependencies = ["png", "glfw"]
19check_dependencies(dependencies)
20
21temp_png = os.path.join(os.getcwd(),"out.png")
22
23def key_down(viewer, key, modifier):
24    if key == ord('1'):
25        # Allocate temporary buffers
26        R = igl.eigen.MatrixXuc(1280, 800)
27        G = igl.eigen.MatrixXuc(1280, 800)
28        B = igl.eigen.MatrixXuc(1280, 800)
29        A = igl.eigen.MatrixXuc(1280, 800)
30
31        # Draw the scene in the buffers
32        viewer.core.draw_buffer(viewer.data(), False, R, G, B, A)
33
34        # Save it to a PNG
35        igl.png.writePNG(R, G, B, A, temp_png)
36    elif key == ord('2'):
37        # Allocate temporary buffers
38        R = igl.eigen.MatrixXuc()
39        G = igl.eigen.MatrixXuc()
40        B = igl.eigen.MatrixXuc()
41        A = igl.eigen.MatrixXuc()
42
43        # Read the PNG
44        igl.png.readPNG(temp_png, R, G, B, A)
45
46        # Replace the mesh with a triangulated square
47        V = igl.eigen.MatrixXd([[-0.5, -0.5, 0],
48                                [0.5, -0.5, 0],
49                                [0.5, 0.5, 0],
50                                [-0.5, 0.5, 0]])
51
52        F = igl.eigen.MatrixXd([[0, 1, 2], [2, 3, 0]]).castint()
53
54        UV = igl.eigen.MatrixXd([[0, 0], [1, 0], [1, 1], [0, 1]])
55
56        viewer.data().clear()
57        viewer.data().set_mesh(V, F)
58        viewer.data().set_uv(UV)
59        viewer.core.align_camera_center(V)
60        viewer.data().show_texture = True
61
62        # Use the image as a texture
63        viewer.data().set_texture(R, G, B)
64
65    else:
66        return False
67
68    return True
69
70
71if __name__ == "__main__":
72    V = igl.eigen.MatrixXd()
73    F = igl.eigen.MatrixXi()
74
75    # Load meshes in OFF format
76    igl.readOFF(TUTORIAL_SHARED_PATH + "bunny.off", V, F)
77
78    viewer = igl.glfw.Viewer()
79
80    print(
81        "Usage: Press 1 to render the scene and save it in a png. \nPress 2 to load the saved png and use it as a texture.")
82
83    viewer.callback_key_down = key_down
84    viewer.data().set_mesh(V, F)
85    viewer.launch()
86
87    os.remove(temp_png)
88