def window_pixel_space(self): """with文、又はデコレータとして使用 :rtype: GCM """ win_width, win_height = self.window_size modelview_mat = Buffer('double', (4, 4), bgl.GL_MODELVIEW_MATRIX) projection_mat = Buffer('double', (4, 4), bgl.GL_PROJECTION_MATRIX) matrix_mode = Buffer('int', 1, bgl.GL_MATRIX_MODE) viewport = Buffer('int', 4, bgl.GL_VIEWPORT) bgl.glViewport(0, 0, win_width, win_height) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() ofs = -0.01 bgl.glOrtho(ofs, win_width + ofs, ofs, win_height + ofs, -100, 100) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glLoadIdentity() bgl.glMatrixMode(matrix_mode[0]) try: yield finally: bgl.glViewport(*viewport) self._load_matrix(modelview_mat, projection_mat)
def window_space(win): modelview_mat = bgl.Buffer(bgl.GL_DOUBLE, 16) projection_mat = bgl.Buffer(bgl.GL_DOUBLE, 16) bgl.glGetDoublev(bgl.GL_MODELVIEW_MATRIX, modelview_mat) bgl.glGetDoublev(bgl.GL_PROJECTION_MATRIX, projection_mat) matrix_mode = bgl.Buffer(bgl.GL_INT, 1) bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, matrix_mode) viewport = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport) bgl.glViewport(0, 0, win.width, win.height) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() ofs = -0.01 bgl.glOrtho(ofs, win.width + ofs, ofs, win.height + ofs, -100, 100) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glLoadIdentity() bgl.glMatrixMode(matrix_mode[0]) yield bgl.glViewport(*viewport) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadMatrixd(projection_mat) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glLoadMatrixd(modelview_mat) bgl.glMatrixMode(matrix_mode[0])
def bind(self): if self is not _SnapOffscreen.bound: if _SnapOffscreen.bound is None: bgl.glGetIntegerv(bgl.GL_FRAMEBUFFER_BINDING, self.cur_fbo) bgl.glGetIntegerv(bgl.GL_VIEWPORT, self.cur_viewport) bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.fbo[0]) bgl.glViewport(0, 0, self.width, self.height) _SnapOffscreen.bound = self
def draw(self, context): log("Draw") if not self.is_synced: return stage = self.stage if not stage: return view_settings = ViewSettings(context) if view_settings.width * view_settings.height == 0: return gf_camera = view_settings.export_camera() self.renderer.SetCameraState( gf_camera.frustum.ComputeViewMatrix(), gf_camera.frustum.ComputeProjectionMatrix()) if self.is_gl_delegate: self.renderer.SetRenderViewport( (*view_settings.border[0], *view_settings.border[1])) else: self.renderer.SetRenderViewport((0, 0, *view_settings.border[1])) self.renderer.SetRendererAov('color') self.render_params.renderResolution = (view_settings.width, view_settings.height) if self.is_gl_delegate: bgl.glEnable(bgl.GL_DEPTH_TEST) else: bgl.glDisable(bgl.GL_DEPTH_TEST) bgl.glViewport(*view_settings.border[0], *view_settings.border[1]) bgl.glClearColor(0.0, 0.0, 0.0, 0.0) bgl.glClearDepth(1.0) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) # Bind shader that converts from scene linear to display space, bgl.glEnable(bgl.GL_BLEND) bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ONE_MINUS_SRC_ALPHA) self.render_engine.bind_display_space_shader(context.scene) try: self.renderer.Render(stage.GetPseudoRoot(), self.render_params) except Exception as e: log.error(e) self.render_engine.unbind_display_space_shader() bgl.glDisable(bgl.GL_BLEND) if not self.renderer.IsConverged(): self.notify_status("Rendering...", "") else: self.notify_status("Rendering Done", "", False)
def _render_gl(self, scene): CLEAR_COLOR = (0.0, 0.0, 0.0, 0.0) CLEAR_DEPTH = 1.0 # creating draw_target draw_target = Glf.DrawTarget(self.width, self.height) draw_target.Bind() draw_target.AddAttachment("color", bgl.GL_RGBA, bgl.GL_FLOAT, bgl.GL_RGBA) draw_target.AddAttachment("depth", bgl.GL_DEPTH_COMPONENT, bgl.GL_FLOAT, bgl.GL_DEPTH_COMPONENT32F) # creating renderer renderer = UsdImagingGL.Engine() log("Hydra render:", scene.hdusd.final.delegate) renderer.SetRendererPlugin(scene.hdusd.final.delegate) # setting camera self._set_scene_camera(renderer, scene) renderer.SetRenderViewport((0, 0, self.width, self.height)) renderer.SetRendererAov('color') bgl.glEnable(bgl.GL_DEPTH_TEST) bgl.glViewport(0, 0, self.width, self.height) bgl.glClearColor(*CLEAR_COLOR) bgl.glClearDepth(CLEAR_DEPTH) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) root = self.stage.GetPseudoRoot() params = UsdImagingGL.RenderParams() params.renderResolution = (self.width, self.height) params.frame = Usd.TimeCode.Default() params.clearColor = CLEAR_COLOR try: renderer.Render(root, params) except Exception as e: log.error(e) self.update_render_result({ 'Combined': gl.get_framebuffer_data(self.width, self.height) }) draw_target.Unbind() # it's important to clear data explicitly draw_target = None renderer = None
def render(self, dg): scene = dg.scene scale = scene.render.resolution_percentage / 100.0 width = int(scene.render.resolution_x * scale) height = int(scene.render.resolution_y * scale) zu.blen_gl_enable() try: # Create drawing target self.genfb(width, height) # Prep Zu scene self.scene = zu.scene_new() view_mat = self.camera_model_matrix(scene.camera) view_mat.invert() win_mat = scene.camera.calc_matrix_camera(dg, x=width, y=height) cam = win_mat @ view_mat zu.scene_cam(self.scene, mat(cam)) self.load_dg(dg) # Render bgl.glViewport(0, 0, width, height) zu.scene_draw(self.scene, self.fb) # Retrieve texture data pixels = bgl.Buffer(bgl.GL_FLOAT, width * height * 4) bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, pixels) # Copy pixel data to output result = self.begin_result(0, 0, width, height) layer = result.layers[0].passes["Combined"] pixels = pixels.to_list() layer.rect = list( zip(*[pixels[i::4] for i in range(4)])) # FIXME: holy f**k this is slow self.end_result(result) finally: del self.objects self.objects = None del self.scene self.scene = None bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, 0) self.delfb() zu.blen_gl_disable()
def draw_callback_px(self, context): #get RegionView3D r3d = 0 for space in context.area.spaces: if space.type == 'VIEW_3D': r3d = space.region_3d if r3d == 0: print("region_3D NOT FOUND") pass screenWidth = context.area.width screenHeight = context.area.height bgl.glEnable(bgl.GL_BLEND) bgl.glEnable(bgl.GL_DEPTH_TEST) # get old viewport properties oldViewport = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, oldViewport) #oldViewDistance = r3d.view_distance oldMatrix = bgl.Buffer(bgl.GL_DOUBLE, [4,4]) bgl.glGetDoublev(bgl.GL_PROJECTION_MATRIX, oldMatrix) viewportWidth = int(oldViewport[2]/4) viewportHeight = int(oldViewport[3]/4) #bgl.glViewport(screenWidth - viewportWidth, screenHeight - viewportHeight, viewportWidth, viewportHeight) bgl.glViewport(screenWidth - viewportWidth, (screenHeight - viewportHeight) + int((viewportHeight-viewportWidth)/2), viewportWidth, viewportHeight) draw_cube(context, r3d) # restore opengl defaults #r3d.view_distance = oldViewDistance bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) bgl.glDisable(bgl.GL_DEPTH_TEST) bgl.glColor4f(0.0, 0.0, 0.0, 1.0) bgl.glViewport(oldViewport[0],oldViewport[1],oldViewport[2],oldViewport[3]) bgl.glPushMatrix() bgl.glLoadMatrixf(oldMatrix) bgl.glPopMatrix()
def view_draw(self, context): verco = [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)] texco = [(1.0, 1.0), (0.0, 1.0), (0.0, 0.0), (1.0, 0.0)] viewport = bgl.Buffer(bgl.GL_INT, [4]) bgl.glDisable(bgl.GL_DEPTH_TEST) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport) bgl.glViewport(viewport[0], viewport[1], viewport[2], viewport[3]) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.glUseProgram(self.program) wind = glGetUniformLocation(self.program, "u_wind") res = glGetUniformLocation(self.program, "u_resolution") size = glGetUniformLocation(self.program, "u_size") glUniform2fv(wind, 1, [150.0, 150.0]) glUniform1f(size, 250.0) glUniform1f(res, 512.0) bgl.glBegin(bgl.GL_QUADS) for i in range(4): bgl.glTexCoord3f(texco[i][0], texco[i][1], 1.0) bgl.glVertex2f(verco[i][0], verco[i][1]) bgl.glEnd() bgl.glUseProgram(0) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glPopMatrix() bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPopMatrix()
def view_draw(self, ctx, dg): if self.scene is None: return buf = bgl.Buffer(bgl.GL_INT, 1) bgl.glGetIntegerv(bgl.GL_DRAW_FRAMEBUFFER_BINDING, buf) if buf[0] == 0: return width, height = ctx.region.width, ctx.region.height if self.dim != (width, height): self.delfb() self.prepare_viewport(ctx, dg) # Render the scene bgl.glViewport(0, 0, width, height) cam = ctx.region_data.perspective_matrix zu.scene_cam(self.scene, mat(cam)) zu.scene_draw(self.scene, self.fb) # Copy the rendered scene to the viewport (through the color space adjustment shader) bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, buf[0]) bgl.glEnable(bgl.GL_BLEND) bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA) self.bind_display_space_shader(dg.scene) bgl.glBindVertexArray(self.vao) bgl.glEnableVertexAttribArray(self.quad_in) bgl.glEnableVertexAttribArray(self.uv_in) bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.tex) bgl.glDrawArrays(bgl.GL_TRIANGLE_FAN, 0, 4) bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0) bgl.glDisableVertexAttribArray(self.quad_in) bgl.glDisableVertexAttribArray(self.uv_in) bgl.glBindVertexArray(0) self.unbind_display_space_shader() bgl.glDisable(bgl.GL_BLEND)
def render_main(self, context, animation=False): # noinspection PyBroadException,PyBroadException try: # Get visible layers layers = [] scene = context.scene for x in range(0, 20): if scene.layers[x] is True: layers.extend([x]) # Get object list objlist = context.scene.objects # -------------------- # Get resolution # -------------------- scene = bpy.context.scene render_scale = scene.render.resolution_percentage / 100 width = int(scene.render.resolution_x * render_scale) height = int(scene.render.resolution_y * render_scale) # --------------------------------------- # Get output path # --------------------------------------- ren_path = bpy.context.scene.render.filepath if len(ren_path) > 0: if ren_path.endswith(os.path.sep): initpath = os.path.realpath(ren_path) + os.path.sep else: (initpath, filename) = os.path.split(ren_path) outpath = os.path.join(initpath, "measureit_tmp_render.png") else: self.report({'ERROR'}, "MeasureIt: Unable to save temporary render image. Define a valid render path") return False # Get Render Image img = get_render_image(outpath) if img is None: self.report({'ERROR'}, "MeasureIt: Unable to save temporary render image. Define a valid render path") return False # ----------------------------- # Calculate rows and columns # ----------------------------- tile_x = 240 tile_y = 216 row_num = ceil(height / tile_y) col_num = ceil(width / tile_x) print("MeasureIt: Image divided in " + str(row_num) + "x" + str(col_num) + " tiles") # pixels out of visible area cut4 = (col_num * tile_x * 4) - width * 4 # pixels aout of drawing area totpixel4 = width * height * 4 # total pixels RGBA viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) # Load image on memory img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST) tex = img.bindcode # -------------------------------------------- # Create output image (to apply texture) # -------------------------------------------- if "measureit_output" in bpy.data.images: out_img = bpy.data.images["measureit_output"] if out_img is not None: out_img.user_clear() bpy.data.images.remove(out_img) out = bpy.data.images.new("measureit_output", width, height) tmp_pixels = [1] * totpixel4 # -------------------------------- # Loop for all tiles # -------------------------------- for row in range(0, row_num): for col in range(0, col_num): buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4) bgl.glDisable(bgl.GL_SCISSOR_TEST) # if remove this line, get blender screenshot not image bgl.glViewport(0, 0, tile_x, tile_y) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() # defines ortographic view for single tile x1 = tile_x * col y1 = tile_y * row bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y) # Clear bgl.glClearColor(0.0, 0.0, 0.0, 0.0) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) bgl.glEnable(bgl.GL_TEXTURE_2D) bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex) # defines drawing area bgl.glBegin(bgl.GL_QUADS) bgl.glColor3f(1.0, 1.0, 1.0) bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(0.0, 0.0) bgl.glTexCoord2f(1.0, 0.0) bgl.glVertex2f(width, 0.0) bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(width, height) bgl.glTexCoord2f(0.0, 1.0) bgl.glVertex2f(0.0, height) bgl.glEnd() # ----------------------------- # Loop to draw all lines # ----------------------------- for myobj in objlist: if myobj.hide is False: if 'MeasureGenerator' in myobj: # verify visible layer for x in range(0, 20): if myobj.layers[x] is True: if x in layers: op = myobj.MeasureGenerator[0] draw_segments(context, myobj, op, None, None) break if scene.measureit_rf is True: bgl.glColor3f(1.0, 1.0, 1.0) rfcolor = scene.measureit_rf_color rfborder = scene.measureit_rf_border rfline = scene.measureit_rf_line bgl.glLineWidth(rfline) bgl.glColor4f(rfcolor[0], rfcolor[1], rfcolor[2], rfcolor[3]) x1 = rfborder x2 = width - rfborder y1 = int(math.ceil(rfborder / (width / height))) y2 = height - y1 draw_rectangle((x1, y1), (x2, y2)) # -------------------------------- # copy pixels to temporary area # -------------------------------- bgl.glFinish() bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) # read image data for y in range(0, tile_y): # final image pixels position p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4) p2 = p1 + (tile_x * 4) # buffer pixels position b1 = y * width * 4 b2 = b1 + (tile_x * 4) if p1 < totpixel4: # avoid pixel row out of area if col == col_num - 1: # avoid pixel columns out of area p2 -= cut4 b2 -= cut4 tmp_pixels[p1:p2] = buffer[b1:b2] # ----------------------- # Copy temporary to final # ----------------------- out.pixels = tmp_pixels[:] # Assign image data img.gl_free() # free opengl image memory # delete image img.user_clear() bpy.data.images.remove(img) # remove temp file os.remove(outpath) # reset bgl.glEnable(bgl.GL_SCISSOR_TEST) # ----------------------- # restore opengl defaults # ----------------------- bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) bgl.glColor4f(0.0, 0.0, 0.0, 1.0) # Saves image if out is not None and (scene.measureit_render is True or animation is True): ren_path = bpy.context.scene.render.filepath filename = "mit_frame" if len(ren_path) > 0: if ren_path.endswith(os.path.sep): initpath = os.path.realpath(ren_path) + os.path.sep else: (initpath, filename) = os.path.split(ren_path) ftxt = "%04d" % scene.frame_current outpath = os.path.join(initpath, filename + ftxt + ".png") save_image(self, outpath, out) return True except: print("Unexpected error:" + str(sys.exc_info())) self.report({'ERROR'}, "MeasureIt: Unable to create render image") return False
def generate_icon(name, verts=None, faces=None): pcoll = preview_collections["shape_types"] if name in pcoll: thumb = pcoll.get(name) else: thumb = pcoll.new(name) thumb.image_size = (200, 200) if verts is not None: import bgl polygon_color = bpy.context.user_preferences.themes[0].view_3d.edge_facesel edge_color = bpy.context.user_preferences.themes[0].view_3d.edge_select vertex_color = bpy.context.user_preferences.themes[0].view_3d.vertex_select clear_color = bpy.context.user_preferences.themes[0].user_interface.wcol_menu.inner viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) buffer = bgl.Buffer(bgl.GL_FLOAT, 200 * 200 * 4) bgl.glDisable(bgl.GL_SCISSOR_TEST) bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA) bgl.glEnable(bgl.GL_LINE_SMOOTH) bgl.glEnable(bgl.GL_POINT_SMOOTH) bgl.glViewport(0, 0, 200, 200) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.gluOrtho2D(0, 0, 0, 0) bgl.glLineWidth(4.0) bgl.glPointSize(10.0) bgl.glClearColor(*clear_color) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) if faces is None: bgl.glBegin(bgl.GL_POLYGON) bgl.glColor3f(*polygon_color) for vert in verts: bgl.glVertex2f(*vert) bgl.glEnd() else: bgl.glBegin(bgl.GL_TRIANGLES) bgl.glColor3f(*polygon_color) for face in faces: bgl.glVertex2f(*verts[face[0]]) bgl.glVertex2f(*verts[face[1]]) bgl.glVertex2f(*verts[face[2]]) bgl.glEnd() bgl.glBegin(bgl.GL_LINE_LOOP) bgl.glColor3f(*edge_color) for vert in verts: bgl.glVertex2f(*vert) bgl.glEnd() bgl.glBegin(bgl.GL_POINTS) bgl.glColor3f(*vertex_color) for vert in verts: bgl.glVertex2f(*vert) bgl.glEnd() bgl.glReadPixels(0, 0, 200, 200, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) bgl.glEnable(bgl.GL_SCISSOR_TEST) bgl.glLineWidth(1.0) bgl.glPointSize(1.0) buffer = buffer[:] for idx in range(0, 200 * 200 * 4, 4): if ( buffer[idx] == clear_color[0] and buffer[idx + 1] == clear_color[1] and buffer[idx + 2] == clear_color[2] ): buffer[idx + 3] = 0.0 thumb.image_pixels_float = buffer
def render(self, draw_data): io = self.io shader = self._bl_shader display_width, display_height = io.display_size fb_width = int(display_width * io.display_fb_scale[0]) fb_height = int(display_height * io.display_fb_scale[1]) if fb_width == 0 or fb_height == 0: return draw_data.scale_clip_rects(*io.display_fb_scale) # backup GL state ( last_program, last_texture, last_active_texture, last_array_buffer, last_element_array_buffer, last_vertex_array, last_blend_src, last_blend_dst, last_blend_equation_rgb, last_blend_equation_alpha, last_viewport, last_scissor_box, ) = self._backup_integers( gl.GL_CURRENT_PROGRAM, 1, gl.GL_TEXTURE_BINDING_2D, 1, gl.GL_ACTIVE_TEXTURE, 1, gl.GL_ARRAY_BUFFER_BINDING, 1, gl.GL_ELEMENT_ARRAY_BUFFER_BINDING, 1, gl.GL_VERTEX_ARRAY_BINDING, 1, gl.GL_BLEND_SRC, 1, gl.GL_BLEND_DST, 1, gl.GL_BLEND_EQUATION_RGB, 1, gl.GL_BLEND_EQUATION_ALPHA, 1, gl.GL_VIEWPORT, 4, gl.GL_SCISSOR_BOX, 4, ) last_enable_blend = gl.glIsEnabled(gl.GL_BLEND) last_enable_cull_face = gl.glIsEnabled(gl.GL_CULL_FACE) last_enable_depth_test = gl.glIsEnabled(gl.GL_DEPTH_TEST) last_enable_scissor_test = gl.glIsEnabled(gl.GL_SCISSOR_TEST) gl.glEnable(gl.GL_BLEND) gl.glBlendEquation(gl.GL_FUNC_ADD) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glDisable(gl.GL_CULL_FACE) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_SCISSOR_TEST) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glViewport(0, 0, int(fb_width), int(fb_height)) ortho_projection = (2.0 / display_width, 0.0, 0.0, 0.0, 0.0, 2.0 / -display_height, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -1.0, 1.0, 0.0, 1.0) shader.bind() shader.uniform_float("ProjMtx", ortho_projection) shader.uniform_int("Texture", 0) for commands in draw_data.commands_lists: size = commands.idx_buffer_size * imgui.INDEX_SIZE // 4 address = commands.idx_buffer_data ptr = C.cast(address, C.POINTER(C.c_int)) idx_buffer_np = np.ctypeslib.as_array(ptr, shape=(size, )) size = commands.vtx_buffer_size * imgui.VERTEX_SIZE // 4 address = commands.vtx_buffer_data ptr = C.cast(address, C.POINTER(C.c_float)) vtx_buffer_np = np.ctypeslib.as_array(ptr, shape=(size, )) vtx_buffer_shaped = vtx_buffer_np.reshape(-1, imgui.VERTEX_SIZE // 4) idx_buffer_offset = 0 for command in commands.commands: x, y, z, w = command.clip_rect gl.glScissor(int(x), int(fb_height - w), int(z - x), int(w - y)) vertices = vtx_buffer_shaped[:, :2] uvs = vtx_buffer_shaped[:, 2:4] colors = vtx_buffer_shaped.view(np.uint8)[:, 4 * 4:] colors = colors.astype('f') / 255.0 indices = idx_buffer_np[idx_buffer_offset:idx_buffer_offset + command.elem_count] gl.glBindTexture(gl.GL_TEXTURE_2D, command.texture_id) batch = batch_for_shader(shader, 'TRIS', { "Position": vertices, "UV": uvs, "Color": colors, }, indices=indices) batch.draw(shader) idx_buffer_offset += command.elem_count # restore modified GL state gl.glUseProgram(last_program) gl.glActiveTexture(last_active_texture) gl.glBindTexture(gl.GL_TEXTURE_2D, last_texture) gl.glBindVertexArray(last_vertex_array) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, last_array_buffer) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer) gl.glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha) gl.glBlendFunc(last_blend_src, last_blend_dst) if last_enable_blend: gl.glEnable(gl.GL_BLEND) else: gl.glDisable(gl.GL_BLEND) if last_enable_cull_face: gl.glEnable(gl.GL_CULL_FACE) else: gl.glDisable(gl.GL_CULL_FACE) if last_enable_depth_test: gl.glEnable(gl.GL_DEPTH_TEST) else: gl.glDisable(gl.GL_DEPTH_TEST) if last_enable_scissor_test: gl.glEnable(gl.GL_SCISSOR_TEST) else: gl.glDisable(gl.GL_SCISSOR_TEST) gl.glViewport(last_viewport[0], last_viewport[1], last_viewport[2], last_viewport[3]) gl.glScissor(last_scissor_box[0], last_scissor_box[1], last_scissor_box[2], last_scissor_box[3])
def unbind(self): if self is _SnapOffscreen.bound: bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.cur_fbo[0]) bgl.glViewport(*self.cur_viewport) _SnapOffscreen.bound = None
render_scale = scene.render.resolution_percentage / 100 WIDTH = int(scene.render.resolution_x * render_scale) HEIGHT = int(scene.render.resolution_y * render_scale) # Load image on memory img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST) tex = img.bindcode # Create output image (to apply texture) out = bpy.data.images.new("output", WIDTH, HEIGHT) buffer = bgl.Buffer(bgl.GL_FLOAT, WIDTH * HEIGHT * 4) bgl.glDisable(bgl.GL_SCISSOR_TEST ) # if remove this line, get blender screenshot not image bgl.glViewport(0, 0, WIDTH, HEIGHT) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() bgl.gluOrtho2D(0, WIDTH, 0, HEIGHT) # bgl.glLineWidth(10) bgl.glBegin(bgl.GL_LINES) bgl.glColor4f(1.0, 0.0, 0.0, 1.0) #bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(0.0, 0.0) #bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(WIDTH, HEIGHT)
def draw_callback_viewUV(area, UV_TO_VIEW, id): # print(id, area.spaces[0].image, area.spaces[0].show_uvedit ) settings = bpy.context.scene.uv_highlight prefs = bpy.context.user_preferences.addons[__package__].preferences mode = bpy.context.scene.tool_settings.uv_select_mode # remove closed areas if len(area.regions) == 0 or area.type != "IMAGE_EDITOR": bpy.types.SpaceImageEditor.draw_handler_remove(IMAGE_EDITORS[area], 'WINDOW') IMAGE_EDITORS.pop(area, None) # print("removing Image_Editor from drawing: %s" % id) return # dont show this if the area is in Image mode :D if not main.isEditingUVs() or area.spaces[0].mode != "VIEW" or not area.spaces[0].show_uvedit: # print("skipping Image_Editor from drawing: %s" % id) return sync_mode = bpy.context.scene.tool_settings.use_uv_select_sync viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) for region in area.regions: if region.type == "WINDOW": width = region.width height = region.height region_x = region.x region_y = region.y bgl.glViewport(region_x, region_y, width, height) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPushMatrix() # bgl.glLoadIdentity() origin = UV_TO_VIEW(0, 0, False) axis = UV_TO_VIEW(1.0, 0, False)[0] - origin[0] M = (axis, 0, 0, 0, 0, axis, 0, 0, 0, 0, 1.0, 0, origin[0], origin[1], 0, 1.0) m = bgl.Buffer(bgl.GL_FLOAT, 16, M) bgl.glLoadMatrixf(m) if settings.show_hidden_faces and not sync_mode: bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ONE) draw_vertex_array("hidden_edges", bgl.GL_LINES, 2, prefs.uv_hidden_faces) if settings.show_udim_indices: draw_udim_tiles(M, prefs.udim_markers) # PRE HIGHLIGHT VERTS if settings.show_preselection and main.UV_MOUSE and UV_TO_VIEW and not sync_mode: if mode == 'VERTEX' and main.closest_vert and main.closest_vert[1]: bgl.glLoadIdentity() bgl.glPointSize(5.0) bgl.glBegin(bgl.GL_POINTS) bgl.glColor4f(*prefs.uv_preselection_color_verts_edges) if main.other_vert: bgl.glVertex2i(*UV_TO_VIEW(*main.other_vert)) bgl.glVertex2i(*UV_TO_VIEW(main.closest_vert[1][0], main.closest_vert[1][1], False)) bgl.glEnd() # print("MOUSE: %s, ClosestVert: %s - %s" % (UV_MOUSE, closestVert[1], view)) elif mode == 'EDGE': # draw dark first, then overpaint with brighter colour bgl.glLoadIdentity() bgl.glLineWidth(3.5) bgl.glEnable(bgl.GL_LINE_SMOOTH) bgl.glEnable(bgl.GL_BLEND) bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA) bgl.glBegin(bgl.GL_LINES) # edge if main.closest_edge and main.closest_edge[1][0] and main.closest_edge[1][1]: bgl.glColor3f(*COLOR_BLACK) bgl.glVertex2i(*(UV_TO_VIEW(*main.closest_edge[1][0], False))) bgl.glVertex2i(*(UV_TO_VIEW(*main.closest_edge[1][1], False))) # matching edge if main.other_edge and main.other_edge[1][0] and main.other_edge[1][1]: bgl.glColor3f(*COLOR_BLACK) bgl.glVertex2i(*(UV_TO_VIEW(*main.other_edge[1][0], False))) bgl.glVertex2i(*(UV_TO_VIEW(*main.other_edge[1][1], False))) bgl.glEnd() bgl.glLineWidth(2) bgl.glBegin(bgl.GL_LINES) # edge if main.closest_edge and main.closest_edge[1][0] and main.closest_edge[1][1]: bgl.glColor4f(*prefs.uv_preselection_color_verts_edges) bgl.glVertex2i(*(UV_TO_VIEW(*main.closest_edge[1][0], False))) bgl.glVertex2i(*(UV_TO_VIEW(*main.closest_edge[1][1], False))) # matching edge if main.other_edge and main.other_edge[1][0] and main.other_edge[1][1]: bgl.glColor4f(*prefs.uv_preselection_color_verts_edges) bgl.glVertex2i(*(UV_TO_VIEW(*main.other_edge[1][0], False))) bgl.glVertex2i(*(UV_TO_VIEW(*main.other_edge[1][1], False))) bgl.glEnd() else: bgl.glDisable((bgl.GL_CULL_FACE)) bgl.glEnable(bgl.GL_BLEND) bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ONE) draw_vertex_array("closest_face_uvs", bgl.GL_TRIANGLES, 2, prefs.uv_preselection_color_faces) bgl.glViewport(*tuple(viewport_info)) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPopMatrix() bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glPopMatrix() restore_opengl_defaults()
def execute(self, refholder): # pass tr = self.nodeTree.properties.TextureResolution print("begining execution " + str(tr)) # compute A' mask = np.array([[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]]) # Input data pixels A = self.inputs[0].getPixels() B = self.inputs[1].getPixels() # print(A) bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, self.rdData[self.name]["prev_program"]) bgl.glUseProgram(self.rdData[self.name]["program"]) #set any uniforms needed bgl.glUniform1f(self.rdData[self.name]["feed_loc"], self.inputs[2].value) bgl.glUniform1f(self.rdData[self.name]["kill_loc"], self.inputs[3].value) bgl.glUniform1f(self.rdData[self.name]["da_loc"], self.inputs[4].value) bgl.glUniform1f(self.rdData[self.name]["db_loc"], self.inputs[5].value) bgl.glUniform1f(self.rdData[self.name]["dt_loc"], self.inputs[6].value) bgl.glUniform1f(self.rdData[self.name]["step_loc"], 1 / tr) bgl.glDisable(bgl.GL_SCISSOR_TEST) bgl.glViewport(0, 0, tr, tr) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.gluOrtho2D(0, 1, 0, 1) bgl.glEnable(bgl.GL_TEXTURE_2D) bgl.glActiveTexture(bgl.GL_TEXTURE0) channels = [] if self.channels == '0': channels = [0] elif self.channels == '1': channels = [0, 1, 2] for j in channels: self.rdData[self.name]["npArray"][:, :, 0] = A[:, :, j] self.rdData[self.name]["npArray"][:, :, 1] = B[:, :, j] # Caution: Interfacing with Cython requires toList() self.rdData[self.name]["image"].pixels = self.rdData[ self.name]["npArray"].flatten() self.rdData[self.name]["image"].gl_load(0, bgl.GL_LINEAR, bgl.GL_LINEAR) bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.rdData[self.name]["image"].bindcode[0]) bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_S, bgl.GL_REPEAT) bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_T, bgl.GL_REPEAT) for i in range(self.inputs[7].value): bgl.glClearDepth(1.0) bgl.glClearColor(0.0, 0.0, 0.0, 0.0) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) bgl.glBegin(bgl.GL_TRIANGLES) bgl.glColor3f(1.0, 1.0, 1.0) bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(-1.0, -1.0) bgl.glTexCoord2f(1.0, 0.0) bgl.glVertex2f(1.0, -1.0) bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(1.0, 1.0) bgl.glColor3f(1.0, 1.0, 1.0) bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(-1.0, -1.0) bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(1.0, 1.0) bgl.glTexCoord2f(0.0, 1.0) bgl.glVertex2f(-1.0, 1.0) bgl.glEnd() bgl.glCopyTexImage2D( bgl.GL_TEXTURE_2D, #target 0, #level bgl.GL_RGBA, #internalformat 0, #x 0, #y tr, tr, 0 #border ) #glFlush glFinish or none here? bgl.glFinish() bgl.glReadPixels(0, 0, tr, tr, bgl.GL_RGBA, bgl.GL_FLOAT, self.rdData[self.name]["buffer"]) self.rdData[self.name]["image"].pixels = self.rdData[ self.name]["buffer"][:] #write the image channel npImage = np.asarray(self.rdData[self.name]["image"].pixels, dtype="float") self.rdData[self.name]["npArray"] = npImage.reshape( tr, tr, self.rdData[self.name]["image"].channels) self.outputs[0].setPackedImageFromChannels( self.rdData[self.name]["npArray"][:, :, 0], j, flatten=True) self.outputs[1].setPackedImageFromChannels( self.rdData[self.name]["npArray"][:, :, 1], j, flatten=True) self.outputs[2].setPackedImageFromPixels( self.rdData[self.name]["npArray"]) self.inputs[0].setPackedImageFromChannels( self.rdData[self.name]["npArray"][:, :, 0], j, flatten=True) self.inputs[1].setPackedImageFromChannels( self.rdData[self.name]["npArray"][:, :, 1], j, flatten=True) # ================================= Test bed # self.outputs[0].getTexture().image.copy() # self.outputs[1].getTexture().image.copy() # self.outputs[2].getTexture().image.copy() # nparr = np.asarray(self.outputs[0].getTexture().image.pixels, dtype="float") # nparr = nparr.reshape(tr, tr, 4) # print(nparr) self.rdData[self.name]["image"].gl_free() #restore the state so blender wont break bgl.glEnable(bgl.GL_SCISSOR_TEST) bgl.glUseProgram(self.rdData[self.name]["prev_program"][0]) bgl.glActiveTexture(bgl.GL_TEXTURE0)
def render_main(self, context, objlist, animation=False): # noinspection PyBroadException,PyBroadException # Save old info scene = context.scene render = scene.render settings = render.image_settings depth = settings.color_depth settings.color_depth = '8' # noinspection PyBroadException try: # Get visible layers layers = [] for x in range(0, 20): if scene.layers[x] is True: layers.extend([x]) # -------------------- # Get resolution # -------------------- render_scale = render.resolution_percentage / 100 width = int(render.resolution_x * render_scale) height = int(render.resolution_y * render_scale) # --------------------------------------- # Get output path # --------------------------------------- temp_path = path.realpath(bpy.app.tempdir) if len(temp_path) > 0: outpath = path.join(temp_path, "archipack_tmp_render.png") else: self.report({ 'ERROR' }, "Archipack: Unable to save temporary render image. Define a valid temp path" ) settings.color_depth = depth return False # Get Render Image img = self.get_render_image(outpath) if img is None: self.report({ 'ERROR' }, "Archipack: Unable to save temporary render image. Define a valid temp path" ) settings.color_depth = depth return False # ----------------------------- # Calculate rows and columns # ----------------------------- tile_x = 240 tile_y = 216 row_num = ceil(height / tile_y) col_num = ceil(width / tile_x) print("Archipack: Image divided in " + str(row_num) + "x" + str(col_num) + " tiles") # pixels out of visible area cut4 = (col_num * tile_x * 4) - width * 4 # pixels aout of drawing area totpixel4 = width * height * 4 # total pixels RGBA viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) # Load image on memory img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST) # 2.77 API change if bpy.app.version >= (2, 77, 0): tex = img.bindcode[0] else: tex = img.bindcode # -------------------------------------------- # Create output image (to apply texture) # -------------------------------------------- if "archipack_output" in bpy.data.images: out_img = bpy.data.images["archipack_output"] if out_img is not None: out_img.user_clear() bpy.data.images.remove(out_img) out = bpy.data.images.new("archipack_output", width, height) tmp_pixels = [1] * totpixel4 # -------------------------------- # Loop for all tiles # -------------------------------- for row in range(0, row_num): for col in range(0, col_num): buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4) bgl.glDisable( bgl.GL_SCISSOR_TEST ) # if remove this line, get blender screenshot not image bgl.glViewport(0, 0, tile_x, tile_y) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() # defines ortographic view for single tile x1 = tile_x * col y1 = tile_y * row bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y) # Clear bgl.glClearColor(0.0, 0.0, 0.0, 0.0) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) bgl.glEnable(bgl.GL_TEXTURE_2D) bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex) # defines drawing area bgl.glBegin(bgl.GL_QUADS) bgl.glColor3f(1.0, 1.0, 1.0) bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(0.0, 0.0) bgl.glTexCoord2f(1.0, 0.0) bgl.glVertex2f(width, 0.0) bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(width, height) bgl.glTexCoord2f(0.0, 1.0) bgl.glVertex2f(0.0, height) bgl.glEnd() # ----------------------------- # Loop to draw all lines # ----------------------------- for o, d in objlist: if o.hide is False: # verify visible layer for x in range(0, 20): if o.layers[x] is True: if x in layers: context.scene.objects.active = o # print("%s: %s" % (o.name, d.manip_stack)) manipulators = d.manip_stack if manipulators is not None: for m in manipulators: if m is not None: m.draw_callback( m, context, render=True) break # ----------------------------- # Loop to draw all debug # ----------------------------- """ if scene.archipack_debug is True: selobj = bpy.context.selected_objects for myobj in selobj: if scene.archipack_debug_vertices is True: draw_vertices(context, myobj, None, None) if scene.archipack_debug_faces is True or scene.archipack_debug_normals is True: draw_faces(context, myobj, None, None) """ """ if scene.archipack_rf is True: bgl.glColor3f(1.0, 1.0, 1.0) rfcolor = scene.archipack_rf_color rfborder = scene.archipack_rf_border rfline = scene.archipack_rf_line bgl.glLineWidth(rfline) bgl.glColor4f(rfcolor[0], rfcolor[1], rfcolor[2], rfcolor[3]) x1 = rfborder x2 = width - rfborder y1 = int(ceil(rfborder / (width / height))) y2 = height - y1 draw_rectangle((x1, y1), (x2, y2)) """ # -------------------------------- # copy pixels to temporary area # -------------------------------- bgl.glFinish() bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) # read image data for y in range(0, tile_y): # final image pixels position p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4) p2 = p1 + (tile_x * 4) # buffer pixels position b1 = y * width * 4 b2 = b1 + (tile_x * 4) if p1 < totpixel4: # avoid pixel row out of area if col == col_num - 1: # avoid pixel columns out of area p2 -= cut4 b2 -= cut4 tmp_pixels[p1:p2] = buffer[b1:b2] # ----------------------- # Copy temporary to final # ----------------------- out.pixels = tmp_pixels[:] # Assign image data img.gl_free() # free opengl image memory # delete image img.user_clear() bpy.data.images.remove(img) # remove temp file remove(outpath) # reset bgl.glEnable(bgl.GL_SCISSOR_TEST) # ----------------------- # restore opengl defaults # ----------------------- bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) bgl.glColor4f(0.0, 0.0, 0.0, 1.0) # Saves image if out is not None: # and (scene.archipack_render is True or animation is True): ren_path = bpy.context.scene.render.filepath filename = "ap_frame" if len(ren_path) > 0: if ren_path.endswith(path.sep): initpath = path.realpath(ren_path) + path.sep else: (initpath, filename) = path.split(ren_path) ftxt = "%04d" % scene.frame_current outpath = path.realpath( path.join(initpath, filename + ftxt + ".png")) self.save_image(outpath, out) settings.color_depth = depth return True except: settings.color_depth = depth print("Unexpected error:" + str(exc_info())) self.report({ 'ERROR' }, "Archipack: Unable to create render image. Be sure the output render path is correct" ) return False
def render_opengl(self, context): from math import ceil layers = [] scene = context.scene for x in range(0, 20): if scene.layers[x] is True: layers.extend([x]) objlist = context.scene.objects render_scale = scene.render.resolution_percentage / 100 width = int(scene.render.resolution_x * render_scale) height = int(scene.render.resolution_y * render_scale) # I cant use file_format becuase the pdf writer needs jpg format # the file_format returns 'JPEG' not 'JPG' # file_format = context.scene.render.image_settings.file_format.lower() ren_path = bpy.path.abspath(bpy.context.scene.render.filepath) + ".jpg" # if len(ren_path) > 0: # if ren_path.endswith(os.path.sep): # initpath = os.path.realpath(ren_path) + os.path.sep # else: # (initpath, filename) = os.path.split(ren_path) # outpath = os.path.join(initpath, "ogl_tmp.png") # else: # self.report({'ERROR'}, "Invalid render path") # return False img = get_render_image(ren_path) if img is None: self.report({'ERROR'}, "Invalid render path:" + ren_path) return False tile_x = 240 tile_y = 216 row_num = ceil(height / tile_y) col_num = ceil(width / tile_x) cut4 = (col_num * tile_x * 4) - width * 4 totpixel4 = width * height * 4 viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST) # 2.77 API change if bpy.app.version >= (2, 77, 0): tex = img.bindcode[0] else: tex = img.bindcode if context.scene.name in bpy.data.images: old_img = bpy.data.images[context.scene.name] old_img.user_clear() bpy.data.images.remove(old_img) img_result = bpy.data.images.new(context.scene.name, width, height) tmp_pixels = [1] * totpixel4 #---------- Loop for all tiles for row in range(0, row_num): for col in range(0, col_num): buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4) bgl.glDisable( bgl.GL_SCISSOR_TEST ) # if remove this line, get blender screenshot not image bgl.glViewport(0, 0, tile_x, tile_y) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() # defines ortographic view for single tile x1 = tile_x * col y1 = tile_y * row bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y) # Clear bgl.glClearColor(0.0, 0.0, 0.0, 0.0) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) bgl.glEnable(bgl.GL_TEXTURE_2D) bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex) # defines drawing area bgl.glBegin(bgl.GL_QUADS) bgl.glColor3f(1.0, 1.0, 1.0) bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(0.0, 0.0) bgl.glTexCoord2f(1.0, 0.0) bgl.glVertex2f(width, 0.0) bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(width, height) bgl.glTexCoord2f(0.0, 1.0) bgl.glVertex2f(0.0, height) bgl.glEnd() for obj in objlist: if obj.mv.type == 'VISDIM_A': for x in range(0, 20): if obj.layers[x] is True: if x in layers: opengl_dim = obj.mv.opengl_dim if not opengl_dim.hide: draw_dimensions(context, obj, opengl_dim, None, None) break #---------- copy pixels to temporary area bgl.glFinish() bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) # read image data for y in range(0, tile_y): # final image pixels position p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4) p2 = p1 + (tile_x * 4) # buffer pixels position b1 = y * width * 4 b2 = b1 + (tile_x * 4) if p1 < totpixel4: # avoid pixel row out of area if col == col_num - 1: # avoid pixel columns out of area p2 -= cut4 b2 -= cut4 tmp_pixels[p1:p2] = buffer[b1:b2] img_result.pixels = tmp_pixels[:] img.gl_free() img.user_clear() bpy.data.images.remove(img) os.remove(ren_path) bgl.glEnable(bgl.GL_SCISSOR_TEST) #---------- restore opengl defaults bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) bgl.glColor4f(0.0, 0.0, 0.0, 1.0) if img_result is not None: return img_result
def drawCallback(self, context): # use ImageTexture.evaluate / get Image.pixels in case of View2D? # seems unnecessary to restore afterwards. bgl.glViewport(*self.viewport) bgl.glScissor(*self.viewport) b = bgl.Buffer(bgl.GL_FLOAT, 3) for p in itertools.chain(self.points, self.current_mouse_points): bgl.glReadPixels(p[0], p[1], 1, 1, bgl.GL_RGB, bgl.GL_FLOAT, b) p[-1] = self.convertColorspace(context, b.to_list()) points_drawn = 0 max_points_to_draw = PTS_LIMIT - self.remaining last_point_drawn = None for p in self.points: if points_drawn == max_points_to_draw: break self.drawPoint(*p[2:5]) last_point_drawn = p points_drawn += 1 # under cursor -> probably not wanted for p in self.current_mouse_points[:-1]: if points_drawn == max_points_to_draw: break self.drawPoint(*p[2:5]) last_point_drawn = p points_drawn += 1 segments_drawn = 0 if len(self.points) > 1: ps = iter(self.points) next(ps) for p1, p2 in zip(self.points, ps): if segments_drawn == max_points_to_draw - 1: break self.drawSegment(p1[2], p1[3], p2[2], p2[3], False) segments_drawn += 1 if self.current_mouse_points: p1 = self.points[-1] p2 = self.current_mouse_points[0] if segments_drawn < max_points_to_draw - 1: self.drawSegment(p1[2], p1[3], p2[2], p2[3], True) segments_drawn += 1 if len(self.current_mouse_points) > 1: ps = iter(self.current_mouse_points) next(ps) for p1, p2 in zip(self.current_mouse_points, ps): if segments_drawn == max_points_to_draw - 1: break self.drawSegment(p1[2], p1[3], p2[2], p2[3], True) segments_drawn += 1 if points_drawn == max_points_to_draw: # this means even the point under the cursor _is_ already # surnumerary, thus we have to draw the last segment in red if self.current_mouse_points: p1 = last_point_drawn p2 = self.current_mouse_points[-1] self.drawSegment(p1[2], p1[3], p2[2], p2[3], True, True) if context.window_manager.crd_show_values: for p, i in zip(itertools.chain(self.points, self.current_mouse_points), range(points_drawn)): blf.position(0, p[2] + 10, p[3] - 10, 0) bgl.glColor4f(0.8, 0.8, 0.8, 1.0) blf.size(0, 10, context.user_preferences.system.dpi) blf.draw(0, "(%.3f, %.3f, %.3f)" % tuple(p[-1])) if points_drawn <= max_points_to_draw: # we want to draw the current color anyways if self.current_mouse_points: p = self.current_mouse_points[-1] blf.position(0, p[2] + 10, p[3] - 10, 0) bgl.glColor4f(0.8, 0.8, 0.8, 1.0) blf.size(0, 10, context.user_preferences.system.dpi) blf.draw(0, "(%.3f, %.3f, %.3f)" % tuple(p[-1])) bgl.glColor4f(0.8, 0.8, 0.8, 1.0) blf.size(0, 20, context.user_preferences.system.dpi) if context.window_manager.crd_use_intermediate: blf.position(0, 10, 60, 0) blf.draw(0, "Oversamples:") blf.position(0, 160, 60, 0) blf.draw(0, str(context.window_manager.crd_intermediate_amount)) blf.position(0, 10, 30, 0) blf.draw(0, "Path Type:") blf.position(0, 160, 30, 0) blf.draw(0, {"POLYLINE": "Polyline", "CUBIC_SPLINE": "Cubic Spline"}[context.window_manager.crd_path_type])
def generate_icon(name, verts=None, faces=None, coll="shape_types"): pcoll = preview_collections[coll] if name in pcoll: thumb = pcoll.get(name) else: thumb = pcoll.new(name) thumb.image_size = (200, 200) if verts is not None: import bgl polygon_color = bpy.context.user_preferences.themes[0].view_3d.edge_facesel edge_color = bpy.context.user_preferences.themes[0].view_3d.edge_select vertex_color = bpy.context.user_preferences.themes[0].view_3d.vertex_select clear_color = bpy.context.user_preferences.themes[0].user_interface.wcol_menu.inner viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) buffer = bgl.Buffer(bgl.GL_FLOAT, 200 * 200 * 4) bgl.glDisable(bgl.GL_SCISSOR_TEST) bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA) bgl.glEnable(bgl.GL_LINE_SMOOTH) bgl.glEnable(bgl.GL_POINT_SMOOTH) bgl.glViewport(0, 0, 200, 200) bgl.glMatrixMode(bgl.GL_MODELVIEW) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glPushMatrix() bgl.glLoadIdentity() bgl.gluOrtho2D(0, 0, 0, 0) bgl.glLineWidth(4.0) bgl.glPointSize(10.0) bgl.glClearColor(*clear_color) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) if faces is None: bgl.glBegin(bgl.GL_POLYGON) bgl.glColor3f(*polygon_color) for vert in verts: bgl.glVertex2f(*vert) bgl.glEnd() else: bgl.glBegin(bgl.GL_TRIANGLES) bgl.glColor3f(*polygon_color) for face in faces: bgl.glVertex2f(*verts[face[0]]) bgl.glVertex2f(*verts[face[1]]) bgl.glVertex2f(*verts[face[2]]) bgl.glEnd() bgl.glBegin(bgl.GL_LINE_LOOP) bgl.glColor3f(*edge_color) for vert in verts: bgl.glVertex2f(*vert) bgl.glEnd() bgl.glBegin(bgl.GL_POINTS) bgl.glColor3f(*vertex_color) for vert in verts: bgl.glVertex2f(*vert) bgl.glEnd() bgl.glReadPixels(0, 0, 200, 200, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) bgl.glEnable(bgl.GL_SCISSOR_TEST) bgl.glLineWidth(1.0) bgl.glPointSize(1.0) buffer = buffer[:] for idx in range(0, 200 * 200 * 4, 4): if buffer[idx] == clear_color[0] and \ buffer[idx + 1] == clear_color[1] and buffer[idx + 2] == clear_color[2]: buffer[idx + 3] = 0.0 thumb.image_pixels_float = buffer
def draw_callback_view3D(area, v3d, rv3d): if (area not in main.VIEW3D or len(area.regions) == 0 or bpy.context.scene.camera == None or area.type != "VIEW_3D" or rv3d.view_perspective != 'CAMERA' or not bpy.context.scene.pixel_grid_visible): return scene = bpy.context.scene viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) region = None for r in area.regions: if r.type == "WINDOW": region = r width = region.width height = region.height region_x = region.x region_y = region.y bgl.glViewport(region_x, region_y, width, height) camera_frame = view3d_camera_border(region, rv3d) # TopRight - BottomLeft screen_resolution = camera_frame[0] - camera_frame[2] resolution_percentage = scene.render.resolution_percentage / 100.0 resolution_x = int(scene.render.resolution_x * resolution_percentage) resolution_y = int(scene.render.resolution_y * resolution_percentage) screen_x = screen_resolution.x / resolution_x screen_y = screen_resolution.y / resolution_y #shift_x, shift_y = main.get_camera_shift(scene, screen_resolution.x, screen_resolution.x) # generate grid vertices = [] alpha = 0 if screen_x > GRID_MIN_SIZE and screen_y > GRID_MIN_SIZE: for x in range(resolution_x): position_x = camera_frame[3].x + x * screen_x vertices.extend( (position_x, camera_frame[0].y, position_x, camera_frame[2].y)) for y in range(resolution_y): position_y = camera_frame[0].y - y * screen_y vertices.extend( (camera_frame[2].x, position_y, camera_frame[0].x, position_y)) # fade in pixel grid alpha = maprange((GRID_MIN_SIZE, GRID_MIN_SIZE * 4), (0, 1.0), min(screen_x, screen_y)) alpha = min(1.0, max(0.0, alpha)) ''' vertices = [0, 0, 100, 0, 0, 0, 100, 100, 0, 0, 0, 100, 0, 0, 100, 100, ] ''' create_vao("grid", vertices) bgl.glEnable(bgl.GL_BLEND) bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA) prefs = bpy.context.user_preferences.addons[__package__].preferences color = prefs.pixel_grid_color color = (color[0], color[1], color[2], color[3] * alpha) draw_vertex_array("grid", bgl.GL_LINES, 2, color) bgl.glViewport(*tuple(viewport_info))
def drawCallback(self, context): # use ImageTexture.evaluate / get Image.pixels in case of View2D? # seems unnecessary to restore afterwards. bgl.glViewport(*self.viewport) bgl.glScissor(*self.viewport) b = bgl.Buffer(bgl.GL_FLOAT, 3) for p in itertools.chain(self.points, self.current_mouse_points): bgl.glReadPixels(p[0], p[1], 1, 1, bgl.GL_RGB, bgl.GL_FLOAT, b) p[-1] = self.convertColorspace(context, b.to_list()) points_drawn = 0 max_points_to_draw = PTS_LIMIT - self.remaining last_point_drawn = None for p in self.points: if points_drawn == max_points_to_draw: break self.drawPoint(*p[2:5]) last_point_drawn = p points_drawn += 1 # under cursor -> probably not wanted for p in self.current_mouse_points[:-1]: if points_drawn == max_points_to_draw: break self.drawPoint(*p[2:5]) last_point_drawn = p points_drawn += 1 segments_drawn = 0 if len(self.points) > 1: ps = iter(self.points) next(ps) for p1, p2 in zip(self.points, ps): if segments_drawn == max_points_to_draw - 1: break self.drawSegment(p1[2], p1[3], p2[2], p2[3], False) segments_drawn += 1 if self.current_mouse_points: p1 = self.points[-1] p2 = self.current_mouse_points[0] if segments_drawn < max_points_to_draw - 1: self.drawSegment(p1[2], p1[3], p2[2], p2[3], True) segments_drawn += 1 if len(self.current_mouse_points) > 1: ps = iter(self.current_mouse_points) next(ps) for p1, p2 in zip(self.current_mouse_points, ps): if segments_drawn == max_points_to_draw - 1: break self.drawSegment(p1[2], p1[3], p2[2], p2[3], True) segments_drawn += 1 if points_drawn == max_points_to_draw: # this means even the point under the cursor _is_ already # surnumerary, thus we have to draw the last segment in red if self.current_mouse_points: p1 = last_point_drawn p2 = self.current_mouse_points[-1] self.drawSegment(p1[2], p1[3], p2[2], p2[3], True, True) if context.window_manager.crd_show_values: for p, i in zip( itertools.chain(self.points, self.current_mouse_points), range(points_drawn)): blf.position(0, p[2] + 10, p[3] - 10, 0) bgl.glColor4f(0.8, 0.8, 0.8, 1.0) blf.size(0, 10, context.user_preferences.system.dpi) blf.draw(0, "(%.3f, %.3f, %.3f)" % tuple(p[-1])) if points_drawn <= max_points_to_draw: # we want to draw the current color anyways if self.current_mouse_points: p = self.current_mouse_points[-1] blf.position(0, p[2] + 10, p[3] - 10, 0) bgl.glColor4f(0.8, 0.8, 0.8, 1.0) blf.size(0, 10, context.user_preferences.system.dpi) blf.draw(0, "(%.3f, %.3f, %.3f)" % tuple(p[-1])) bgl.glColor4f(0.8, 0.8, 0.8, 1.0) blf.size(0, 20, context.user_preferences.system.dpi) if context.window_manager.crd_use_intermediate: blf.position(0, 10, 60, 0) blf.draw(0, "Oversamples:") blf.position(0, 160, 60, 0) blf.draw(0, str(context.window_manager.crd_intermediate_amount)) blf.position(0, 10, 30, 0) blf.draw(0, "Path Type:") blf.position(0, 160, 30, 0) blf.draw(0, { 'POLYLINE': "Polyline", 'CUBIC_SPLINE': "Cubic Spline" }[context.window_manager.crd_path_type])
def render_opengl(self, context): from math import ceil layers = [] scene = context.scene for x in range(0, 20): if scene.layers[x] is True: layers.extend([x]) objlist = context.scene.objects render_scale = scene.render.resolution_percentage / 100 width = int(scene.render.resolution_x * render_scale) height = int(scene.render.resolution_y * render_scale) # I cant use file_format becuase the pdf writer needs jpg format # the file_format returns 'JPEG' not 'JPG' # file_format = context.scene.render.image_settings.file_format.lower() ren_path = bpy.path.abspath(bpy.context.scene.render.filepath) + ".jpg" # if len(ren_path) > 0: # if ren_path.endswith(os.path.sep): # initpath = os.path.realpath(ren_path) + os.path.sep # else: # (initpath, filename) = os.path.split(ren_path) # outpath = os.path.join(initpath, "ogl_tmp.png") # else: # self.report({'ERROR'}, "Invalid render path") # return False img = get_render_image(ren_path) if img is None: self.report({'ERROR'}, "Invalid render path:" + ren_path) return False tile_x = 240 tile_y = 216 row_num = ceil(height / tile_y) col_num = ceil(width / tile_x) cut4 = (col_num * tile_x * 4) - width * 4 totpixel4 = width * height * 4 viewport_info = bgl.Buffer(bgl.GL_INT, 4) bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST) # 2.77 API change if bpy.app.version >= (2, 77, 0): tex = img.bindcode[0] else: tex = img.bindcode if context.scene.name in bpy.data.images: old_img = bpy.data.images[context.scene.name] old_img.user_clear() bpy.data.images.remove(old_img) img_result = bpy.data.images.new(context.scene.name, width, height) tmp_pixels = [1] * totpixel4 #---------- Loop for all tiles for row in range(0, row_num): for col in range(0, col_num): buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4) bgl.glDisable(bgl.GL_SCISSOR_TEST) # if remove this line, get blender screenshot not image bgl.glViewport(0, 0, tile_x, tile_y) bgl.glMatrixMode(bgl.GL_PROJECTION) bgl.glLoadIdentity() # defines ortographic view for single tile x1 = tile_x * col y1 = tile_y * row bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y) # Clear bgl.glClearColor(0.0, 0.0, 0.0, 0.0) bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) bgl.glEnable(bgl.GL_TEXTURE_2D) bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex) # defines drawing area bgl.glBegin(bgl.GL_QUADS) bgl.glColor3f(1.0, 1.0, 1.0) bgl.glTexCoord2f(0.0, 0.0) bgl.glVertex2f(0.0, 0.0) bgl.glTexCoord2f(1.0, 0.0) bgl.glVertex2f(width, 0.0) bgl.glTexCoord2f(1.0, 1.0) bgl.glVertex2f(width, height) bgl.glTexCoord2f(0.0, 1.0) bgl.glVertex2f(0.0, height) bgl.glEnd() for obj in objlist: if obj.mv.type == 'VISDIM_A': for x in range(0, 20): if obj.layers[x] is True: if x in layers: opengl_dim = obj.mv.opengl_dim if not opengl_dim.hide: draw_dimensions(context, obj, opengl_dim, None, None) break #---------- copy pixels to temporary area bgl.glFinish() bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) # read image data for y in range(0, tile_y): # final image pixels position p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4) p2 = p1 + (tile_x * 4) # buffer pixels position b1 = y * width * 4 b2 = b1 + (tile_x * 4) if p1 < totpixel4: # avoid pixel row out of area if col == col_num - 1: # avoid pixel columns out of area p2 -= cut4 b2 -= cut4 tmp_pixels[p1:p2] = buffer[b1:b2] img_result.pixels = tmp_pixels[:] img.gl_free() img.user_clear() bpy.data.images.remove(img) os.remove(ren_path) bgl.glEnable(bgl.GL_SCISSOR_TEST) #---------- restore opengl defaults bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) bgl.glColor4f(0.0, 0.0, 0.0, 1.0) if img_result is not None: return img_result