Ejemplo n.º 1
0
def test_invalid_send():
    client = SpeckleClient()
    client.account = Account(token="fake_token")
    transport = ServerTransport("3073b96e86", client)

    with pytest.raises(SpeckleException):
        operations.send(Base(), [transport])
Ejemplo n.º 2
0
def test_invalid_receive():
    client = SpeckleClient()
    client.account = Account(token="fake_token")
    transport = ServerTransport("fake stream", client)

    with pytest.raises(SpeckleException):
        operations.receive("fake object", transport)
Ejemplo n.º 3
0
def processItem(item):
    client, stream, branch, commit = item
    transport = ServerTransport(stream.id, client)
    stream_data = operations.receive(commit.referencedObject, transport)
    host_name = client.url[8:]
    dynamic_member_names = stream_data.get_dynamic_member_names()
    returnObjects = []
    for i, dynamic_member_name in enumerate(dynamic_member_names):
        obj_collection = stream_data[dynamic_member_name]
        temp_objects = []
        if len(obj_collection) > 0:
            for j, obj in enumerate(obj_collection):
                object_name = host_name + "_" + stream.id + "_" + branch.id + "_" + commit.id + "_" + dynamic_member_name + "_" + str(
                    j + 1)
                try:
                    speckle_mesh = getattr(obj, 'displayValue')[0]
                    units = getattr(obj, "units", None)
                    if units:
                        scale = get_scale_length(
                            units
                        ) / bpy.context.scene.unit_settings.scale_length
                    else:
                        scale = 1.0
                    blender_mesh = mesh_to_native(speckle_mesh,
                                                  name=object_name,
                                                  scale=scale)
                except:
                    blender_mesh = bpy.data.meshes.new(name=object_name)
                    bm = bmesh.new()
                    bm.verts.new((0.0, 0.0, 0.0))
                    bm.to_mesh(blender_mesh)
                    bm.free()
                new_object = bpy.data.objects.new(object_name, blender_mesh)
                member_names = obj.get_member_names()
                for member_name in member_names:
                    attribute = getattr(obj, member_name)
                    if isinstance(attribute, float) or isinstance(
                            attribute, int) or isinstance(attribute, str):
                        new_object[member_name] = attribute
                #temp_objects.append(new_object)
                item = [
                    new_object, new_object.matrix_world, None, obj.id,
                    object_name
                ]
                top_object1 = TopologyByGeometry.processItem(
                    item, 0.001, "Default")
                top_object2 = TopologySelfMerge.processItem(top_object1)
                d = DictionarySetValueAtKey.processItem(
                    top_object1.GetDictionary(), "TOPOLOGIC_type",
                    top_object2.GetTypeAsString())
                d = DictionarySetValueAtKey.processItem(
                    d, "TOPOLOGIC_length_unit",
                    bpy.context.scene.unit_settings.length_unit)
                top_object2.SetDictionary(d)
                temp_objects.append(top_object2)
            returnObjects.append(temp_objects)
    return returnObjects
Ejemplo n.º 4
0
    def test_send_and_receive(self, client, sample_stream, mesh):
        transport = ServerTransport(client=client, stream_id=sample_stream.id)
        hash = operations.send(mesh, transports=[transport])

        # also try constructing server transport with token and url
        transport = ServerTransport(
            stream_id=sample_stream.id, token=client.account.token, url=client.url
        )
        # use a fresh memory transport to force receiving from remote
        received = operations.receive(
            hash, remote_transport=transport, local_transport=MemoryTransport()
        )

        assert isinstance(received, FakeMesh)
        assert received.vertices == mesh.vertices
        assert isinstance(received.origin, Point)
        assert received.origin.x == mesh.origin.x
        # not comparing hashes as order is not guaranteed back from server

        mesh.id = hash  # populate with decomposed id for use in proceeding tests
def processItem(item):
	client, stream = item
	transport = ServerTransport(client=client, stream_id=stream.id)

	# get the `globals` branch
	branch = client.branch.get(stream.id, "globals")

	# get the latest commit
	if len(branch.commits.items) > 0:
		latest_commit = branch.commits.items[0]

		# receive the globals object
		globs = operations.receive(latest_commit.referencedObject, transport)
		return processBase(globs)
	return None
Ejemplo n.º 6
0
def import_stl():
    file_path, user_id, stream_id, branch_name, commit_message = sys.argv[1:]
    print(f'ImportSTL argv[1:]: {sys.argv[1:]}')

    # Parse input
    stl_mesh = stl.mesh.Mesh.from_file(file_path)
    print(
        f'Parsed mesh with {stl_mesh.points.shape[0]} faces ({stl_mesh.points.shape[0] * 3} vertices)'
    )

    # Construct speckle obj
    vertices = stl_mesh.points.flatten().tolist()
    faces = []
    for i in range(stl_mesh.points.shape[0]):
        faces.extend([0, 3 * i, 3 * i + 1, 3 * i + 2])

    speckle_mesh = Mesh(vertices=vertices,
                        faces=faces,
                        colors=[],
                        textureCoordinates=[])
    print('Constructed Speckle Mesh object')

    # Commit

    client = SpeckleClient(host=os.getenv('SPECKLE_SERVER_URL',
                                          'localhost:3000'),
                           use_ssl=False)
    client.authenticate(os.environ['USER_TOKEN'])

    if not client.branch.get(stream_id, branch_name):
        client.branch.create(
            stream_id, branch_name,
            'File upload branch' if branch_name == 'uploads' else '')

    transport = ServerTransport(client=client, stream_id=stream_id)
    id = operations.send(base=speckle_mesh, transports=[transport])

    commit_id = client.commit.create(stream_id=stream_id,
                                     object_id=id,
                                     branch_name=(branch_name
                                                  or DEFAULT_BRANCH),
                                     message=(commit_message
                                              or 'STL file upload'),
                                     source_application='STL')

    return commit_id
Ejemplo n.º 7
0
    def test_branch_get(self, client, mesh, stream, branch):
        transport = ServerTransport(client=client, stream_id=stream.id)
        mesh.id = operations.send(mesh, transports=[transport])

        client.commit.create(
            stream_id=stream.id,
            branch_name=branch.name,
            object_id=mesh.id,
            message="a commit for testing branch get",
        )

        fetched_branch = client.branch.get(stream_id=stream.id,
                                           name=branch.name)

        assert isinstance(fetched_branch, Branch)
        assert fetched_branch.name == branch.name
        assert fetched_branch.description == branch.description
        assert isinstance(fetched_branch.commits.items, list)
        assert isinstance(fetched_branch.commits.items[0], Commit)
Ejemplo n.º 8
0
def processItem(item):
    client, stream, branch, description, message, key, data, run = item
    if not run:
        return None
    # create a base object to hold data
    base = Base()
    base[key] = data
    transport = ServerTransport(stream.id, client)
    # and send the data to the server and get back the hash of the object
    obj_id = operations.send(base, [transport])

    # now create a commit on that branch with your updated data!
    commit_id = client.commit.create(
        stream.id,
        obj_id,
        "gbxml",
        message=message,
    )
    print("COMMIT ID", commit_id)
    for commit in branch.commits.items:
        print("  VS. COMMIT.ID", commit.id)
        if commit.id == commit_id:
            return commit
    return None
Ejemplo n.º 9
0
def processItem(item):
    client, stream, branch, description, message, key, blender_object, openURL, run = item
    if not run:
        return None
    # create a base object to hold data
    #base = Base()
    #base[key] = obj
    transport = ServerTransport(stream.id, client)
    # and send the data to the server and get back the hash of the object
    print("Blender Object:", blender_object)
    base = convert_to_speckle(blender_object, 1.0, desgraph=None)
    obj_id = operations.send(base[0], [transport])

    # now create a commit on that branch with your updated data!
    commit_id = client.commit.create(
        stream.id,
        obj_id,
        branch.name,
        message=message,
    )
    web_address = client.url + "/streams/" + stream.id + "/commits/" + commit_id
    if openURL:
        webbrowser.open(web_address)
    return web_address
Ejemplo n.º 10
0
def runItem(item):
    resetItem(item)
    client, stream, branch, commit = item
    transport = ServerTransport(stream.id, client)
    stream_data = operations.receive(commit.referencedObject, transport)
    host_name = client.url[8:]
    client_collection = addCollectionIfNew("Host " + host_name)
    stream_collection = addCollectionIfNew("Stream " + stream.id)
    branch_collection = addCollectionIfNew("Branch " + branch.id)
    commit_collection = addCollectionIfNew("Commit " + commit.id)
    dynamic_member_names = stream_data.get_dynamic_member_names()
    returnObjects = []
    for i, dynamic_member_name in enumerate(dynamic_member_names):
        obj_collection = stream_data[dynamic_member_name]
        if len(obj_collection) > 0:
            object_collection = addCollectionIfNew(host_name + "_" +
                                                   stream.id + "_" +
                                                   branch.id + "_" +
                                                   commit.id + "_" +
                                                   dynamic_member_name)
            for j, obj in enumerate(obj_collection):
                object_name = host_name + "_" + stream.id + "_" + branch.id + "_" + commit.id + "_" + dynamic_member_name + "_" + str(
                    j + 1)
                try:
                    speckle_mesh = getattr(obj, 'displayValue')[0]
                    blender_mesh = mesh_to_native(speckle_mesh, object_name)
                except:
                    blender_mesh = bpy.data.meshes.new(name=object_name)
                    bm = bmesh.new()
                    bm.verts.new((0.0, 0.0, 0.0))
                    bm.to_mesh(blender_mesh)
                    bm.free()

                # Delete any pre-existing object with the same name
                try:
                    object_to_delete = bpy.data.objects[object_name]
                    bpy.data.objects.remove(object_to_delete, do_unlink=True)
                except:
                    pass
                new_object = bpy.data.objects.new(object_name, blender_mesh)
                member_names = obj.get_member_names()
                for member_name in member_names:
                    attribute = getattr(obj, member_name)
                    if isinstance(attribute, float) or isinstance(
                            attribute, int) or isinstance(attribute, str):
                        new_object[member_name] = attribute
                object_collection.objects.link(new_object)
                returnObjects.append(new_object)
            try:
                commit_collection.children.link(object_collection)
            except:
                pass
    try:
        branch_collection.children.link(commit_collection)
    except:
        pass
    try:
        stream_collection.children.link(branch_collection)
    except:
        pass
    try:
        client_collection.children.link(stream_collection)
    except:
        pass
    try:
        bpy.context.scene.collection.children.link(client_collection)
    except:
        pass
    return returnObjects
Ejemplo n.º 11
0
def import_obj():
    file_path, user_id, stream_id, branch_name, commit_message = sys.argv[1:]
    print(f'ImportOBJ argv[1:]: {sys.argv[1:]}')

    # Parse input
    obj = ObjFile(file_path)
    print(
        f'Parsed obj with {len(obj.faces)} faces ({len(obj.vertices) * 3} vertices)'
    )

    speckle_root = Base()
    speckle_root['@objects'] = []

    for objname in obj.objects:
        print(f'  Converting {objname}...')

        speckle_obj = Base()
        speckle_obj.name = objname
        speckle_obj['@displayValue'] = []
        speckle_root['@objects'].append(speckle_obj)

        for obj_mesh in obj.objects[objname]:
            speckle_vertices = [
                coord for point in obj_mesh['vertices'] for coord in point
            ]
            speckle_faces = []
            for obj_face in obj_mesh['faces']:
                if len(obj_face) == 3:
                    speckle_faces.append(0)
                elif len(obj_face) == 4:
                    speckle_faces.append(1)
                else:
                    speckle_faces.append(len(obj_face))
                speckle_faces.extend(obj_face)

            has_vertex_colors = False
            for vc in obj_mesh['vertex_colors']:
                if vc is not None:
                    has_vertex_colors = True
            colors = []
            if has_vertex_colors:
                for vc in obj_mesh['vertex_colors']:
                    if vc is None:
                        r, g, b = (1.0, 1.0, 1.0)
                    else:
                        r, g, b = vc
                    argb = (1.0, r, g, b)
                    color = int.from_bytes([int(val * 255) for val in argb],
                                           byteorder="big",
                                           signed=True)
                    colors.append(color)

            speckle_mesh = Mesh(vertices=speckle_vertices,
                                faces=speckle_faces,
                                colors=colors,
                                textureCoordinates=[])

            obj_material = obj_mesh['material']
            if obj_material:
                speckle_mesh['renderMaterial'] = convert_material(obj_material)

            speckle_obj['@displayValue'].append(speckle_mesh)

    # Commit

    client = SpeckleClient(host=os.getenv('SPECKLE_SERVER_URL',
                                          'localhost:3000'),
                           use_ssl=False)
    client.authenticate(os.environ['USER_TOKEN'])

    if not client.branch.get(stream_id, branch_name):
        client.branch.create(
            stream_id, branch_name,
            'File upload branch' if branch_name == 'uploads' else '')

    transport = ServerTransport(client=client, stream_id=stream_id)
    id = operations.send(base=speckle_root, transports=[transport])

    commit_id = client.commit.create(stream_id=stream_id,
                                     object_id=id,
                                     branch_name=(branch_name
                                                  or DEFAULT_BRANCH),
                                     message=(commit_message
                                              or 'OBJ file upload'),
                                     source_application='OBJ')

    return commit_id