Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import bpy
- import bmesh
- from mathutils.geometry import barycentric_transform, intersect_point_tri_2d
- # this will use the 2D cursor of the first UV editor found
- for area in bpy.context.screen.areas:
- if area.type == 'IMAGE_EDITOR':
- space_data = area.spaces.active
- loc = space_data.cursor_location
- norm_coords = space_data.uv_editor.show_normalized_coords
- break
- else:
- raise Exception("No UV editor found")
- # mesh UVs are always normalized, but not the 2D cursor!
- def uv_normalize(tex, uv):
- if tex.image is None:
- x, y = 256, 256
- else:
- x, y = tex.image.size
- return (uv[0] / x, uv[1] / y, 0) # to_3d()
- ob = bpy.context.object
- assert ob.type == "MESH", "Selected object not a mesh"
- me = ob.data
- bm = bmesh.new()
- bm.from_mesh(me)
- # tag selected faces, because triangulate may clear selection state
- for f in bm.faces:
- if f.select:
- f.tag = True
- # viewport seems to use fixed / clipping instead of beauty
- bmesh.ops.triangulate(bm, faces=bm.faces, quad_method=1, ngon_method=1)
- # re-select faces
- for f in bm.faces:
- if f.tag:
- f.select_set(True)
- uv_layer = bm.loops.layers.uv.active
- tex = bm.faces.layers.tex.active
- def find_coord(loc, face, uvs):
- uv1, uv2, uv3 = uvs
- x, y, z = [v.co for v in face.verts]
- co = barycentric_transform(loc, uv1, uv2, uv3, x, y, z)
- bpy.context.scene.cursor_location = ob.matrix_world * co
- random_face = None
- sel_faces = [f for f in bm.faces if f.select]
- for face in sel_faces:
- uv1, uv2, uv3 = [l[uv_layer].uv.to_3d() for l in face.loops]
- if norm_coords:
- loc_normalized = loc.to_3d()
- else:
- loc_normalized = uv_normalize(face[tex], loc)
- # remember the first face for possible fallback
- if random_face is None:
- random_face = loc_normalized, face, (uv1, uv2, uv3)
- #print("trying", loc_normalized, "vs", uv1, uv2, uv3)
- if intersect_point_tri_2d(loc_normalized, uv1, uv2, uv3):
- print("found intersecting triangle")
- find_coord(loc_normalized, face, (uv1, uv2, uv3))
- break
- else:
- print("trying random selected face for extrapolation")
- find_coord(*random_face)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement