相同的代码,但在不同平台上产生不同的结果。

huangapple go评论108阅读模式
英文:

Same code but different results from different platform

问题

我明白你的请求,以下是翻译好的代码部分:

  1. # cube.py文件中的一部分
  2. class Cube(object):
  3. def __init__(self, vert_shader, frag_shader):
  4. self.vertices = np.array([
  5. # 在这里指定顶点坐标
  6. [-0.5, -0.5, -0.5], # A 0
  7. [0.5, -0.5, -0.5], # B 1
  8. [0.5, -0.5, 0.5], # C 2
  9. [-0.5, -0.5, 0.5], # D 3
  10. [-0.5, 0.5, -0.5], # E 4
  11. [0.5, 0.5, -0.5], # F 5
  12. [0.5, 0.5, 0.5], # G 6
  13. [-0.5, 0.5, 0.5] # H 7
  14. ], dtype=np.float32)
  15. self.indices = np.array([
  16. # 在这里指定索引
  17. 4, 7, 5, 6, # 顶部
  18. 6, 0,
  19. 0, 4, 1, 5, 2, 6, 3, 7, 0, 4, # 侧面
  20. 5, 1,
  21. 0, 3, 1, 2 # 底部
  22. ])
  23. # 在这里使用坐标计算顶点法线
  24. normals = np.random.normal(0, 1, (self.vertices.shape[0], 3)).astype(np.float32)
  25. normals[:, 2] = np.abs(normals[:, 2])
  26. self.normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)
  27. # 颜色:RGB格式
  28. self.colors = np.array([
  29. # 在这里指定顶点颜色
  30. [0.0, 0.0, 0.0], # 黑色
  31. [1.0, 0.0, 0.0], # 红色
  32. [1.0, 1.0, 0.0], # 黄色
  33. [0.0, 1.0, 0.0], # 绿色
  34. [0.0, 0.0, 1.0], # 蓝色
  35. [1.0, 0.0, 1.0], # 洋红色
  36. [1.0, 1.0, 1.0], # 白色
  37. [0.0, 1.0, 1.0] # 青色
  38. ], dtype=np.float32)
  39. # libs/buffer.py文件中的一部分
  40. class VAO(object):
  41. def __init__(self):
  42. self.vao = GL.glGenVertexArrays(1)
  43. GL.glBindVertexArray(self.vao)
  44. GL.glBindVertexArray(0)
  45. self.vbo = {}
  46. self.ebo = None
  47. def add_vbo(self, location, data, ncomponents=3, dtype=GL.GL_FLOAT, normalized=False, stride=0, offset=None):
  48. self.activate()
  49. buffer_idx = GL.glGenBuffers(1)
  50. GL.glBindBuffer(GL.GL_ARRAY_BUFFER, buffer_idx)
  51. GL.glBufferData(GL.GL_ARRAY_BUFFER, data, GL.GL_STATIC_DRAW)
  52. GL.glVertexAttribPointer(location, ncomponents, dtype, normalized, stride, offset)
  53. GL.glEnableVertexAttribArray(location)
  54. self.vbo[location] = buffer_idx
  55. self.deactivate()
  56. # viewer.py文件中的一部分
  57. class Viewer:
  58. def __init__(self, width=800, height=800):
  59. self.fill_modes = cycle([GL.GL_LINE, GL.GL_POINT, GL.GL_FILL])
  60. # 窗口创建及其他初始化
  61. def run(self):
  62. while not glfw.window_should_close(self.win):
  63. # 清空绘制缓冲区
  64. GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
  65. win_size = glfw.get_window_size(self.win)
  66. view = self.trackball.view_matrix()
  67. projection = self.trackball.projection_matrix(win_size)
  68. # 绘制场景对象
  69. for drawable in self.drawables:
  70. drawable.draw(projection, view, None)
  71. # 刷新绘制命令,交换绘制缓冲区
  72. glfw.swap_buffers(self.win)
  73. # 处理事件
  74. glfw.poll_events()
  75. # 主程序和场景设置
  76. def main():
  77. viewer = Viewer()
  78. # 放置基本对象的实例
  79. model = Cube("./gouraud.vert", "./gouraud.frag").setup()
  80. viewer.add(model)
  81. viewer.run()
  82. if __name__ == '__main__':
  83. glfw.init()
  84. main()
  85. glfw.terminate()

希望这能帮助你解决冲突。

英文:

I have an exercise to draw a simple cube that teacher asks me to fill in where: <br> "YOUR CODE HERE ...". <br>
I have done it but when coming to see the result, it rendered something weird (Figure 1 ). I have run that code on my friend's laptop and it gave a really good cube (Figure 2). <br>
There are 3 files in used:

  • cube.py:
  1. from libs.buffer import *
  2. import glfw
  3. class Cube(object):
  4. def __init__(self, vert_shader, frag_shader):
  5. self.vertices = np.array([
  6. # YOUR CODE HERE to specify vertices&#39; coordinates
  7. [-0.5, -0.5, -0.5], # A 0
  8. [0.5, -0.5, -0.5], # B 1
  9. [0.5, -0.5, 0.5], # C 2
  10. [-0.5, -0.5, 0.5], # D 3
  11. [-0.5, 0.5, -0.5], # E 4
  12. [0.5, 0.5, -0.5], # F 5
  13. [0.5, 0.5, 0.5], # G 6
  14. [-0.5, 0.5, 0.5] # H 7
  15. ], dtype=np.float32)
  16. self.indices = np.array([
  17. # YOUR CODE HERE to specify indices
  18. 4, 7, 5, 6, # Top
  19. 6, 0,
  20. 0, 4, 1, 5, 2, 6, 3, 7, 0, 4, # Sides
  21. 5, 1,
  22. 0, 3, 1, 2 # Bottom
  23. ])
  24. # YOUR CODE HERE to compute vertices&#39; normals using the coordinates
  25. normals = np.random.normal(0, 1, (self.vertices.shape[0], 3)).astype(np.float32)
  26. normals[:, 2] = np.abs(normals[:, 2])
  27. self.normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)
  28. # colors: RGB format
  29. self.colors = np.array([
  30. # YOUR CODE HERE to specify vertices&#39; color
  31. [0.0, 0.0, 0.0], # black
  32. [1.0, 0.0, 0.0], # red
  33. [1.0, 1.0, 0.0], # yellow
  34. [0.0, 1.0, 0.0], # green
  35. [0.0, 0.0, 1.0], # blue
  36. [1.0, 0.0, 1.0], # magenta
  37. [1.0, 1.0, 1.0], # white
  38. [0.0, 1.0, 1.0] # cyan
  39. ], dtype=np.float32)
  40. self.vao = VAO()
  41. self.shader = Shader(vert_shader, frag_shader)
  42. self.uma = UManager(self.shader)
  43. #
  44. &quot;&quot;&quot;
  45. Create object -&gt; call setup -&gt; call draw
  46. &quot;&quot;&quot;
  47. def setup(self):
  48. # setup VAO for drawing cylinder&#39;s side
  49. self.vao.add_vbo(0, self.vertices, ncomponents=3, stride=0, offset=None)
  50. self.vao.add_vbo(1, self.colors, ncomponents=3, stride=0, offset=None)
  51. # setup EBO for drawing cylinder&#39;s side, bottom and top
  52. self.vao.add_ebo(self.indices)
  53. return self
  54. def draw(self, projection, view, model):
  55. GL.glUseProgram(self.shader.render_idx)
  56. modelview = view
  57. self.uma.upload_uniform_matrix4fv(projection, &#39;projection&#39;, True)
  58. self.uma.upload_uniform_matrix4fv(modelview, &#39;modelview&#39;, True)
  59. self.vao.activate()
  60. GL.glDrawElements(GL.GL_TRIANGLE_STRIP, self.indices.shape[0], GL.GL_UNSIGNED_INT, None)
  61. def key_handler(self, key):
  62. if key == glfw.KEY_1:
  63. self.selected_texture = 1
  64. if key == glfw.KEY_2:
  65. self.selected_texture = 2
  • libs/buffer.py:
  1. import OpenGL.GL as GL
  2. import cv2
  3. class VAO(object):
  4. def __init__(self):
  5. self.vao = GL.glGenVertexArrays(1)
  6. GL.glBindVertexArray(self.vao)
  7. GL.glBindVertexArray(0)
  8. self.vbo = {}
  9. self.ebo = None
  10. def add_vbo(self, location, data, ncomponents=3, dtype=GL.GL_FLOAT, normalized=False, stride=0, offset=None):
  11. self.activate()
  12. buffer_idx = GL.glGenBuffers(1)
  13. GL.glBindBuffer(GL.GL_ARRAY_BUFFER, buffer_idx)
  14. GL.glBufferData(GL.GL_ARRAY_BUFFER, data, GL.GL_STATIC_DRAW)
  15. # location = GL.glGetAttribLocation(self.shader.render_idx, name)
  16. GL.glVertexAttribPointer(location, ncomponents, dtype, normalized, stride, offset)
  17. GL.glEnableVertexAttribArray(location)
  18. self.vbo[location] = buffer_idx
  19. self.deactivate()
  20. def add_ebo(self, indices):
  21. self.activate()
  22. self.ebo = GL.glGenBuffers(1)
  23. GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.ebo)
  24. GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indices, GL.GL_STATIC_DRAW)
  25. self.deactivate()
  26. def __del__(self):
  27. GL.glDeleteVertexArrays(1, [self.vao])
  28. GL.glDeleteBuffers(1, list(self.vbo.values()))
  29. if self.ebo is not None:
  30. GL.glDeleteBuffers(1, [self.ebo])
  31. def activate(self):
  32. GL.glBindVertexArray(self.vao) # activated
  33. def deactivate(self):
  34. GL.glBindVertexArray(0) # activated
  35. class UManager(object):
  36. def __init__(self, shader):
  37. self.shader = shader
  38. self.textures = {}
  39. @staticmethod
  40. def load_texture(filename):
  41. texture = cv2.cvtColor(cv2.imread(filename, 1), cv2.COLOR_BGR2RGB)
  42. return texture
  43. def _get_texture_loc(self):
  44. if not bool(self.textures):
  45. return 0
  46. else:
  47. locs = list(self.textures.keys())
  48. locs.sort(reverse=True)
  49. ret_id = locs[0] + 1
  50. return ret_id
  51. &quot;&quot;&quot;
  52. * first call to setup_texture: activate GL.GL_TEXTURE0
  53. &gt; use GL.glUniform1i to associate the activated texture to the texture in shading program (see fragment shader)
  54. * second call to setup_texture: activate GL.GL_TEXTURE1
  55. &gt; use GL.glUniform1i to associate the activated texture to the texture in shading program (see fragment shader)
  56. * second call to setup_texture: activate GL.GL_TEXTURE2
  57. &gt; use GL.glUniform1i to associate the activated texture to the texture in shading program (see fragment shader)
  58. and so on
  59. &quot;&quot;&quot;
  60. def setup_texture(self, sampler_name, image_file):
  61. rgb_image = UManager.load_texture(image_file)
  62. GL.glUseProgram(self.shader.render_idx) # must call before calling to GL.glUniform1i
  63. texture_idx = GL.glGenTextures(1)
  64. binding_loc = self._get_texture_loc()
  65. self.textures[binding_loc] = {}
  66. self.textures[binding_loc][&quot;id&quot;] = texture_idx
  67. self.textures[binding_loc][&quot;name&quot;] = sampler_name
  68. GL.glActiveTexture(GL.GL_TEXTURE0 + binding_loc) # activate texture GL.GL_TEXTURE0, GL.GL_TEXTURE1, ...
  69. GL.glBindTexture(GL.GL_TEXTURE_2D, texture_idx)
  70. GL.glUniform1i(GL.glGetUniformLocation(self.shader.render_idx, sampler_name), binding_loc)
  71. GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB,
  72. rgb_image.shape[1], rgb_image.shape[0], 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, rgb_image)
  73. GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
  74. GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
  75. def upload_uniform_matrix4fv(self, matrix, name, transpose=True):
  76. GL.glUseProgram(self.shader.render_idx)
  77. location = GL.glGetUniformLocation(self.shader.render_idx, name)
  78. GL.glUniformMatrix4fv(location, 1, transpose, matrix)
  79. def upload_uniform_matrix3fv(self, matrix, name, transpose=False):
  80. GL.glUseProgram(self.shader.render_idx)
  81. location = GL.glGetUniformLocation(self.shader.render_idx, name)
  82. GL.glUniformMatrix3fv(location, 1, transpose, matrix)
  83. def upload_uniform_vector4fv(self, vector, name):
  84. GL.glUseProgram(self.shader.render_idx)
  85. location = GL.glGetUniformLocation(self.shader.render_idx, name)
  86. GL.glUniform4fv(location, 1, vector)
  87. def upload_uniform_vector3fv(self, vector, name):
  88. GL.glUseProgram(self.shader.render_idx)
  89. location = GL.glGetUniformLocation(self.shader.render_idx, name)
  90. GL.glUniform3fv(location, 1, vector)
  91. def upload_uniform_scalar1f(self, scalar, name):
  92. GL.glUseProgram(self.shader.render_idx)
  93. location = GL.glGetUniformLocation(self.shader.render_idx, name)
  94. GL.glUniform1f(location, scalar)
  95. def upload_uniform_scalar1i(self, scalar, name):
  96. GL.glUseProgram(self.shader.render_idx)
  97. location = GL.glGetUniformLocation(self.shader.render_idx, name)
  98. GL.glUniform1i(location, scalar)
  • viewer.py (file to run):
  1. import OpenGL.GL as GL # standard Python OpenGL wrapper
  2. import glfw # lean windows system wrapper for OpenGL
  3. import numpy as np # all matrix manipulations &amp; OpenGL args
  4. from itertools import cycle # cyclic iterator to easily toggle polygon rendering modes
  5. from libs.transform import Trackball
  6. from cube import *
  7. # ------------ Viewer class &amp; windows management ------------------------------
  8. class Viewer:
  9. &quot;&quot;&quot; GLFW viewer windows, with classic initialization &amp; graphics loop &quot;&quot;&quot;
  10. def __init__(self, width=800, height=800):
  11. self.fill_modes = cycle([GL.GL_LINE, GL.GL_POINT, GL.GL_FILL])
  12. # version hints: create GL windows with &gt;= OpenGL 3.3 and core profile
  13. glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
  14. glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
  15. glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE)
  16. glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
  17. glfw.window_hint(glfw.RESIZABLE, False)
  18. glfw.window_hint(glfw.DEPTH_BITS, 16)
  19. glfw.window_hint(glfw.DOUBLEBUFFER, True)
  20. self.win = glfw.create_window(width, height, &#39;Viewer&#39;, None, None)
  21. # make win&#39;s OpenGL context current; no OpenGL calls can happen before
  22. glfw.make_context_current(self.win)
  23. # initialize trackball
  24. self.trackball = Trackball()
  25. self.mouse = (0, 0)
  26. # register event handlers
  27. glfw.set_key_callback(self.win, self.on_key)
  28. glfw.set_cursor_pos_callback(self.win, self.on_mouse_move)
  29. glfw.set_scroll_callback(self.win, self.on_scroll)
  30. # useful message to check OpenGL renderer characteristics
  31. print(&#39;OpenGL&#39;, GL.glGetString(GL.GL_VERSION).decode() + &#39;, GLSL&#39;,
  32. GL.glGetString(GL.GL_SHADING_LANGUAGE_VERSION).decode() +
  33. &#39;, Renderer&#39;, GL.glGetString(GL.GL_RENDERER).decode())
  34. # initialize GL by setting viewport and default render characteristics
  35. GL.glClearColor(0.5, 0.5, 0.5, 0.1)
  36. #GL.glEnable(GL.GL_CULL_FACE) # enable backface culling (Exercise 1)
  37. #GL.glFrontFace(GL.GL_CCW) # GL_CCW: default
  38. GL.glEnable(GL.GL_DEPTH_TEST) # enable depth test (Exercise 1)
  39. GL.glDepthFunc(GL.GL_LESS) # GL_LESS: default
  40. # initially empty list of object to draw
  41. self.drawables = []
  42. def run(self):
  43. &quot;&quot;&quot; Main render loop for this OpenGL windows &quot;&quot;&quot;
  44. while not glfw.window_should_close(self.win):
  45. # clear draw buffer
  46. GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
  47. win_size = glfw.get_window_size(self.win)
  48. view = self.trackball.view_matrix()
  49. projection = self.trackball.projection_matrix(win_size)
  50. # draw our scene objects
  51. for drawable in self.drawables:
  52. drawable.draw(projection, view, None)
  53. # flush render commands, and swap draw buffers
  54. glfw.swap_buffers(self.win)
  55. # Poll for and process events
  56. glfw.poll_events()
  57. def add(self, *drawables):
  58. &quot;&quot;&quot; add objects to draw in this windows &quot;&quot;&quot;
  59. self.drawables.extend(drawables)
  60. def on_key(self, _win, key, _scancode, action, _mods):
  61. &quot;&quot;&quot; &#39;Q&#39; or &#39;Escape&#39; quits &quot;&quot;&quot;
  62. if action == glfw.PRESS or action == glfw.REPEAT:
  63. if key == glfw.KEY_ESCAPE or key == glfw.KEY_Q:
  64. glfw.set_window_should_close(self.win, True)
  65. if key == glfw.KEY_W:
  66. GL.glPolygonMode(GL.GL_FRONT_AND_BACK, next(self.fill_modes))
  67. for drawable in self.drawables:
  68. if hasattr(drawable, &#39;key_handler&#39;):
  69. drawable.key_handler(key)
  70. def on_mouse_move(self, win, xpos, ypos):
  71. &quot;&quot;&quot; Rotate on left-click &amp; drag, pan on right-click &amp; drag &quot;&quot;&quot;
  72. old = self.mouse
  73. self.mouse = (xpos, glfw.get_window_size(win)[1] - ypos)
  74. if glfw.get_mouse_button(win, glfw.MOUSE_BUTTON_LEFT):
  75. self.trackball.drag(old, self.mouse, glfw.get_window_size(win))
  76. if glfw.get_mouse_button(win, glfw.MOUSE_BUTTON_RIGHT):
  77. self.trackball.pan(old, self.mouse)
  78. def on_scroll(self, win, _deltax, deltay):
  79. &quot;&quot;&quot; Scroll controls the camera distance to trackball center &quot;&quot;&quot;
  80. self.trackball.zoom(deltay, glfw.get_window_size(win)[1])
  81. # -------------- main program and scene setup --------------------------------
  82. def main():
  83. &quot;&quot;&quot; create windows, add shaders &amp; scene objects, then run rendering loop &quot;&quot;&quot;
  84. viewer = Viewer()
  85. # place instances of our basic objects
  86. model = Cube(&quot;./gouraud.vert&quot;, &quot;./gouraud.frag&quot;).setup()
  87. viewer.add(model)
  88. # start rendering loop
  89. viewer.run()
  90. if __name__ == &#39;__main__&#39;:
  91. glfw.init() # initialize windows system glfw
  92. main() # main function keeps variables locally scoped
  93. glfw.terminate() # destroy all glfw windows and GL contexts

Hope someone can help me solve this conflict. <br>
P/s: I use MacOS whereas my friend uses Window.

答案1

得分: 0

问题在于<b>cube.py</b>中索引数组的数据类型。为了在各种操作系统上顺利运行,我们需要指定一个特定的数据类型。例如:self.indices = np.array([...], dtype=np.uint32)

英文:

The problem is the data type of index array in <b>cube.py</b>. We need to specify a specific type in order to run smoothly through various OSs. <br>
For example: self.indices = np.array([...], dtype=np.uint32).

huangapple
  • 本文由 发表于 2023年2月23日 20:41:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定