예제 #1
0
def _generate_camera_data(camera, lens, frame0):
    camera_data = {}
    cam_num_frames = tde4.getCameraNoFrames(camera)

    img_width = tde4.getCameraImageWidth(camera)
    img_height = tde4.getCameraImageHeight(camera)
    camera_data['resolution'] = (img_width, img_height)

    film_back_x = tde4.getLensFBackWidth(lens)
    film_back_y = tde4.getLensFBackHeight(lens)
    camera_data['film_back_cm'] = (film_back_x, film_back_y)

    lco_x = tde4.getLensLensCenterX(lens)
    lco_y = tde4.getLensLensCenterY(lens)
    camera_data['lens_center_offset_cm'] = (lco_x, lco_y)

    camera_data['per_frame'] = []
    for frame in range(1, cam_num_frames):
        # Note: In 3DEqualizer, film back and lens center is assumed
        # to be static, only focal length can be dynamic.
        focal_length = tde4.getCameraFocalLength(camera, frame)
        frame_data = {
            'frame': frame + frame0,
            'focal_length_cm': focal_length,
        }
        camera_data['per_frame'].append(frame_data)

    return camera_data
예제 #2
0
파일: tools.py 프로젝트: Rotomator/noid
def cameraHasDistortion(camera):
    if isClassicModel(camera):
        return cameraHasDistortionClassic(camera)
    else:
        lens = tde4.getCameraLens(camera)
        model = getCameraModel(camera)
        for parameterName in getLDmodelParameterList(model):
            defaultValue = tde4.getLDModelParameterDefault(
                model, parameterName)
            # distorsionMode
            dyndistmode = tde4.getLensDynamicDistortionMode(lens)
            if dyndistmode == "DISTORTION_STATIC":
                actualValue = tde4.getLensLDAdjustableParameter(
                    lens, parameterName, 1, 1)
                if defaultValue != actualValue:
                    return True
            else:
                num_frames = tde4.getCameraNoFrames(camera)
                for frame in range(1, num_frames + 1):
                    focal = tde4.getCameraFocalLength(camera, frame)
                    focus = tde4.getCameraFocus(camera, frame)
                    actualValue = tde4.getLensLDAdjustableParameter(
                        lens, parameterName, focal, focus)
                    if defaultValue != actualValue:
                        return True
        return False
예제 #3
0
def getOutSize(req, cameraIndex, cameraTmp):
    # get the actual image size from cameraTmp
    imageHeightInTmp = tde4.getCameraImageHeight(cameraTmp)
    imageWidthInTmp = tde4.getCameraImageWidth(cameraTmp)

    lensTmp = tde4.getCameraLens(cameraTmp)

    folcalParameter = getFocalParameters(lensTmp)

    # distorsionMode
    dyndistmode = tde4.getLensDynamicDistortionMode(lensTmp)

    log.debug('dyndistmode : ' + str(dyndistmode))

    if dyndistmode == "DISTORTION_STATIC":
        lensModelParameter = getLensModelParameter(camera=None,
                                                   lens=lensTmp,
                                                   frame=None)
        resOutTmp = get_bounding_box.calculateBoundigBox(
            imageWidthInTmp, imageHeightInTmp, "undistort", folcalParameter,
            lensModelParameter)
        imageWidthOuttmp = resOutTmp.width
        imageHeightOuttmp = resOutTmp.height
    else:
        imageHeightOuttmp = imageHeightInTmp
        imageWidthOuttmp = imageWidthInTmp
        for frame in range(1, tde4.getCameraNoFrames(cameraTmp) + 1):
            lensModelParameter = getLensModelParameter(camera=cameraTmp,
                                                       lens=lensTmp,
                                                       frame=frame)
            resOuttmp = get_bounding_box.calculateBoundigBox(
                imageWidthInTmp, imageHeightInTmp, "undistort",
                folcalParameter, lensModelParameter)
            if imageHeightOuttmp < resOuttmp.height:
                imageHeightOuttmp = resOuttmp.height
            if imageWidthOuttmp < resOuttmp.width:
                imageWidthOuttmp = resOuttmp.width

    if imageHeightInTmp > imageHeightOuttmp:
        imageHeightOuttmp = imageHeightInTmp
    if imageWidthInTmp > imageWidthOuttmp:
        imageWidthOuttmp = imageWidthInTmp

    log.debug('****************** lensModelParameter ********************')
    for key in lensModelParameter.keys():
        log.debug(key + ' : ' + str(lensModelParameter.get(key)))

    return imageHeightOuttmp, imageWidthOuttmp
예제 #4
0
파일: tools.py 프로젝트: Rotomator/noid
 def getInfoCam(self):
     cam = self.cam
     index = self.index
     self.offset = tde4.getCameraFrameOffset(cam)
     self.cameraPath = tde4.getCameraPath(cam).replace('\\', '/')
     self.camType = tde4.getCameraType(cam)
     self.noframes = tde4.getCameraNoFrames(cam)
     self.lens = tde4.getCameraLens(cam)
     self.rez_x = tde4.getCameraImageWidth(cam)
     self.rez_y = tde4.getCameraImageHeight(cam)
     self.model = tde4.getLensLDModel(self.lens)
     self.firstFrame = tde4.getCameraSequenceAttr(cam)[0]
     self.name = "%s_%s_1" % (validName(tde4.getCameraName(cam)), index)
     self.lastFrame = '%d' % (self.firstFrame + self.noframes - 1)
     self.firstFrame = '%d' % self.firstFrame
     self.focal_cm = tde4.getCameraFocalLength(cam, 1)
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".ty\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".tz\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".rx\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".ry\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".rz\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".sx\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".sy\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".sz\");\n")
            #
            # write cameras...

            cl = tde4.getCameraList()
            index = 1
            for cam in cl:
                camType = tde4.getCameraType(cam)
                noframes = tde4.getCameraNoFrames(cam)
                lens = tde4.getCameraLens(cam)
                if lens != None:
                    name = validName(tde4.getCameraName(cam))
                    if tde4.getCameraStereoOrientation(
                            cam) == 'STEREO_LEFT' and tde4.getCameraStereoMode(
                                cam) != 'STEREO_OFF':
                        name = ShotName + '_trk_camLeft'
                    elif tde4.getCameraStereoOrientation(
                            cam
                    ) == 'STEREO_RIGHT' and tde4.getCameraStereoMode(
                            cam) != 'STEREO_OFF':
                        name = ShotName + '_trk_camRight'
                    else:
                        name = ShotName + '_trk_cam'
                    #name       = "%s_%s_1"%(name,index)
예제 #6
0
def _generate_v2_v3_and_v4(point_group,
                           camera,
                           points,
                           version=None,
                           **kwargs):
    """
    Generate the UV file format contents, using JSON format.

    Set the individual _generate_v2 or _generate_v3 functions for
    details of what is stored.

    :param point_group: The 3DE Point Group containing 'points'
    :type point_group: str

    :param camera: The 3DE Camera containing 2D 'points' data.
    :type camera: str

    :param points: The list of 3DE Points representing 2D data to
                   save.
    :type points: list of str

    :param version: The version of file to generate,
                    UV_TRACK_FORMAT_VERSION_2 or
                    UV_TRACK_FORMAT_VERSION_3.
    :type version: int

    :param start_frame: Format v2 and v3; The frame number to be
                        considered at 'first frame'.
                        Defaults to 1001 if set to None.
    :type start_frame: None or int

    :param undistort: Format v2; Should we apply undistortion to the 2D
                      points data? Yes or no.
    :type undistort: bool

    :returns: A JSON format string, with the UV Track data in it.
    :rtype: str
    """
    assert isinstance(point_group, basestring)
    assert isinstance(camera, basestring)
    assert isinstance(points, (list, tuple))
    assert isinstance(version, (int, long))
    assert version in [
        UV_TRACK_FORMAT_VERSION_2, UV_TRACK_FORMAT_VERSION_3,
        UV_TRACK_FORMAT_VERSION_4
    ]

    start_frame = kwargs.get('start_frame')
    assert start_frame is None or isinstance(start_frame, int)
    if start_frame is None:
        start_frame = 1001

    undistort = None
    if version == UV_TRACK_FORMAT_VERSION_2:
        undistort = kwargs.get('undistort')
        assert isinstance(undistort, bool)

    data = None
    if version == UV_TRACK_FORMAT_VERSION_2:
        data = UV_TRACK_HEADER_VERSION_2.copy()
    elif version == UV_TRACK_FORMAT_VERSION_3:
        data = UV_TRACK_HEADER_VERSION_3.copy()
    elif version == UV_TRACK_FORMAT_VERSION_4:
        data = UV_TRACK_HEADER_VERSION_4.copy()
    else:
        raise ValueError("Version number is invalid; %r" % version)

    cam_num_frames = tde4.getCameraNoFrames(camera)
    camera_fov = tde4.getCameraFOV(camera)

    if len(points) == 0:
        return ''

    frame0 = int(start_frame)
    frame0 -= 1

    data['num_points'] = len(points)
    data['is_undistorted'] = None
    if version == UV_TRACK_FORMAT_VERSION_2:
        data['is_undistorted'] = bool(undistort)

    data['points'] = []
    for point in points:
        point_data = {}

        # Query point information
        name = tde4.getPointName(point_group, point)
        uid = None
        if SUPPORT_PERSISTENT_ID is True:
            uid = tde4.getPointPersistentID(point_group, point)
        point_set = tde4.getPointSet(point_group, point)
        point_set_name = None
        if point_set is not None:
            point_set_name = tde4.getSetName(point_group, point_set)
        point_data['name'] = name
        point_data['id'] = uid
        point_data['set_name'] = point_set_name
        valid_mode = _get_point_valid_mode(point_group, point)

        # Get the 3D point position
        if version in [UV_TRACK_FORMAT_VERSION_3, UV_TRACK_FORMAT_VERSION_4]:
            point_data['3d'] = _get_3d_data_from_point(point_group, point)

        # Write per-frame position data
        frame = 1  # 3DE starts at frame '1' regardless of the 'start frame'.
        point_data['per_frame'] = []
        pos_block = tde4.getPointPosition2DBlock(point_group, point, camera, 1,
                                                 cam_num_frames)
        for pos in pos_block:
            if pos[0] == -1.0 or pos[1] == -1.0:
                # No valid data here.
                frame += 1
                continue

            # Is the 2D point obscured?
            valid = tde4.isPointPos2DValid(point_group, point, camera, frame)
            if valid == 0:
                # No valid data here.
                frame += 1
                continue

            # Check if we're inside the FOV / Frame or not.
            valid_pos = _is_valid_position(pos, camera_fov, valid_mode)
            if valid_pos is False:
                frame += 1
                continue

            pos_undist = pos
            if undistort is True or undistort is None:
                pos_undist = tde4.removeDistortion2D(camera, frame, pos)
            weight = _get_point_weight(point_group, point, camera, frame)

            f = frame + frame0
            frame_data = {'frame': f, 'pos': pos_undist, 'weight': weight}
            if version in [
                    UV_TRACK_FORMAT_VERSION_3, UV_TRACK_FORMAT_VERSION_4
            ]:
                frame_data['pos_dist'] = pos
            point_data['per_frame'].append(frame_data)
            frame += 1

        data['points'].append(point_data)

    if version == UV_TRACK_FORMAT_VERSION_4:
        lens = tde4.getCameraLens(camera)
        data['camera'] = _generate_camera_data(camera, lens, frame0)

    data_str = json.dumps(data)
    return data_str
예제 #7
0
def exportMocaObjects(f, frameStart):
    #
    # write object/mocap point groups...
    frameStart = int(frameStart)
    frame0 = frameStart - 1

    camera = tde4.getCurrentCamera()
    noframes = tde4.getCameraNoFrames(camera)
    pgl = tde4.getPGroupList()
    index = 1
    for pg in pgl:
        if tde4.getPGroupType(pg) == "OBJECT" and camera is not None:
            f.write("\n")
            f.write("// create object point group...\n")
            groupValidName = tools.validName(tde4.getPGroupName(pg))
            pgname = "objectPGroup_%s_%d_1" % (groupValidName, index)
            index += 1
            f.write(
                "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                % pgname)
            f.write(
                "$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n"
            )

            # write points...
            l = tde4.getPointList(pg)
            for p in l:
                if tde4.isPointCalculated3D(pg, p):
                    name = tde4.getPointName(pg, p)
                    name = "p%s" % tools.validName(name)
                    p3d = tde4.getPointCalcPosition3D(pg, p)
                    p3d = convertZup(p3d, yup)
                    if 'agisoft' not in name:
                        f.write("\n")
                        f.write("// create point %s...\n" % name)
                        f.write(
                            "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                            % name)
                        f.write("$locator = (\"|\" + $locator);\n")
                        f.write("xform -t %.15f %.15f %.15f $locator;\n" %
                                (p3d[0], p3d[1], p3d[2]))
                        f.write("parent $locator $pointGroupName;\n")

            f.write("\n")
            scale = tde4.getPGroupScale3D(pg)
            f.write(
                "xform -zeroTransformPivots -rotateOrder zxy -scale %.15f %.15f %.15f $pointGroupName;\n"
                % (scale, scale, scale))

            # animate object point group...
            f.write("\n")
            f.write("// animating point group %s...\n" % pgname)
            frame = 1
            rot0 = None

            while frame <= noframes:
                # rot/pos...
                p3d = tde4.getPGroupPosition3D(pg, camera, frame)
                p3d = convertZup(p3d, yup)
                r3d = tde4.getPGroupRotation3D(pg, camera, frame)
                rot = convertToAngles(r3d)
                if frame > 1:
                    rot = [
                        angleMod360(rot0[0], rot[0]),
                        angleMod360(rot0[1], rot[1]),
                        angleMod360(rot0[2], rot[2])
                    ]
                rot0 = rot
                f.write(
                    "setKeyframe -at translateX -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, p3d[0]))
                f.write(
                    "setKeyframe -at translateY -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, p3d[1]))
                f.write(
                    "setKeyframe -at translateZ -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, p3d[2]))
                f.write(
                    "setKeyframe -at rotateX -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, rot[0]))
                f.write(
                    "setKeyframe -at rotateY -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, rot[1]))
                f.write(
                    "setKeyframe -at rotateZ -t %d -v %.15f $pointGroupName;\n"
                    % (frame + frame0, rot[2]))

                frame += 1

        # mocap point groups...
        if tde4.getPGroupType(pg) == "MOCAP" and camera is not None:
            f.write("\n")
            f.write("// create mocap point group...\n")
            groupValidName = tools.validName(tde4.getPGroupName(pg))
            pgname = "objectPGroup_%s_%d_1" % (groupValidName, index)
            index += 1
            f.write(
                "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                % pgname)
            f.write(
                "$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n"
            )

            # write points...
            l = tde4.getPointList(pg)
            for p in l:
                if tde4.isPointCalculated3D(pg, p):
                    name = tde4.getPointName(pg, p)
                    name = "p%s" % tools.validName(name)
                    p3d = tde4.getPointMoCapCalcPosition3D(pg, p, camera, 1)
                    p3d = convertZup(p3d, yup)
                    f.write("\n")
                    f.write("// create point %s...\n" % name)
                    f.write(
                        "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                        % name)
                    f.write("$locator = (\"|\" + $locator);\n")
                    f.write("xform -t %.15f %.15f %.15f $locator;\n" %
                            (p3d[0], p3d[1], p3d[2]))
                    for frame in range(1, noframes + 1):
                        p3d = tde4.getPointMoCapCalcPosition3D(
                            pg, p, camera, frame)
                        p3d = convertZup(p3d, yup)
                        f.write(
                            "setKeyframe -at translateX -t %d -v %.15f $locator; "
                            % (frame + frame0, p3d[0]))
                        f.write(
                            "setKeyframe -at translateY -t %d -v %.15f $locator; "
                            % (frame + frame0, p3d[1]))
                        f.write(
                            "setKeyframe -at translateZ -t %d -v %.15f $locator; "
                            % (frame + frame0, p3d[2]))
                    f.write("parent $locator $pointGroupName;\n")

            f.write("\n")
            scale = tde4.getPGroupScale3D(pg)
            f.write(
                "xform -zeroTransformPivots -rotateOrder zxy -scale %.15f %.15f %.15f $pointGroupName;\n"
                % (scale, scale, scale))

            # animate mocap point group...
            f.write("\n")
            f.write("// animating point group %s...\n" % pgname)
            frame = 1
            while frame <= noframes:
                # rot/pos...
                p3d = tde4.getPGroupPosition3D(pg, camera, frame)
                p3d = convertZup(p3d, yup)
                r3d = tde4.getPGroupRotation3D(pg, camera, frame)
                rot = convertToAngles(r3d)
                if frame > 1:
                    rot = [
                        angleMod360(rot0[0], rot[0]),
                        angleMod360(rot0[1], rot[1]),
                        angleMod360(rot0[2], rot[2])
                    ]
                rot0 = rot
                f.write(
                    "setKeyframe -at translateX -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, p3d[0]))
                f.write(
                    "setKeyframe -at translateY -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, p3d[1]))
                f.write(
                    "setKeyframe -at translateZ -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, p3d[2]))
                f.write(
                    "setKeyframe -at rotateX -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, rot[0]))
                f.write(
                    "setKeyframe -at rotateY -t %d -v %.15f $pointGroupName; "
                    % (frame + frame0, rot[1]))
                f.write(
                    "setKeyframe -at rotateZ -t %d -v %.15f $pointGroupName;\n"
                    % (frame + frame0, rot[2]))

                frame += 1
def _generate_v1(point_group,
                 camera,
                 points,
                 start_frame=None,
                 undistort=False):
    """
    Generate the UV file format contents, using a basic ASCII format.

    :param point_group: The 3DE Point Group containing 'points'
    :type point_group: str

    :param camera: The 3DE Camera containing 2D 'points' data.
    :type camera: str

    :param points: The list of 3DE Points representing 2D data to
                   save.
    :type points: list of str

    :param start_frame: The frame number to be considered at
                       'first frame'. Defaults to 1001 if
                       set to None.
    :type start_frame: None or int

    :param undistort: Should we apply undistortion to the 2D points
                      data? Yes or no.
    :type undistort: bool

    Each point will store:
    - Point name
    - X, Y position (in UV coordinates, per-frame)
    - Point weight (per-frame)
    """
    assert isinstance(point_group, basestring)
    assert isinstance(camera, basestring)
    assert isinstance(points, (list, tuple))
    assert start_frame is None or isinstance(start_frame, int)
    assert isinstance(undistort, bool)
    if start_frame is None:
        start_frame = 1001
    data_str = ''
    cam_num_frames = tde4.getCameraNoFrames(camera)

    if len(points) == 0:
        return data_str

    frame0 = int(start_frame)
    frame0 -= 1

    data_str += '{0:d}\n'.format(len(points))

    for point in points:
        name = tde4.getPointName(point_group, point)
        c2d = tde4.getPointPosition2DBlock(point_group, point, camera, 1,
                                           cam_num_frames)

        # Write per-frame position data
        num_valid_frame = 0
        pos_list = []
        weight_list = []
        frame = 1  # 3DE starts at frame '1' regardless of the 'start-frame'.
        for v in c2d:
            if v[0] == -1.0 or v[1] == -1.0:
                # No valid data here.
                frame += 1
                continue

            # Does the 2D point go outside the camera FOV? Is that ok?
            valid = tde4.isPointPos2DValid(point_group, point, camera, frame)
            if valid == 0:
                # No valid data here.
                frame += 1
                continue
            # Number of points with valid positions
            num_valid_frame += 1

            f = frame + frame0
            if undistort is True:
                v = tde4.removeDistortion2D(camera, frame, v)
            weight = 1.0
            if SUPPORT_POINT_WEIGHT_BY_FRAME is True:
                weight = tde4.getPointWeightByFrame(point_group, point, camera,
                                                    frame)

            pos_list.append((f, v))
            weight_list.append((f, weight))
            frame += 1

        # add data
        data_str += name + '\n'
        data_str += '{0:d}\n'.format(num_valid_frame)
        for pos_data, weight_data in zip(pos_list, weight_list):
            f = pos_data[0]
            v = pos_data[1]
            w = weight_data[1]
            assert f == weight_data[0]
            data_str += '%d %.15f %.15f %.8f\n' % (f, v[0], v[1], w)

    return data_str
예제 #9
0
def generateNukeNode(cam, direction, offset=0, index=0):
    lens = tde4.getCameraLens(cam)
    model = tde4.getLensLDModel(lens)
    num_frames = tde4.getCameraNoFrames(cam)
    w_fb_cm = tde4.getLensFBackWidth(lens)
    h_fb_cm = tde4.getLensFBackHeight(lens)
    lco_x_cm = tde4.getLensLensCenterX(lens)
    lco_y_cm = tde4.getLensLensCenterY(lens)
    pxa = tde4.getLensPixelAspect(lens)
    # xa,xb,ya,yb in unit coordinates, in this order.
    fov = tde4.getCameraFOV(cam)

    print 'camera: ', tde4.getCameraName(cam)
    print 'offset:', offset
    print 'lens:', tde4.getLensName(lens)
    print 'model: ', model

    nukeNode = []

    nukeNode.append('# Created by 3DEqualizer4 ')
    nukeNode.append('# using Export Nuke Distortion Nodes export script')
    nukeNode.append("LD" + tools.nukify_name(model) + ' {')
    nukeNode.append(' direction ' + direction)

    # write focal length curve if dynamic
    if tde4.getCameraZoomingFlag(cam):
        print 'dynamic focal length'
        dynFocalLength = []

        for frame in range(1, num_frames + 1):
            dynFocalLength.append('x%i' % (frame + offset))
            dynFocalLength.append(' %.7f ' %
                                  tde4.getCameraFocalLength(cam, frame))
        focalLenghtStr = "".join(dynFocalLength)
        nukeNode.append(' tde4_focal_length_cm {{curve ' + focalLenghtStr +
                        ' }}')

# write static focal length else
    else:
        print 'static focal length'
        focalLenghtStr = ' tde4_focal_length_cm %.7f '
        focalLenghtStr = focalLenghtStr % tde4.getCameraFocalLength(cam, 1)
        nukeNode.append(focalLenghtStr)

# write focus distance curve if dynamic
    try:
        if tde4.getCameraFocusMode(cam) == "FOCUS_DYNAMIC":
            print 'dynamic focus distance'
            dynFocusDistance = []
            for frame in range(1, num_frames + 1):
                dynFocusDistance.append('x%i' % (frame + offset))
                dynFocusDistance.append(' %.7f ' %
                                        tde4.getCameraFocus(cam, frame))
            focusDStr = "".join(dynFocusDistance)
            toWrite = ' tde4_custom_focus_distance_cm {{curve ' + focusDStr + '}}'
            nukeNode.append(toWrite)
    except:
        # For 3DE4 Release 1:
        pass
# write static focus distance else
    else:
        print 'static focus distance'
        try:
            cameraFocus = ' tde4_custom_focus_distance_cm %.7f '
            cameraFocus = cameraFocus % tde4.getCameraFocus(cam, 1)
            nukeNode.append(cameraFocus)
        except:
            # For 3DE4 Release 1:
            nukeNode.append(' tde4_custom_focus_distance_cm 100.0 ')


# write camera
    nukeNode.append(' tde4_filmback_width_cm %.7f ' % w_fb_cm)
    nukeNode.append(' tde4_filmback_height_cm %.7f ' % h_fb_cm)
    nukeNode.append(' tde4_lens_center_offset_x_cm %.7f ' % lco_x_cm)
    nukeNode.append(' tde4_lens_center_offset_y_cm %.7f ' % lco_y_cm)
    nukeNode.append(' tde4_pixel_aspect %.7f ' % pxa)
    nukeNode.append(' field_of_view_xa_unit %.7f ' % fov[0])
    nukeNode.append(' field_of_view_ya_unit %.7f ' % fov[2])
    nukeNode.append(' field_of_view_xb_unit %.7f ' % fov[1])
    nukeNode.append(' field_of_view_yb_unit %.7f ' % fov[3])
    nukeNode.append(' filter Simon')

    # dynamic distortion
    try:
        dyndistmode = tde4.getLensDynamicDistortionMode(lens)
    except:
        # For 3DE4 Release 1:
        if tde4.getLensDynamicDistortionFlag(lens) == 1:
            dyndistmode = "DISTORTION_DYNAMIC_FOCAL_LENGTH"
        else:
            dyndistmode = "DISTORTION_STATIC"

    if dyndistmode == "DISTORTION_STATIC":
        print 'static lens distortion'
        for para in (tools.getLDmodelParameterList(model)):
            distStr = ' %.7f ' % tde4.getLensLDAdjustableParameter(
                lens, para, 1, 1)
            nukeNode.append(' ' + tools.nukify_name(para) + distStr)
    else:
        print 'dynamic lens distortion,'
        # dynamic
        for para in (tools.getLDmodelParameterList(model)):

            lensCurve = []
            for frame in range(1, num_frames + 1):
                focal = tde4.getCameraFocalLength(cam, frame)
                focus = tde4.getCameraFocus(cam, frame)
                lensCurve.append('x%i' % (frame + offset))
                frameParam = tde4.getLensLDAdjustableParameter(
                    lens, para, focal, focus)
                lensCurve.append(' %.7f ' % frameParam)
            lensCurveStr = ' {{curve ' + "".join(lensCurve) + ' }}'
            nukeNode.append(' ' + tools.nukify_name(para) + lensCurveStr)

    nameNode = 'name ' + getLDNodeName(cam, direction, offset, index)
    nukeNode.append(nameNode)
    nukeNode.append('}')

    return nukeNode
def exportNukeDewarpNode(cam, offset, nuke_path):
    lens = tde4.getCameraLens(cam)
    model = tde4.getLensLDModel(lens)
    num_frames = tde4.getCameraNoFrames(cam)
    w_fb_cm = tde4.getLensFBackWidth(lens)
    h_fb_cm = tde4.getLensFBackHeight(lens)
    lco_x_cm = tde4.getLensLensCenterX(lens)
    lco_y_cm = tde4.getLensLensCenterY(lens)
    pxa = tde4.getLensPixelAspect(lens)
    # xa,xb,ya,yb in unit coordinates, in this order.
    fov = tde4.getCameraFOV(cam)

    print 'camera: ', tde4.getCameraName(cam)
    print 'offset:', offset
    print 'lens:', tde4.getLensName(lens)
    print 'model: ', model

    f = open(nuke_path, "w")
    try:
        f.write(
            '# Created by 3DEqualizer4 using Export Nuke Distortion Nodes export script\n'
        )
        f.write("LD" + nukify_name(model) + ' {\n')
        f.write(' direction undistort\n')

        # write focal length curve if dynamic
        if tde4.getCameraZoomingFlag(cam):
            print 'dynamic focal length'
            f.write(' tde4_focal_length_cm {{curve ')
            for frame in range(1, num_frames + 1):
                f.write('x%i' % (frame + offset))
                f.write(' %.7f ' % tde4.getCameraFocalLength(cam, frame))
            f.write('}}\n')
# write static focal length else
        else:
            print 'static focal length'
            f.write(' tde4_focal_length_cm %.7f \n' %
                    tde4.getCameraFocalLength(cam, 1))
# write focus distance curve if dynamic
        try:
            if tde4.getCameraFocusMode(cam) == "FOCUS_DYNAMIC":
                print 'dynamic focus distance'
                f.write(' tde4_custom_focus_distance_cm {{curve ')
                for frame in range(1, num_frames + 1):
                    f.write('x%i' % (frame + offset))
                    f.write(' %.7f ' % tde4.getCameraFocus(cam, frame))
                f.write('}}\n')
        except:
            # For 3DE4 Release 1:
            pass
# write static focus distance else
        else:
            print 'static focus distance'
            try:
                f.write(' tde4_custom_focus_distance_cm %.7f \n' %
                        tde4.getCameraFocus(cam, 1))
            except:
                # For 3DE4 Release 1:
                f.write(' tde4_custom_focus_distance_cm 100.0 \n')
# write camera
        f.write(' tde4_filmback_width_cm %.7f \n' % w_fb_cm)
        f.write(' tde4_filmback_height_cm %.7f \n' % h_fb_cm)
        f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lco_x_cm)
        f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lco_y_cm)
        f.write(' tde4_pixel_aspect %.7f \n' % pxa)
        f.write(' field_of_view_xa_unit %.7f \n' % fov[0])
        f.write(' field_of_view_ya_unit %.7f \n' % fov[2])
        f.write(' field_of_view_xb_unit %.7f \n' % fov[1])
        f.write(' field_of_view_yb_unit %.7f \n' % fov[3])

        # write distortion parameters
        #
        # dynamic distortion
        try:
            dyndistmode = tde4.getLensDynamicDistortionMode(lens)
        except:
            # For 3DE4 Release 1:
            if tde4.getLensDynamicDistortionFlag(lens) == 1:
                dyndistmode = "DISTORTION_DYNAMIC_FOCAL_LENGTH"
            else:
                dyndistmode = "DISTORTION_STATIC"

        old_api = True
        try:
            tde4.getLensLDAdjustableParameter(lens, para, 1)
        except:
            old_api = False

        if old_api:
            if dyndistmode == "DISTORTION_DYNAMIC_FOCAL_LENGTH":
                print 'dynamic lens distortion, focal length'
                # dynamic focal length (zoom)
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' {{curve ')
                    for frame in range(1, num_frames + 1):
                        focal = tde4.getCameraFocalLength(cam, frame)
                        f.write('x%i' % (frame + offset))
                        f.write(' %.7f ' % tde4.getLensLDAdjustableParameter(
                            lens, para, focal))
                    f.write('}}\n')

            if dyndistmode == "DISTORTION_DYNAMIC_FOCUS_DISTANCE":
                print 'dynamic lens distortion, focus distance'
                # dynamic focus distance
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' {{curve ')
                    for frame in range(1, num_frames + 1):
                        # Older Releases do not have Focus-methods.
                        try:
                            focus = tde4.getCameraFocus(cam, frame)
                        except:
                            focus = 100.0
                        f.write('x%i' % (frame + offset))
                        f.write(' %.7f ' % tde4.getLensLDAdjustableParameter(
                            lens, para, focus))
                    f.write('}}\n')

# static distortion
            if dyndistmode == "DISTORTION_STATIC":
                print 'static lens distortion'
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' %.7f \n' %
                            tde4.getLensLDAdjustableParameter(lens, para, 1))
        else:
            # new API
            if dyndistmode == "DISTORTION_STATIC":
                print 'static lens distortion'
                for para in (getLDmodelParameterList(model)):
                    f.write(
                        ' ' + nukify_name(para) + ' %.7f \n' %
                        tde4.getLensLDAdjustableParameter(lens, para, 1, 1))
            else:
                print 'dynamic lens distortion,'
                # dynamic
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' {{curve ')
                    for frame in range(1, num_frames + 1):
                        focal = tde4.getCameraFocalLength(cam, frame)
                        focus = tde4.getCameraFocus(cam, frame)
                        f.write('x%i' % (frame + offset))
                        f.write(' %.7f ' % tde4.getLensLDAdjustableParameter(
                            lens, para, focal, focus))
                    f.write('}}\n')

        f.write(' name LD_3DE4_' + decode_entities(tde4.getCameraName(cam)) +
                '\n')
        f.write('}\n')

    finally:
        f.close()
예제 #11
0
def main():
    campg = None
    pgl = tde4.getPGroupList()
    for pg in pgl:
        if tde4.getPGroupType(pg) == "CAMERA": campg = pg
    if campg == None:
        tde4.postQuestionRequester("Export Maya...",
                                   "Error, there is no camera point group.",
                                   "Ok")

    #
    # open requester...

    try:
        req = _export_requester_maya
    except (ValueError, NameError, TypeError):
        _export_requester_maya = tde4.createCustomRequester()
        req = _export_requester_maya
        tde4.addFileWidget(req, "file_browser", "Exportfile...", "*.mel")
        tde4.addTextFieldWidget(req, "startframe_field", "Startframe", "1")
        # tde4.addOptionMenuWidget(req,"mode_menu","Orientation","Y-Up", "Z-Up")
        tde4.addToggleWidget(req, "hide_ref_frames", "Hide Reference Frames",
                             0)

    cam = tde4.getCurrentCamera()
    offset = tde4.getCameraFrameOffset(cam)
    tde4.setWidgetValue(req, "startframe_field", str(offset))

    # ret	= tde4.postCustomRequester(req,"Export Maya (MEL-Script)...",600,0,"Ok","Cancel")
    ret = 1

    if ret == 1:
        # yup	= tde4.getWidgetValue(req,"mode_menu")
        # if yup==2: yup = 0
        yup = 1
        # path	= tde4.getWidgetValue(req,"file_browser")
        path = get_mel_filename()['path']
        # frame0	= float(tde4.getWidgetValue(req,"startframe_field"))
        # frame0	-= 1
        framerange = get_frame_range()
        playbackoptions = 'playbackOptions -min {0} -max {1};'
        playbackoptions = playbackoptions.format(framerange['first'],
                                                 framerange['last'])
        frame0 = framerange['first'] - 1

        hide_ref = tde4.getWidgetValue(req, "hide_ref_frames")
        if path != None:
            if not path.endswith('.mel'): path = path + '.mel'
            f = open(path, "w")
            if not f.closed:

                #
                # write some comments...

                f.write("//\n")
                f.write("// Maya/MEL export data written by %s\n" %
                        tde4.get3DEVersion())
                f.write("//\n")
                f.write(
                    "// All lengths are in centimeter, all angles are in degree.\n"
                )
                f.write("//\n\n")

                #
                # write scene group...
                groupname = """// create scene group...
string $sceneGroupName = `group -em -name "mm_{name}"`;
"""

                # f.write("// create scene group...\n")
                # f.write("string $sceneGroupName = `group -em -name \"Scene\"`;\n")
                groupname = groupname.format(
                    name=get_mel_filename()['filename'][:-4])
                f.write(groupname)

                #
                # write cameras...

                cl = tde4.getCameraList()
                index = 1
                for cam in cl:
                    camType = tde4.getCameraType(cam)
                    noframes = tde4.getCameraNoFrames(cam)
                    lens = tde4.getCameraLens(cam)
                    if lens != None:
                        name = validName(tde4.getCameraName(cam))
                        cam_name = 'cam_mm_' + name
                        # name		= "%s_%s_1"%(name,index)
                        # name		= "%s_%s"%(name,index)
                        name = cam_name
                        index += 1
                        fback_w = tde4.getLensFBackWidth(lens)
                        fback_h = tde4.getLensFBackHeight(lens)
                        p_aspect = tde4.getLensPixelAspect(lens)
                        focal = tde4.getCameraFocalLength(cam, 1)
                        lco_x = tde4.getLensLensCenterX(lens)
                        lco_y = tde4.getLensLensCenterY(lens)

                        # convert filmback to inch...
                        fback_w = fback_w / 2.54
                        fback_h = fback_h / 2.54
                        lco_x = -lco_x / 2.54
                        lco_y = -lco_y / 2.54

                        # convert focal length to mm...
                        focal = focal * 10.0

                        # create camera...
                        f.write("\n")
                        f.write("// create camera %s...\n" % name)
                        f.write(
                            "string $cameraNodes[] = `camera -name \"%s\" -hfa %.15f  -vfa %.15f -fl %.15f -ncp 0.01 -fcp 10000 -shutterAngle 180 -ff \"overscan\"`;\n"
                            % (name, fback_w, fback_h, focal))
                        f.write("string $cameraTransform = $cameraNodes[0];\n")
                        f.write("string $cameraShape = $cameraNodes[1];\n")
                        f.write(
                            "xform -zeroTransformPivots -rotateOrder zxy $cameraTransform;\n"
                        )
                        f.write(
                            "setAttr ($cameraShape+\".horizontalFilmOffset\") %.15f;\n"
                            % lco_x)
                        f.write(
                            "setAttr ($cameraShape+\".verticalFilmOffset\") %.15f;\n"
                            % lco_y)
                        f.write("setAttr ($cameraShape+\".renderable\") 1;\n")
                        p3d = tde4.getPGroupPosition3D(campg, cam, 1)
                        p3d = convertZup(p3d, yup)
                        f.write(
                            "xform -translation %.15f %.15f %.15f $cameraTransform;\n"
                            % (p3d[0], p3d[1], p3d[2]))
                        r3d = tde4.getPGroupRotation3D(campg, cam, 1)
                        rot = convertToAngles(r3d)
                        f.write(
                            "xform -rotation %.15f %.15f %.15f $cameraTransform;\n"
                            % rot)
                        f.write("xform -scale 1 1 1 $cameraTransform;\n")
                        """add pipeline attributes to camerashape"""
                        # attribs = add_pipeline_attribs() ### OBSOLETE WAY
                        attribs = add_pipeline_parms()
                        f.write(attribs)

                        # image plane...
                        f.write("\n\n\n\n// create image plane...\n")
                        f.write(
                            "string $imagePlane = `createNode imagePlane`;\n")
                        f.write(
                            "cameraImagePlaneUpdate ($cameraShape, $imagePlane);\n"
                        )
                        f.write(
                            "setAttr ($imagePlane + \".offsetX\") %.15f;\n" %
                            lco_x)
                        f.write(
                            "setAttr ($imagePlane + \".offsetY\") %.15f;\n" %
                            lco_y)

                        if camType == "SEQUENCE":
                            f.write(
                                "setAttr ($imagePlane+\".useFrameExtension\") 1;\n"
                            )
                        else:
                            f.write(
                                "setAttr ($imagePlane+\".useFrameExtension\") 0;\n"
                            )

                        f.write(
                            "expression -n \"frame_ext_expression\" -s ($imagePlane+\".frameExtension=frame\");\n"
                        )
                        path = tde4.getCameraPath(cam)
                        sattr = tde4.getCameraSequenceAttr(cam)
                        path = prepareImagePath(path, sattr[0])
                        f.write(
                            "setAttr ($imagePlane + \".imageName\") -type \"string\" \"%s\";\n"
                            % (path))
                        f.write("setAttr ($imagePlane + \".fit\") 4;\n")
                        f.write(
                            "setAttr ($imagePlane + \".displayOnlyIfCurrent\") 1;\n"
                        )
                        f.write(
                            "setAttr ($imagePlane  + \".depth\") (9000/2);\n")

                        # parent camera to scene group...
                        f.write("\n")
                        f.write("// parent camera to scene group...\n")
                        f.write("parent $cameraTransform $sceneGroupName;\n")

                        if camType == "REF_FRAME" and hide_ref:
                            f.write(
                                "setAttr ($cameraTransform +\".visibility\") 0;\n"
                            )

                        # animate camera...
                        if camType != "REF_FRAME":
                            f.write("\n")
                            f.write("// animating camera %s...\n" % name)
                            f.write(playbackoptions)
                            # f.write("playbackOptions -min %d -max %d;\n"%(1+frame0,noframes+frame0))
                            f.write("\n\n")

                        frame = 1
                        while frame <= noframes:
                            # rot/pos...
                            p3d = tde4.getPGroupPosition3D(campg, cam, frame)
                            p3d = convertZup(p3d, yup)
                            r3d = tde4.getPGroupRotation3D(campg, cam, frame)
                            rot = convertToAngles(r3d)
                            if frame > 1:
                                rot = [
                                    angleMod360(rot0[0], rot[0]),
                                    angleMod360(rot0[1], rot[1]),
                                    angleMod360(rot0[2], rot[2])
                                ]
                            rot0 = rot
                            f.write(
                                "setKeyframe -at translateX -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, p3d[0]))
                            f.write(
                                "setKeyframe -at translateY -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, p3d[1]))
                            f.write(
                                "setKeyframe -at translateZ -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, p3d[2]))
                            f.write(
                                "setKeyframe -at rotateX -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, rot[0]))
                            f.write(
                                "setKeyframe -at rotateY -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, rot[1]))
                            f.write(
                                "setKeyframe -at rotateZ -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, rot[2]))

                            # focal length...
                            focal = tde4.getCameraFocalLength(cam, frame)
                            focal = focal * 10.0
                            f.write(
                                "setKeyframe -at focalLength -t %d -v %.15f $cameraShape;\n"
                                % (frame + frame0, focal))

                            frame += 1

                #
                # write camera point group...

                f.write("\n")
                f.write("// create camera point group...\n")
                name = "cameraPGroup_%s_1" % validName(
                    tde4.getPGroupName(campg))
                f.write(
                    "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                    % name)
                # f.write("$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n")
                f.write("\n")

                # write points...
                l = tde4.getPointList(campg)
                for p in l:
                    if tde4.isPointCalculated3D(campg, p):
                        name = tde4.getPointName(campg, p)
                        name = "p%s" % validName(name)
                        p3d = tde4.getPointCalcPosition3D(campg, p)
                        p3d = convertZup(p3d, yup)
                        f.write("\n")
                        f.write("// create point %s...\n" % name)
                        f.write(
                            "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                            % name)
                        f.write("$locator = (\"|\" + $locator);\n")
                        f.write("xform -t %.15f %.15f %.15f $locator;\n" %
                                (p3d[0], p3d[1], p3d[2]))
                        f.write("parent $locator $pointGroupName;\n")

                f.write("\n")
                f.write(
                    "xform -zeroTransformPivots -rotateOrder zxy -scale 1.000000 1.000000 1.000000 $pointGroupName;\n"
                )
                f.write("\n")

                #
                # write object/mocap point groups...

                camera = tde4.getCurrentCamera()
                noframes = tde4.getCameraNoFrames(camera)
                pgl = tde4.getPGroupList()
                index = 1
                for pg in pgl:
                    if tde4.getPGroupType(pg) == "OBJECT" and camera != None:
                        f.write("\n")
                        f.write("// create object point group...\n")
                        pgname = "objectPGroup_%s_%d_1" % (validName(
                            tde4.getPGroupName(pg)), index)
                        index += 1
                        f.write(
                            "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                            % pgname)
                        f.write(
                            "$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n"
                        )

                        # write points...
                        l = tde4.getPointList(pg)
                        for p in l:
                            if tde4.isPointCalculated3D(pg, p):
                                name = tde4.getPointName(pg, p)
                                name = "p%s" % validName(name)
                                p3d = tde4.getPointCalcPosition3D(pg, p)
                                p3d = convertZup(p3d, yup)
                                f.write("\n")
                                f.write("// create point %s...\n" % name)
                                f.write(
                                    "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                                    % name)
                                f.write("$locator = (\"|\" + $locator);\n")
                                f.write(
                                    "xform -t %.15f %.15f %.15f $locator;\n" %
                                    (p3d[0], p3d[1], p3d[2]))
                                f.write("parent $locator $pointGroupName;\n")

                        f.write("\n")
                        scale = tde4.getPGroupScale3D(pg)
                        f.write(
                            "xform -zeroTransformPivots -rotateOrder zxy -scale %.15f %.15f %.15f $pointGroupName;\n"
                            % (scale, scale, scale))

                        # animate object point group...
                        f.write("\n")
                        f.write("// animating point group %s...\n" % pgname)
                        frame = 1
                        while frame <= noframes:
                            # rot/pos...
                            p3d = tde4.getPGroupPosition3D(pg, camera, frame)
                            p3d = convertZup(p3d, yup)
                            r3d = tde4.getPGroupRotation3D(pg, camera, frame)
                            rot = convertToAngles(r3d)
                            if frame > 1:
                                rot = [
                                    angleMod360(rot0[0], rot[0]),
                                    angleMod360(rot0[1], rot[1]),
                                    angleMod360(rot0[2], rot[2])
                                ]
                            rot0 = rot
                            f.write(
                                "setKeyframe -at translateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[0]))
                            f.write(
                                "setKeyframe -at translateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[1]))
                            f.write(
                                "setKeyframe -at translateZ -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[2]))
                            f.write(
                                "setKeyframe -at rotateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[0]))
                            f.write(
                                "setKeyframe -at rotateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[1]))
                            f.write(
                                "setKeyframe -at rotateZ -t %d -v %.15f $pointGroupName;\n"
                                % (frame + frame0, rot[2]))

                            frame += 1

                    # mocap point groups...
                    if tde4.getPGroupType(pg) == "MOCAP" and camera != None:
                        f.write("\n")
                        f.write("// create mocap point group...\n")
                        pgname = "objectPGroup_%s_%d_1" % (validName(
                            tde4.getPGroupName(pg)), index)
                        index += 1
                        f.write(
                            "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                            % pgname)
                        f.write(
                            "$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n"
                        )

                        # write points...
                        l = tde4.getPointList(pg)
                        for p in l:
                            if tde4.isPointCalculated3D(pg, p):
                                name = tde4.getPointName(pg, p)
                                name = "p%s" % validName(name)
                                p3d = tde4.getPointMoCapCalcPosition3D(
                                    pg, p, camera, 1)
                                p3d = convertZup(p3d, yup)
                                f.write("\n")
                                f.write("// create point %s...\n" % name)
                                f.write(
                                    "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                                    % name)
                                f.write("$locator = (\"|\" + $locator);\n")
                                f.write(
                                    "xform -t %.15f %.15f %.15f $locator;\n" %
                                    (p3d[0], p3d[1], p3d[2]))
                                for frame in range(1, noframes + 1):
                                    p3d = tde4.getPointMoCapCalcPosition3D(
                                        pg, p, camera, frame)
                                    p3d = convertZup(p3d, yup)
                                    f.write(
                                        "setKeyframe -at translateX -t %d -v %.15f $locator; "
                                        % (frame + frame0, p3d[0]))
                                    f.write(
                                        "setKeyframe -at translateY -t %d -v %.15f $locator; "
                                        % (frame + frame0, p3d[1]))
                                    f.write(
                                        "setKeyframe -at translateZ -t %d -v %.15f $locator; "
                                        % (frame + frame0, p3d[2]))
                                f.write("parent $locator $pointGroupName;\n")

                        f.write("\n")
                        scale = tde4.getPGroupScale3D(pg)
                        f.write(
                            "xform -zeroTransformPivots -rotateOrder zxy -scale %.15f %.15f %.15f $pointGroupName;\n"
                            % (scale, scale, scale))

                        # animate mocap point group...
                        f.write("\n")
                        f.write("// animating point group %s...\n" % pgname)
                        frame = 1
                        while frame <= noframes:
                            # rot/pos...
                            p3d = tde4.getPGroupPosition3D(pg, camera, frame)
                            p3d = convertZup(p3d, yup)
                            r3d = tde4.getPGroupRotation3D(pg, camera, frame)
                            rot = convertToAngles(r3d)
                            if frame > 1:
                                rot = [
                                    angleMod360(rot0[0], rot[0]),
                                    angleMod360(rot0[1], rot[1]),
                                    angleMod360(rot0[2], rot[2])
                                ]
                            rot0 = rot
                            f.write(
                                "setKeyframe -at translateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[0]))
                            f.write(
                                "setKeyframe -at translateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[1]))
                            f.write(
                                "setKeyframe -at translateZ -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[2]))
                            f.write(
                                "setKeyframe -at rotateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[0]))
                            f.write(
                                "setKeyframe -at rotateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[1]))
                            f.write(
                                "setKeyframe -at rotateZ -t %d -v %.15f $pointGroupName;\n"
                                % (frame + frame0, rot[2]))

                            frame += 1

                #
                # global (scene node) transformation...

                p3d = tde4.getScenePosition3D()
                p3d = convertZup(p3d, yup)
                r3d = tde4.getSceneRotation3D()
                rot = convertToAngles(r3d)
                s = tde4.getSceneScale3D()
                f.write(
                    "xform -zeroTransformPivots -rotateOrder zxy -translation %.15f %.15f %.15f -scale %.15f %.15f %.15f -rotation %.15f %.15f %.15f $sceneGroupName;\n\n"
                    %
                    (p3d[0], p3d[1], p3d[2], s, s, s, rot[0], rot[1], rot[2]))

                f.write("\n")
                f.close()
                # tde4.postQuestionRequester("Export Maya...","Project successfully exported.","Ok")
                print '--> successfully exported Maya Mel'
            else:
                tde4.postQuestionRequester("Export Maya...",
                                           "Error, couldn't open file.", "Ok")

    return get_mel_filename()['path']
예제 #12
0
 def frame_count(self):
     return tde4.getCameraNoFrames(self._cam_id)
예제 #13
0
def getDistortionBoundingBox(camera, lco_x, lco_y):
    # We genererate a number of samples around the image in normalized coordinates.
    # These samples are later unwarped, and the unwarped points
    # will be used to create a bounding box. In general, it is *not* sufficient to
    # undistort only the corners, because distortion might be moustache-shaped.
    # This is our list of samples:
    warped = []
    for i in range(10):
        warped.append([i / 10.0,0.0])
        warped.append([(i + 1) / 10.0,1.0])
        warped.append([0.0,i / 10.0])
        warped.append([1.0,(i + 1) / 10.0])

    # The lens center is by definition the fixed point of the distortion mapping.
    elc = [0.5 + lco_x,0.5 + lco_y]

    # Image size
    w_px = tde4.getCameraImageWidth(camera)
    h_px = tde4.getCameraImageHeight(camera)

    # The bounding boxes for non-symmetrized and symmetrized cased.
    bb_nonsymm = bbdld_bounding_box()
    bb_symm = bbdld_bounding_box()

    # Run through the frames of this camera
    n_frames = tde4.getCameraNoFrames(camera)
    for i_frame in range(n_frames):
        # 3DE4 counts from 1.
        frame = i_frame + 1

        # Now we undistort all edge points for the given
        # camera and frame and extend the bounding boxes.
        for p in warped:
            p_unwarped = tde4.removeDistortion2D(camera,frame,p)
            # Accumulate bounding boxes
            bb_nonsymm.extend(p_unwarped[0],p_unwarped[1])
            bb_symm.extend_symm(p_unwarped[0],p_unwarped[1],elc[0],elc[1])

    # Scale to pixel coordinates and extend to pixel-aligned values
    bb_nonsymm.scale(w_px,h_px)
    bb_nonsymm.extend_to_integer()

    # Image width and height for the non-symmetrized case
    w_nonsymm_px = bb_nonsymm.dx()
    h_nonsymm_px = bb_nonsymm.dy()

    # Lower left corner for the symmetrized case. This tells us
    # how the undistorted image is related to the distorted image.
    x_nonsymm_px = bb_nonsymm.x_min()
    y_nonsymm_px = bb_nonsymm.y_min()

    # Scale to pixel coordinates and extend to pixel-aligned values
    bb_symm.scale(w_px,h_px)
    bb_symm.extend_to_integer()

    # Image width and height for the symmetrized case
    w_symm_px = bb_symm.dx()
    h_symm_px = bb_symm.dy()

    # Lower left corner for the symmetrized case. This tells us
    # how the undistorted image is related to the distorted image.
    x_symm_px = bb_symm.x_min()
    y_symm_px = bb_symm.y_min()

    return x_symm_px,y_symm_px,w_symm_px,h_symm_px
예제 #14
0
def exportDistortionParameters(tde4, cam, lens, f, offset):
    """Add undistort attributes to the Maya camera"""

    model   = tde4.getLensLDModel(lens)

    f.write('addAttr -longName "tde4_lens_model" -dataType "string" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_focal_length_cm" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_filmback_width_cm" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_filmback_height_cm" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_lens_center_offset_x_cm" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_lens_center_offset_y_cm" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_pixel_aspect" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_bbox_scale_factor" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')
    f.write('addAttr -longName "tde4_animated_distortion" -attributeType "short" -storable 1 -readable 1 -writable 1 $cameraShape;\n')

    for para in (getLDmodelParameterList(model)):
        f.write('addAttr -longName "'+ getLDmodelNukeParameterName(para) + '" -attributeType "double" -storable 1 -readable 1 -writable 1 $cameraShape;\n')

    lensModel = getLDmodelNukeNodeName(model)
    f.write('setAttr ($cameraShape+".tde4_lens_model") -type "string" "%s";\n' % lensModel)

    numberFrames = tde4.getCameraNoFrames(cam)
    if tde4.getCameraZoomingFlag(cam):
        # dynamic focal length
        for frame in range(1,numberFrames+1):
            f.write('setKeyframe -at "tde4_focal_length_cm" -t %d -v %.7f $cameraTransform; '%(frame+offset,tde4.getCameraFocalLength(cam,frame)))
    else:
        # static focal length
        f.write("setAttr ($cameraShape+\".tde4_focal_length_cm\") %7f;\n" % tde4.getCameraFocalLength(cam,1))

    fbw = tde4.getLensFBackWidth(lens)
    fbh = tde4.getLensFBackHeight(lens)
    lcx = tde4.getLensLensCenterX(lens)
    lcy = tde4.getLensLensCenterY(lens)
    pxa = tde4.getLensPixelAspect(lens)

    f.write('setAttr ($cameraShape+\".tde4_filmback_width_cm\") %.7f;\n'%fbw)
    f.write('setAttr ($cameraShape+\".tde4_filmback_height_cm\") %.7f;\n'%fbh)
    f.write('setAttr ($cameraShape+\".tde4_lens_center_offset_x_cm\") %.7f;\n'%lcx)
    f.write('setAttr ($cameraShape+\".tde4_lens_center_offset_y_cm\") %.7f;\n'%lcy)
    f.write('setAttr ($cameraShape+\".tde4_pixel_aspect\") %.7f;\n'%pxa)

    # compute the bounding box scale factor (animation taken into account)
    bbox_x, bbox_y, bbox_w, bbox_h = getDistortionBoundingBox(cam, lcx, lcy)
    w_px = tde4.getCameraImageWidth(cam)
    h_px = tde4.getCameraImageHeight(cam)
    # print "%dx%d => %dx%d" % (w_px, h_px, bbox_w, bbox_h)
    distortion_scale_x = float(bbox_w+2) / float(w_px)
    distortion_scale_y = float(bbox_h+2) / float(h_px)
    # print "distortion scale factor x: %f" % distortion_scale_x
    # print "distortion scale factor y: %f" % distortion_scale_y
    distortion_scale = max(distortion_scale_x, distortion_scale_y)
    f.write('setAttr ($cameraShape+\".tde4_bbox_scale_factor\") %.7f;\n' % distortion_scale)

    if tde4.getLensDynamicDistortionFlag(lens):
        # dynamic distortion
        for para in (getLDmodelParameterList(model)):
            for frame in range(1,numberFrames):
                focal = tde4.getCameraFocalLength(cam,frame)
                f.write('setKeyframe -at "%s" -t %d -v %.7f $cameraTransform; '%(getLDmodelNukeParameterName(para),frame+offset,tde4.getLensLDAdjustableParameter(lens, para, focal)))
        f.write('setAttr ($cameraShape+\".tde4_animated_distortion\") 1;\n')
    else:
        # static distortion
        for para in (getLDmodelParameterList(model)):
            f.write('setAttr ($cameraShape+\".'+getLDmodelNukeParameterName(para)+'\") %.7f;\n' % tde4.getLensLDAdjustableParameter(lens, para, 1))
        f.write('setAttr ($cameraShape+\".tde4_animated_distortion\") 0;\n')
예제 #15
0
def apply_to_camera(pgroup_id, cam_id, lens_id, options, file_data):
    """
    Replace the camera and lens with the given options.
    """
    camera_data = file_data.get('data', dict())

    # Set image file path
    file_start_frame = camera_data.get('start_frame')
    file_end_frame = camera_data.get('end_frame')
    plate_load = options.get('plate_load')
    plate_path = options.get('plate_path')
    if (plate_load and file_start_frame is not None
            and file_end_frame is not None and plate_path):
        # Set plate frame range
        file_start = int(file_start_frame)
        file_end = int(file_end_frame)
        tde4.setCameraSequenceAttr(cam_id, file_start, file_end, 1)
        if SUPPORT_CAMERA_FRAME_OFFSET is True:
            tde4.setCameraFrameOffset(cam_id, file_start)

        # Note: It is important to set the file path after the sequence
        # attributes, otherwise the camera will not show the image.
        plate_path = os.path.normpath(plate_path)
        tde4.setCameraPath(cam_id, plate_path)

        if SUPPORT_CAMERA_PLAYBACK_RANGE is True:
            playback_start = 1  # 3DE always starts at frame 1.
            playback_end = tde4.getCameraNoFrames(cam_id)
            tde4.setCameraPlaybackRange(cam_id, playback_start, playback_end)

    # Set pixel aspect ratio
    par = options.get('par')
    if par:
        par = float(par)
        tde4.setLensPixelAspect(lens_id, par)

    # Set Camera name
    set_name = options.get('set_cam_name')
    if set_name:
        cam_name = camera_data.get('name', '')
        if cam_name:
            tde4.setCameraName(cam_id, cam_name)
        lens_name = cam_name + '_lens'
        if lens_name:
            tde4.setLensName(lens_id, lens_name)

    attr_data = camera_data.get('attr', dict())

    # Set film back
    #
    # Note: These values cannot be animated in 3DE, even if in Maya
    # they were animated. We only take the first value in the list and
    # assume the film back value is constant.
    fbk_size = options.get('fbk_size')
    filmBackWidthSamples = attr_data.get('filmBackWidth')
    filmBackHeightSamples = attr_data.get('filmBackHeight')
    if fbk_size and filmBackWidthSamples and filmBackHeightSamples:
        value_x = filmBackWidthSamples[0][-1] * MILLIMETERS_TO_CENTIMETRES
        value_y = filmBackHeightSamples[0][-1] * MILLIMETERS_TO_CENTIMETRES
        tde4.setLensFBackWidth(lens_id, value_x)
        tde4.setLensFBackHeight(lens_id, value_y)

    fbk_offset = options.get('fbk_offset')
    filmBackOffsetXSamples = attr_data.get('filmBackOffsetX')
    filmBackOffsetYSamples = attr_data.get('filmBackOffsetY')
    if fbk_offset and filmBackOffsetXSamples and filmBackOffsetYSamples:
        value_x = filmBackOffsetXSamples[0][-1] * MILLIMETERS_TO_CENTIMETRES
        value_y = filmBackOffsetYSamples[0][-1] * MILLIMETERS_TO_CENTIMETRES
        tde4.setLensLensCenterX(lens_id, value_x)
        tde4.setLensLensCenterY(lens_id, value_y)

    # Set focal length
    file_start_frame = camera_data.get('start_frame')
    file_end_frame = camera_data.get('end_frame')
    chosen_start_frame = options.get('start_frame')
    chosen_end_frame = options.get('end_frame')
    fl = options.get('fl')
    focalLengthSamples = attr_data.get('focalLength')
    if (fl and focalLengthSamples and isinstance(file_start_frame, INT_TYPES)
            and isinstance(file_end_frame, INT_TYPES)
            and isinstance(chosen_start_frame, TEXT_TYPE)
            and isinstance(chosen_end_frame, TEXT_TYPE)):
        file_start = int(file_start_frame)
        file_end = int(file_end_frame)
        chosen_start = int(chosen_start_frame)
        chosen_end = int(chosen_end_frame)
        focal_length_set = _set_camera_focal_length(
            cam_id,
            lens_id,
            focalLengthSamples,
            file_start,
            file_end,
            chosen_start,
            chosen_end,
        )

    # Set translation and rotation
    file_start_frame = camera_data.get('start_frame')
    file_end_frame = camera_data.get('end_frame')
    chosen_start_frame = options.get('start_frame')
    chosen_end_frame = options.get('end_frame')
    if (isinstance(file_start_frame, INT_TYPES)
            and isinstance(file_end_frame, INT_TYPES)
            and isinstance(chosen_start_frame, TEXT_TYPE)
            and isinstance(chosen_end_frame, TEXT_TYPE)):
        file_start = int(file_start_frame)
        file_end = int(file_end_frame)
        chosen_start = int(chosen_start_frame)
        chosen_end = int(chosen_end_frame)

        # Set Translation
        translate_set = False
        translate = options.get('translate')
        tx_samples = attr_data.get('translateX')
        ty_samples = attr_data.get('translateY')
        tz_samples = attr_data.get('translateZ')
        if translate and tx_samples and ty_samples and tz_samples:
            translate_set = _set_camera_translation(pgroup_id, cam_id,
                                                    tx_samples, ty_samples,
                                                    tz_samples, file_start,
                                                    file_end, chosen_start,
                                                    chosen_end)

        # Set Rotation
        rotate_set = False
        rotate = options.get('rotate')
        rx_samples = attr_data.get('rotateX')
        ry_samples = attr_data.get('rotateY')
        rz_samples = attr_data.get('rotateZ')
        if rotate and rx_samples and ry_samples and rz_samples:
            rotate_set = _set_camera_rotation(pgroup_id, cam_id, rx_samples,
                                              ry_samples, rz_samples,
                                              file_start, file_end,
                                              chosen_start, chosen_end)

        if translate_set or rotate_set:
            tde4.setPGroupPostfilterMode(pgroup_id, 'POSTFILTER_OFF')
            tde4.filterPGroup(pgroup_id, cam_id)
    return
def exportNukeDewarpNode(id_cam,offset,nuke_path):
	id_lens 	= tde4.getCameraLens(id_cam)
	model 	= tde4.getLensLDModel(id_lens)
	num_frames 	= tde4.getCameraNoFrames(id_cam)
	w_fb_cm = tde4.getLensFBackWidth(id_lens)
	h_fb_cm = tde4.getLensFBackHeight(id_lens)
	lco_x_cm = tde4.getLensLensCenterX(id_lens)
	lco_y_cm = tde4.getLensLensCenterY(id_lens)
	pxa = tde4.getLensPixelAspect(id_lens)
# xa,xb,ya,yb in unit coordinates, in this order.
	xa_unit,xb_unit,ya_unit,yb_unit = tde4.getCameraFOV(id_cam)
		
	f = open(nuke_path,"w")
	try:
		f.write('# Created by 3DEqualizer4 using Export Nuke Distortion Nodes export script\n')
		f.write("LD" + nukify_name(model) + ' {\n')
		f.write(' direction undistort\n')
################################
# focal length                 #
################################
		if is_focal_length_dynamic(id_cam):
# write focal length curve if dynamic
#			print 'dynamic focal length'
			f.write(' tde4_focal_length_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focal = tde4.getCameraFocalLength(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focal))
			f.write('}}\n')
		else:
# write static focal length otherwise
#			print 'static focal length'
			f.write(' tde4_focal_length_cm %.7f \n' % tde4.getCameraFocalLength(id_cam,1))
################################
# focus distance               #
################################
# For Release 1 this function return False, so no problem with getCameraFocus.
		if is_focus_distance_dynamic(id_cam):
# write focus distance curve if dynamic
#			print 'dynamic focus distance'
			f.write(' tde4_custom_focus_distance_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focus = tde4.getCameraFocus(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focus))
			f.write('}}\n')
		else:
			try:
# write static focus distance otherwise
				f.write(' tde4_custom_focus_distance_cm %.7f \n' % tde4.getCameraFocus(id_cam,1))
			except:
# For Release 1 we simply write out the default value to Nuke.
				f.write(' tde4_custom_focus_distance_cm 100.0 \n')
################################
# built-in parameters          #
################################
# the remaining five built-in parameters
		f.write(' tde4_filmback_width_cm %.7f \n' % w_fb_cm)
		f.write(' tde4_filmback_height_cm %.7f \n' % h_fb_cm)
		f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lco_x_cm)
		f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lco_y_cm)
		f.write(' tde4_pixel_aspect %.7f \n' % pxa)
################################
# field-of-view                #
################################
		f.write(' field_of_view_xa_unit %.7f \n' % xa_unit)
		f.write(' field_of_view_xb_unit %.7f \n' % xb_unit)
		f.write(' field_of_view_ya_unit %.7f \n' % ya_unit)
		f.write(' field_of_view_yb_unit %.7f \n' % yb_unit)
		
# write distortion parameters
#
# dynamic distortion
		dyndistmode = get_dynamic_distortion_mode(id_lens)

		old_api = True
		try:
			for para in getLDmodelParameterList(model):
				tde4.getLensLDAdjustableParameter(id_lens, para, 1)
				break
		except:
			old_api = False

		if old_api:
# dynamic focal length (zoom)
			if dyndistmode=="DISTORTION_DYNAMIC_FOCAL_LENGTH":
#				print 'dynamic lens distortion, focal length'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						f.write ('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal)))
					f.write('}}\n')
# dynamic focus distance
			if dyndistmode=="DISTORTION_DYNAMIC_FOCUS_DISTANCE":
#				print 'dynamic lens distortion, focus distance'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Older Releases do not have Focus-methods.
						try:
# Internally, frames start at 1.
							focus = tde4.getCameraFocus(id_cam,frame + 1)
						except:
							focus = 100.0
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focus)))
					f.write('}}\n')
# static distortion
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1))
		else:
# new API
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1,1))
			else:
#				print 'dynamic lens distortion,'
# dynamic
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						focus = tde4.getCameraFocus(id_cam,frame + 1)
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal,focus)))
#						print "%i[3DE4] -> %i[Nuke]" % (frame + tde4.getCameraFrameOffset(id_cam),frame + offset)
					f.write('}}\n')


		
		f.write(' name LD_3DE4_' + decode_entities(tde4.getCameraName(id_cam)) + '\n')
		f.write('}\n')

	finally:	
		f.close()	
def exportNukeDewarpNode(id_cam,offset,nuke_path):
	id_lens 	= tde4.getCameraLens(id_cam)
	model 	= tde4.getLensLDModel(id_lens)
	num_frames 	= tde4.getCameraNoFrames(id_cam)
	w_fb_cm = tde4.getLensFBackWidth(id_lens)
	h_fb_cm = tde4.getLensFBackHeight(id_lens)
	lco_x_cm = tde4.getLensLensCenterX(id_lens)
	lco_y_cm = tde4.getLensLensCenterY(id_lens)
	pxa = tde4.getLensPixelAspect(id_lens)
# xa,xb,ya,yb in unit coordinates, in this order.
	xa_unit,xb_unit,ya_unit,yb_unit = tde4.getCameraFOV(id_cam)
		
	f = open(nuke_path,"w")
	try:
		f.write('# Created by 3DEqualizer4 using Export Nuke Distortion Nodes export script\n')
		f.write("LD" + nukify_name(model) + ' {\n')
		f.write(' direction undistort\n')
################################
# focal length                 #
################################
		if is_focal_length_dynamic(id_cam):
# write focal length curve if dynamic
#			print 'dynamic focal length'
			f.write(' tde4_focal_length_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focal = tde4.getCameraFocalLength(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focal))
			f.write('}}\n')
		else:
# write static focal length otherwise
#			print 'static focal length'
			f.write(' tde4_focal_length_cm %.7f \n' % tde4.getCameraFocalLength(id_cam,1))
################################
# focus distance               #
################################
# For Release 1 this function return False, so no problem with getCameraFocus.
		if is_focus_distance_dynamic(id_cam):
# write focus distance curve if dynamic
#			print 'dynamic focus distance'
			f.write(' tde4_custom_focus_distance_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focus = tde4.getCameraFocus(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focus))
			f.write('}}\n')
		else:
			try:
# write static focus distance otherwise
				f.write(' tde4_custom_focus_distance_cm %.7f \n' % tde4.getCameraFocus(id_cam,1))
			except:
# For Release 1 we simply write out the default value to Nuke.
				f.write(' tde4_custom_focus_distance_cm 100.0 \n')
################################
# built-in parameters          #
################################
# the remaining five built-in parameters
		f.write(' tde4_filmback_width_cm %.7f \n' % w_fb_cm)
		f.write(' tde4_filmback_height_cm %.7f \n' % h_fb_cm)
		f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lco_x_cm)
		f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lco_y_cm)
		f.write(' tde4_pixel_aspect %.7f \n' % pxa)
################################
# field-of-view                #
################################
		f.write(' field_of_view_xa_unit %.7f \n' % xa_unit)
		f.write(' field_of_view_xb_unit %.7f \n' % xb_unit)
		f.write(' field_of_view_ya_unit %.7f \n' % ya_unit)
		f.write(' field_of_view_yb_unit %.7f \n' % yb_unit)
		
# write distortion parameters
#
# dynamic distortion
		dyndistmode = get_dynamic_distortion_mode(id_lens)

		old_api = True
		try:
			for para in getLDmodelParameterList(model):
				tde4.getLensLDAdjustableParameter(id_lens, para, 1)
				break
		except:
			old_api = False

		if old_api:
# dynamic focal length (zoom)
			if dyndistmode=="DISTORTION_DYNAMIC_FOCAL_LENGTH":
#				print 'dynamic lens distortion, focal length'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						f.write ('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal)))
					f.write('}}\n')
# dynamic focus distance
			if dyndistmode=="DISTORTION_DYNAMIC_FOCUS_DISTANCE":
#				print 'dynamic lens distortion, focus distance'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Older Releases do not have Focus-methods.
						try:
# Internally, frames start at 1.
							focus = tde4.getCameraFocus(id_cam,frame + 1)
						except:
							focus = 100.0
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focus)))
					f.write('}}\n')
# static distortion
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1))
		else:
# new API
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1,1))
			else:
#				print 'dynamic lens distortion,'
# dynamic
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						focus = tde4.getCameraFocus(id_cam,frame + 1)
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal,focus)))
#						print "%i[3DE4] -> %i[Nuke]" % (frame + tde4.getCameraFrameOffset(id_cam),frame + offset)
					f.write('}}\n')


		
		f.write(' name LD_3DE4_' + decode_entities(tde4.getCameraName(id_cam)) + '\n')
		f.write('}\n')

	finally:	
		f.close()	
예제 #18
0
def _remove_rs_from_2d_point(point_group, camera, frame, input_2d, depth):
    """
    Correct Rolling Shutter for the given input_2d point data, on frame.

    :param point_group: Camera Point Group for camera.
    :param camera: The camera to use for rolling shutter calculations.
    :param frame: The 2D point's frame number (in internal 3DE frame numbers).
    :param input_2d: Input 2D data.
    :param depth: The content distance to calculate rolling shutter at.

    :return: 2D point with corrected position.
    :rtype: [float, float]
    """
    assert isinstance(input_2d, vl_sdv.vec2d)
    num_frames = tde4.getCameraNoFrames(camera)
    if num_frames == 1:
        return input_2d

    # Static camera and lens values.
    camera_fps = tde4.getCameraFPS(camera)
    camera_fov = tde4.getCameraFOV(camera)
    lens = tde4.getCameraLens(camera)
    fbw = tde4.getLensFBackWidth(lens)
    fbh = tde4.getLensFBackHeight(lens)
    lcox = tde4.getLensLensCenterX(lens)
    lcoy = tde4.getLensLensCenterY(lens)
    rs_time_shift = tde4.getCameraRollingShutterTimeShift(camera)
    rs_value = rs_time_shift * camera_fps

    # Sample at previous frame
    prev_pos = vl_sdv.vec3d(0, 0, 0)
    prev_frame = frame - 1
    if frame > 1:
        prev_pos = _convert_2d_to_3d_point_undistort(
            point_group, camera,
            fbw, fbh, lcox, lcoy,
            camera_fov,
            prev_frame, input_2d, depth)

    # Sample at next frame
    next_pos = vl_sdv.vec3d(0, 0, 0)
    next_frame = frame + 1
    if frame < num_frames:
        next_pos = _convert_2d_to_3d_point_undistort(
            point_group, camera,
            fbw, fbh, lcox, lcoy,
            camera_fov,
            next_frame, input_2d, depth)

    # Sample at current frame
    curr_pos = _convert_2d_to_3d_point_undistort(
        point_group, camera,
        fbw, fbh, lcox, lcoy,
        camera_fov,
        frame, input_2d, depth)

    # Blend previous, next and current frame values based on the
    # position of the 2D point vertical position and the rolling
    # shutter value.
    if frame == 1:
        prev_pos = curr_pos + (curr_pos - next_pos)
    if frame == num_frames:
        next_pos = curr_pos + (curr_pos - prev_pos)
    t = rs_value * (1.0 - input_2d[1])
    curr_pos = _apply_rs_correction(-t, prev_pos, curr_pos, next_pos)

    # Back-projection
    focal = tde4.getCameraFocalLength(camera, frame)
    r3d = vl_sdv.mat3d(tde4.getPGroupRotation3D(point_group, camera, frame))
    p3d = vl_sdv.vec3d(tde4.getPGroupPosition3D(point_group, camera, frame))
    d = r3d.trans() * (curr_pos - p3d)
    p2d = [0, 0]
    p2d[0] = (d[0] * focal / (-d[2] * fbw)) + (lcox / fbw) + 0.5
    p2d[1] = (d[1] * focal / (-d[2] * fbh)) + (lcoy / fbh) + 0.5
    p = tde4.applyDistortion2D(camera, frame, p2d)
    left, right, bottom, top = camera_fov
    p = vl_sdv.vec2d((p[0] * (right - left)) + left,
                     (p[1] * (top - bottom)) + bottom)
    v = (input_2d + (input_2d - p)).list()
    return v
def _generate_v2(point_group,
                 camera,
                 points,
                 start_frame=None,
                 undistort=False):
    """
    Generate the UV file format contents, using JSON format.

    :param point_group: The 3DE Point Group containing 'points'
    :type point_group: str

    :param camera: The 3DE Camera containing 2D 'points' data.
    :type camera: str

    :param points: The list of 3DE Points representing 2D data to
                   save.
    :type points: list of str

    :param start_frame: The frame number to be considered at
                       'first frame'. Defaults to 1001 if
                       set to None.
    :type start_frame: None or int

    :param undistort: Should we apply undistortion to the 2D points
                      data? Yes or no.
    :type undistort: bool

    Each point will store:
    - Point name
    - X, Y position (in UV coordinates, per-frame)
    - Point weight (per-frame)
    - Point Set name
    - Point 'Persistent ID'
    """
    assert isinstance(point_group, basestring)
    assert isinstance(camera, basestring)
    assert isinstance(points, (list, tuple))
    assert start_frame is None or isinstance(start_frame, int)
    assert isinstance(undistort, bool)
    if start_frame is None:
        start_frame = 1001
    data = UV_TRACK_HEADER_VERSION_2.copy()
    cam_num_frames = tde4.getCameraNoFrames(camera)

    if len(points) == 0:
        return ''

    frame0 = int(start_frame)
    frame0 -= 1

    data['num_points'] = len(points)
    data['is_undistorted'] = bool(undistort)

    data['points'] = []
    for point in points:
        point_data = {}

        # Query point information
        name = tde4.getPointName(point_group, point)
        uid = None
        if SUPPORT_PERSISTENT_ID is True:
            uid = tde4.getPointPersistentID(point_group, point)
        point_set = tde4.getPointSet(point_group, point)
        point_set_name = None
        if point_set is not None:
            point_set_name = tde4.getSetName(point_group, point_set)
        point_data['name'] = name
        point_data['id'] = uid
        point_data['set_name'] = point_set_name

        # Write per-frame position data
        frame = 1  # 3DE starts at frame '1' regardless of the 'start frame'.
        point_data['per_frame'] = []
        pos_block = tde4.getPointPosition2DBlock(point_group, point, camera, 1,
                                                 cam_num_frames)
        for pos in pos_block:
            if pos[0] == -1.0 or pos[1] == -1.0:
                # No valid data here.
                frame += 1
                continue

            # Does the 2D point go outside the camera FOV? Is that ok?
            valid_2d = tde4.isPointPos2DValid(point_group, point, camera,
                                              frame)
            if valid_2d != 1:
                # No valid data here.
                frame += 1
                continue

            f = frame + frame0
            if undistort is True:
                pos = tde4.removeDistortion2D(camera, frame, pos)
            weight = 1.0
            if SUPPORT_POINT_WEIGHT_BY_FRAME is True:
                weight = tde4.getPointWeightByFrame(point_group, point, camera,
                                                    frame)
            frame_data = {'frame': f, 'pos': pos, 'weight': weight}
            point_data['per_frame'].append(frame_data)
            frame += 1

        data['points'].append(point_data)

    data_str = json.dumps(data)
    return data_str
예제 #20
0
def _generate_v1(point_group, camera, points,
                 start_frame=None,
                 undistort=False,
                 rs_distance=None):
    """
    Generate the UV file format contents, using a basic ASCII format.

    Each point will store:
    - Point name
    - X, Y position (in UV coordinates, per-frame)
    - Point weight (per-frame)

    :param point_group: The 3DE Point Group containing 'points'
    :type point_group: str

    :param camera: The 3DE Camera containing 2D 'points' data.
    :type camera: str

    :param points: The list of 3DE Points representing 2D data to
                   save.
    :type points: list of str

    :param start_frame: The frame number to be considered at
                       'first frame'. Defaults to 1001 if
                       set to None.
    :type start_frame: None or int

    :param undistort: Should we apply undistortion to the 2D points
                      data? Yes or no.
    :type undistort: bool

    :param rs_distance: If not None, correct rolling shutter effects on
        the 2D points at the content distance rs_distance.
    :type rs_distance: None or float

    :returns: A ASCII format string, with the UV Track data in it.
    :rtype: str
    """
    assert isinstance(point_group, TEXT_TYPE)
    assert isinstance(camera, TEXT_TYPE)
    assert isinstance(points, (list, tuple))
    assert start_frame is None or isinstance(start_frame, int)
    assert isinstance(undistort, bool)
    assert rs_distance is None or isinstance(rs_distance, float)
    if start_frame is None:
        start_frame = 1001
    data_str = ''

    cam_num_frames = tde4.getCameraNoFrames(camera)
    camera_fov = tde4.getCameraFOV(camera)

    if len(points) == 0:
        return data_str

    frame0 = int(start_frame)
    frame0 -= 1

    data_str += '{0:d}\n'.format(len(points))

    for point in points:
        name = tde4.getPointName(point_group, point)
        c2d = tde4.getPointPosition2DBlock(
            point_group, point, camera,
            1, cam_num_frames
        )
        valid_mode = _get_point_valid_mode(point_group, point)

        # Write per-frame position data
        num_valid_frame = 0
        pos_list = []
        weight_list = []
        frame = 1  # 3DE starts at frame '1' regardless of the 'start-frame'.
        for v in c2d:
            if v[0] == -1.0 or v[1] == -1.0:
                # No valid data here.
                frame += 1
                continue

            # Does the 2D point go outside the camera FOV? Is that ok?
            valid = tde4.isPointPos2DValid(
                point_group,
                point,
                camera,
                frame
            )
            if valid == 0:
                # No valid data here.
                frame += 1
                continue

            # Check if we're inside the FOV / Frame or not.
            valid_pos = _is_valid_position(v, camera_fov, valid_mode)
            if valid_pos is False:
                frame += 1
                continue

            # Number of points with valid positions
            num_valid_frame += 1

            f = frame + frame0
            if rs_distance is not None:
                v = vl_sdv.vec2d(v[0], v[1])
                v = _remove_rs_from_2d_point(
                    point_group, camera, frame, v, rs_distance)
            if undistort is True:
                v = tde4.removeDistortion2D(camera, frame, v)
            weight = _get_point_weight(point_group, point, camera, frame)

            pos_list.append((f, v))
            weight_list.append((f, weight))
            frame += 1

        # add data
        data_str += name + '\n'
        data_str += '{0:d}\n'.format(num_valid_frame)
        for pos_data, weight_data in zip(pos_list, weight_list):
            f = pos_data[0]
            v = pos_data[1]
            w = weight_data[1]
            assert f == weight_data[0]
            data_str += '%d %.15f %.15f %.8f\n' % (f, v[0], v[1], w)

    return data_str