Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
3.6 kB
17
Indexable
Never
from socket import *
import bpy,gpu, threading

### Drawing ###
_handle_3d=None
to_draw=False

def draw(self, context):
    global to_draw,conn
    
    if not to_draw:
        return
    
    to_draw=False

    self.framebuffer = gpu.state.active_framebuffer_get()

    self.viewport_info = gpu.state.viewport_get()
    self.width = self.viewport_info[2]
    self.height = self.viewport_info[3]

    self.framebuffer_image.scale(self.width, self.height)
    
    self.pixelBuffer = self.framebuffer.read_color(0, 0, self.width, self.height, 4, 0, 'FLOAT')
    
    self.pixelBuffer.dimensions = self.width * self.height * 4
    self.framebuffer_image.pixels.foreach_set(self.pixelBuffer)

    conn.send("ok".encode())

class ModalFramebufferCopy(bpy.types.Operator):
    bl_idname = "view3d.modal_framebuffer_copy"
    bl_label = "Draw 3D View Framebuffer"

    def __init__(self):
        # init variables
        self.width = 32
        self.height = 32
        self.image_name = "color_buffer_copy"
        self.framebuffer = None
        self.viewport_info = None
        self.pixelBuffer = None

        if not self.image_name in bpy.data.images:
            self.framebuffer_image = bpy.data.images.new(self.image_name , 32, 32, float_buffer=True)
        else:
            self.framebuffer_image = bpy.data.images[self.image_name]


    def modal(self, context, event):
        # stop the execution of this example code if 'ESC' is pressed
        if event.type in {'ESC'}:
            bpy.types.SpaceView3D.draw_handler_remove(_handle_3d, 'WINDOW')
            return {'CANCELLED'}

        return {'PASS_THROUGH'}


    def invoke(self, context, event):
        print("Invoking modal operator")
        global _handle_3d
        
        _handle_3d = bpy.types.SpaceView3D.draw_handler_add(draw, (self, context), 'WINDOW', 'PRE_VIEW') # this draws the viewport objects alone (without grid)

        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}


def register():
    bpy.utils.register_class(ModalFramebufferCopy)


def unregister():
    bpy.utils.unregister_class(ModalFramebufferCopy)


### Server Stuff ###
s= socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1)
s.bind(("127.0.0.1",6000))

conn=None

def start_server():
    global conn,to_draw
    
    server_active=True
    while server_active:
        print("Waiting for connection...")
        try:
            s.listen()
            conn, addr = s.accept()
            print("Connection Established!")
            while server_active:
                data = conn.recv(1024).decode()
                if not data:
                    break
                print("got res data=",data)
                if(data=="update"):
                    ## generating image
                    print("rotating..")
                    bpy.data.objects['Cube'].rotation_euler[0] = 1.5
                    to_draw=True
                    bpy.ops.view3d.modal_framebuffer_copy('INVOKE_DEFAULT')
                    
                elif(data=="terminate"):
                    server_active=False
                    conn.send("ok".encode())
        except error:
            print("Connection Terminated! Restarting...")
            
    print("Server Terminated!")
    bpy.types.SpaceView3D.draw_handler_remove(_handle_3d, 'WINDOW')


### common ###
if __name__ == "__main__":
    register()

    s= socket(AF_INET, SOCK_STREAM)
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1)
    s.bind(("127.0.0.1",6000))
    
    server_thread=threading.Thread(target=start_server)
    server_thread.start()