Skip to content

Instantly share code, notes, and snippets.

@Fintan
Created February 24, 2019 15:24
Show Gist options
  • Save Fintan/e28cb1f01a6a9770545580f888fef179 to your computer and use it in GitHub Desktop.
Save Fintan/e28cb1f01a6a9770545580f888fef179 to your computer and use it in GitHub Desktop.
Add empty at viewport camera location
import bpy
def get3dViewport():
for a in bpy.context.window.screen.areas:
if a.type == 'VIEW_3D':
print('this ones the 3d viewport')
viewport = a;
return viewport;
# create a cameras collection if it doesn't already exist
def createWaypointsCollection():
if bpy.data.collections.find('waypoints') == -1:
bpy.data.collections.new('waypoints')
bpy.data.collections["Collection"].children.link(bpy.data.collections["waypoints"])
#bpy.data.collections['waypoints'].hide_viewport = True;
def createTrackToEmpty( trackToName='Empty_for_tracking' ):
if bpy.data.objects.find(trackToName) == -1:
empty = bpy.data.objects.new("Empty", None);
empty.name = trackToName;
bpy.data.collections['waypoints'].objects.link(empty);
def createWaypointEmpty(viewport):
region_3d = viewport.spaces[0].region_3d;
# https://blenderartists.org/t/how-to-access-the-view-3d-camera/601372/2
viewport_pos = region_3d.view_matrix.inverted();
empty_ob = bpy.data.objects.new("Empty", None)
empty_ob['lens'] = viewport.spaces[0].lens;
empty_ob['camera_zoom'] = region_3d.view_camera_zoom;
empty_ob['location_x'] = viewport_pos.translation.x;
empty_ob['location_y'] = viewport_pos.translation.y;
empty_ob['location_z'] = viewport_pos.translation.z;
empty_ob['camera_at_pos'] = viewport_pos.translation;
empty_ob['track_to_pos'] = region_3d.view_matrix.translation;
empty_ob['view_matrix'] = region_3d.view_matrix;
empty_ob.location = viewport_pos.translation;
return empty_ob;
def removeAllWaypoints():
if bpy.data.collections.find('waypoints') == -1:
return;
# deselect all
bpy.ops.object.select_all(action='DESELECT');
# https://wiki.blender.org/wiki/Reference/Release_Notes/2.80/Python_API/Scene_and_Object_API
for ob in bpy.data.collections['waypoints'].objects:
ob.select_set(ob.type == 'EMPTY' and ob.name.startswith("Empty"));
# remove it
bpy.ops.object.delete();
#removeAllWaypoints();
createWaypointsCollection();
createTrackToEmpty('Empty.for.tracking');
viewport = get3dViewport();
empty_ob = createWaypointEmpty(viewport);
bpy.data.collections['waypoints'].objects.link(empty_ob);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment