text:
How to load ".npy" file into Blender?
I have a 3-dimensional volume array of size (64, 64, 64) which has an extension of ".npy". I wanted to visualize in Blender so that I can do post-processing work from the software.

I tried loading through script as np.load('data.npy') after importing numpy library. It did not show me any error, but I am unable to visualize it.

Is there a way I could load ".npy" file extension in Blender and visualize it. Or, is there a way I can convert the possible format for blender.

Numpy point cloud
Test script.

Get the verts of context object
Save as test.npy
Load saved file
Create mesh with saved verts
Add mesh to new object and link to scene

Test script
import bpy
import numpy as np

context = bpy.context
ob = context.object
me = ob.data
# get the coords of context object
coords = np.empty(len(me.vertices) * 3)
me.vertices.foreach_get("co", coords)
print(coords.reshape(-1, 3))
# save to .npy file
np.save('test.npy', coords.reshape(-1, 3))
#load it into another array
verts = np.load('test.npy')
print(verts)
# new mesh
me = bpy.data.meshes.new("Verts")
# load in verts
me.from_pydata(verts, [], [])
# create object and link to scene
vob = bpy.data.objects.new("Verts", me)
context.collection.objects.link(vob)
# give same global transform
#vob.matrix_world = ob.matrix_world


text:
Force redraw add-on custom propery in N panel from a separate thread
I have a few custom properties in my add-on to store state data of my job which is executed in the cloud.
class Properties(bpy.types.PropertyGroup):
    """Add-on properties."""
    # Job
    job_id: bpy.props.StringProperty(name="Id", default="", description="Id of the job",)
    job_title: bpy.props.StringProperty(name="Title", default="", description="Title of the job",)
    job_status: bpy.props.StringProperty(name="Status", default="", description="Status of the job",)
    job_progress: bpy.props.FloatProperty(name="Progress", default=0.0,  max=100.0, subtype="PERCENTAGE", description="Progress percentage of the job",)

When I execute a job from the add-on, I also run a separate thread that listen to my API using a websocket connection / GraphQL subscription. When the subscription receives a message, it calls a callback method (running in the separate thread) to updates the job progress and job status properties. Here are the methods.
class CRAFT_OT_subscribe_job(bpy.types.Operator):
    """Subscribe to a job"""
    bl_idname = "craft.subscribe_job"
    bl_label = "Subscribe Job"
    bl_options = {"REGISTER"}

    @staticmethod
    def update_job_progress(job):
        # Update the status and progress percentage of the job
        bpy.context.scene.craft_addon.job_status = job["status"]
        bpy.context.scene.craft_addon.job_progress = float(job["progress"])*100

        # Redraw panel
        for region in bpy.context.area.regions:
            if region.type == "UI":
                region.tag_redraw()

    def execute(self, context):
        # Subscribe job and output
        job_id = int(context.scene.craft_addon.job_id)
        client = bpy.app.driver_namespace.get("craftclient")
        client.subscribe_job(job_id=job_id, callback=self.update_job_progress) # This starts a new thread
        return {"FINISHED"}

The job progress and job status properties are updated properly but they are not refreshed in the N panel UI until user moves the mouse over it. I have tried to call tag_redraw() as mentioned in this answer but since my static method update_job_progress() runs in a separate thread, it triggers the error.

AttributeError: 'NoneType' object has no attribute 'regions'

Any suggestion how I could force redraw the N panel or just the corresponding custom property from a separate thread?

Try context.area.tag_redraw() on your panel.

I tried bpy.context.area.tag_redraw() ratther than context.area.tag_redraw() because I don't have the context in my callback method update_job_progress. I get the same error: AttributeError: 'NoneType' object has no attribute 'tag_redraw'

Had some time to create a demo according to your requirements, see: https://pasteall.org/t98x/raw In short: you can use the update method of the float property and tag the area that way. Does that work for you?

Thank you so much for looking into it @brockmann. I still faced the error for region in context.area.regions: AttributeError: 'NoneType' object has no attribute 'regions' with your method, most likely because contrariwise to your script, mine is multi-threaded. That said, it seems using the update method of the FloatProperty is enough to force the refresh of the UI, even if the method does nothing :) Don't you want to write an answer so that I vote it up?

You can use the update method of the FloatProperty and tag the area that way:
def update_callback(self, context):
    for region in context.area.regions:
        if region.type == "UI":
            region.tag_redraw()
    return None

class MySettings(bpy.types.PropertyGroup):

    my_float: bpy.props.FloatProperty(
        update=update_callback)
    ...

Demo using the Operator Modal Timer template that comes with Blender:
import bpy

def ui_update(self, context):
    for region in context.area.regions:
        if region.type == "UI":
            region.tag_redraw()
    return None

class MySettings(bpy.types.PropertyGroup):

    my_float: bpy.props.FloatProperty(
        name="Float",
        description="Float property",
        default = 0,
        update=ui_update)

class ModalTimerOperator(bpy.types.Operator):
    """Operator which runs its self from a timer"""
    bl_idname = "wm.modal_timer_operator"
    bl_label = "Modal Timer Operator"

    _timer = None

    def modal(self, context, event):
        if event.type in {'RIGHTMOUSE', 'ESC'}:
            self.cancel(context)
            return {'CANCELLED'}

        if event.type == 'TIMER':
            context.scene.my_tool.my_float += .1
        return {'PASS_THROUGH'}

    def execute(self, context):

        wm = context.window_manager
        self._timer = wm.event_timer_add(0.1, window=context.window)
        wm.modal_handler_add(self)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        wm = context.window_manager
        wm.event_timer_remove(self._timer)

class OBJECT_PT_panel(bpy.types.Panel):
    bl_label = "My Panel"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Tools"
    bl_context = "objectmode"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        mytool = scene.my_tool
        layout.prop(mytool, "my_float")
        layout.operator(ModalTimerOperator.bl_idname)

classes = (
    MySettings,
    ModalTimerOperator,
    OBJECT_PT_panel,
)

addon_keymaps = []

def register():
    from bpy.utils import register_class
    for cls in classes:
        register_class(cls)

    bpy.types.Scene.my_tool = bpy.props.PointerProperty(type=MySettings)

def unregister():

    from bpy.utils import unregister_class
    for cls in reversed(classes):
        unregister_class(cls)

    del bpy.types.Scene.my_tool

if __name__ == "__main__":
    register()

Layout code ripped from: How to create a custom UI?

Perhaps a  bpy.app.timer would emulate another thread better. A draw callback on the space that contains, while the timer is running,  the panel could also be an option here.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
A mess happens when i try to unwrap my model, any idea whats causing this?

Please help i have been at this for a couple of hours, and i have no idea how to fix this.

Can you add the blend file? I think you need to add more seams in problematic areas.

have you removed any doubles (in edit mode W --> remove doubles). And a blendfile would help.

i have removed the doubles, and ill add the file now :)

add the top of your sword are a lot of vertices that aren 't connected to each other. So you have to fix that. Also the normals have to be recalculated and in some cases be flipped. And you need extra seams around all the bulges of the sword.

what are the normals ? and how do i do that

the problem is your model. You have got a lot of strange faces in the inside of your sword, and on top of the sword some vertices that are not connected while they should be. So you have to delete all the inner faces and connect the vertices that should be connected. And then add the seams and UV-unwrap the model
In the blendfile I add, I corrected it all so you can see the difference.

Thank you so much, your advice will help a lot in the future. Also thank you for doing it <3

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
texture mapping menu missing in blender render 2.75

I cant find the texture mapping drop down menu in the texture menu when using blender render, are there any alternatives?

You're right, the Mapping panel should be there. Can you post the blend file please?

This is because Use Nodes is enabled on the material using the texture:

Once this option is disabled, the Mapping panel is available in the texture options.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
What is blender's camera projection matrix model?
I have question what is blender's camera projection model.
I want to use blender to my computer vision experiment which need to compare real photo and CG. For real photo, I used camera matrix K for perspective projection, like this
 K= [f 0 Px 0]
    [0 f Py 0]
    [0 0  1 0]

(Px and Py is center coordiate of 2D image, start from Top-Left to Bottom Right)
So I can easily transform 3D vertex to 2D pixel coordinate. To compare this matrix, I need to know how blender make camera matrix K in it's internal rendering process. It seems that blender's camera has 3 parameters (f (focal length), near plane, far plane. Ignoring shift x and y).
How to make blender's camera projection matrix which transform 3D vertex to 2D image coordinate from these 3 paremeters?

Related: http://blender.stackexchange.com/q/9203/599

I checked that post and find perspetive matrix generation method, but it is complete same with OpenGL's perspective matrix expression. It has left, right, top, bottom, near, far parameters. But I don't know how actually blender's camera settings converted to that parameters. Do you know any thing that?

The following Python code builds a calibration matrix K commonly used in computer vision from a Blender camera. You can then use the generated K matrix to compare against your own.
import bpy
from mathutils import Matrix

def get_calibration_matrix_K_from_blender(camd):
    f_in_mm = camd.lens
    scene = bpy.context.scene
    resolution_x_in_px = scene.render.resolution_x
    resolution_y_in_px = scene.render.resolution_y
    scale = scene.render.resolution_percentage / 100
    sensor_width_in_mm = camd.sensor_width
    sensor_height_in_mm = camd.sensor_height
    pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y
    if (camd.sensor_fit == 'VERTICAL'):
        # the sensor height is fixed (sensor fit is horizontal),
        # the sensor width is effectively changed with the pixel aspect ratio
        s_u = resolution_x_in_px * scale / sensor_width_in_mm / pixel_aspect_ratio
        s_v = resolution_y_in_px * scale / sensor_height_in_mm
    else: # 'HORIZONTAL' and 'AUTO'
        # the sensor width is fixed (sensor fit is horizontal),
        # the sensor height is effectively changed with the pixel aspect ratio
        pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y
        s_u = resolution_x_in_px * scale / sensor_width_in_mm
        s_v = resolution_y_in_px * scale * pixel_aspect_ratio / sensor_height_in_mm

    # Parameters of intrinsic calibration matrix K
    alpha_u = f_in_mm * s_u
    alpha_v = f_in_mm * s_v
    u_0 = resolution_x_in_px*scale / 2
    v_0 = resolution_y_in_px*scale / 2
    skew = 0 # only use rectangular pixels

    K = Matrix(
        ((alpha_u, skew,    u_0),
        (    0  ,  alpha_v, v_0),
        (    0  ,    0,      1 )))
    return K

if __name__ == "__main__":
    # Insert your camera name below
    K = get_calibration_matrix_K_from_blender(bpy.data.objects['Camera'].data)
    print(K)

Notes

I've tested this with cycles and many scenes, and it works.
The updated code is now well-tested with non-unit aspect ratio in different scenes.
Non-zero skew is not supported in blender AFAIK.
The principal point assumed fixed at the center of the image. If this is not so, this code needs to be updated to take camera shift into account (see How to set a principal point for a camera)
Lens distortion is taken into account separately, see my answer to Distortion Coefficients and Camera intrinsic of blender's cameras?
I'm ignoring your last column containing all zeros.
The code is written explicitly for documentation purposes. I apologize for the long names and extra variables but it really pays off for debugging careful parameter conversions.
To get the full "projection matrix which transforms 3D vertex to 2D image coordinates" you mention in the end of your question, see my answer to 3x4 camera matrix from blender camera.

Thanks for detailed reply, rfabbri. I tested your code and found some problem about fy (alpha_v) in non-uniform  aspect image (1280x960). I projected mesh to camera, the x of projected position is correct, but y is looks incorrect. I modified your code to aspect_ratio_resolution = resolution_x_in_px / resolution_y_in_px s_v = resolution_y_in_px * scale * aspect_ratio / aspect_ratio_resolution / sensor_height_in_mm Then I got correct result. But I don't know what I did. Can you explan about this?

Also I found that the original and modified code does not work for non uniform pixel aspect (non-square pixel).

@KichangKim what is your sensor fit setting? (next to sensor size: Auto, Horizontal or Vertical)?

@KichangKim I've updated the code (and tested it). Thanks. The pixel aspect ratio is a render context setting, technically not really a physical camera parameter but part of the projection model which takes into account the pixel aspect ratio to be displayed. I am certain that the example you tried had a vertical sensor fit; this reverses the way the aspect ratio influences pixel coordinate computation in blender (I checked this against blender's internal code logic in addition to testing it). If the fit is vertical, the aspect is inverted so it needs to be applied to x.

Thanks for updating code. I found that small mistake in your code, duplicating pixel_aspect_ratio calculation in HORIZONTAL and AUTO mode :)

It looks like there is a bug in this script. I have a camera with resolution 640x320, focal length 18 and sensor width 32. Regardless of which sensor fit I choose, the focal length is (360, 320) but it should be (360, 360) -- which I verified by rendering a calibration pattern. You can find my blend-file here: https://ufile.io/1a231

I've also found the similar problem with camera resolution 640x480, sensor fit AUTO, and the corrected focal length is (640, 640), but is shown (640,853). How can we reason about that?

I (think I) fixed the problems with this function in my modified version.

the solution of rfabbri is overly complicated and computes the wrong alpha_v he also includes the image aspect ratio there. Also it merely fixes the principal point at center. See https://www.rojtberg.net/1601/from-blender-to-opencv-camera-and-back/ for a shorter and complete solution.

@user927543 if you are so sure please write a proper answer. I have no time to check everything. but thanks for trying!

This is a great resource.  No need to apologize for properly named variables; in fact, it should be encouraged.

@paroj - your example is not complete.  It asserts non-vertical sensor_fit and non-scaled image.  A complete example would account for those, no?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Loft between curves in commandline
I am developing a commandline tool to experiment with lofting a set of curves, and would appreciate any guidance.
Usage
blender_loft c0.txt c1.txt output.txt          # simplest to start with

Input

c0.txt, c1.txt: two or more 3D curves represented as a text file each listing the ordered curve samples, one xyz coordinate triplet per line. These are usually just polylines finely sampling some curve fragments.

Output

A file storing a surface between these curves, tautly stretching over the curve fragments as best as possible.

Requirements

Speed is desirable but not a big deal since I just want to experiment first prior to writing optimal code.
Easy to install for others to use. Ideally, just downloading blender should suffice.

What I have so far

So far it seems BSurfaces's loft functionality is the most feature-rich out there, so I went with that. I want to target all its fancy controls and possibilities in the long run.
A bpy script that reads the text files, creates bezier curves from the samples, and try to simulate what Bsurfaces does - for now it is limited to this:

Code I have so far
# Loft curves given by files into surface
#
# INPUT
#    p0.txt, p1.txt
#
# OUTPUT
#    loftsurf.ply
#
# USAGE
#
#   Commandline
#      blender -b -nosound -P blender_loft.py
#
#   Inside blender console
#
#      filename = "PWD/blender_loft.py"
#      exec(compile(open(filename).read(), filename, 'exec'))
#
# AUTHOR
#   Ricardo Fabbri <rfabbri@gmail.com>, 3 Dec 2015
#
import bpy
import bpy_extras
import numpy
from mathutils import Matrix

# Create a spline/bezier from a list of points
def new_curve_from_points(p0,name_prefix):
    npts = len(p0)
    c0 = bpy.data.curves.new(name_prefix + 'CurveToLoft', 'CURVE')
    o0 = bpy.data.objects.new(name_prefix + 'CurveToLoft', c0)
    bpy.context.scene.objects.link(o0)
    c0.dimensions = "3D"

    spline = o0.data.splines.new('BEZIER')
    spline.bezier_points.add(npts - 1)
    # ^-- less one because one point is added when the spline is created.
    for p in range(0, npts):
        spline.bezier_points[p].co = p0[p]
        # spline.bezier_points[p].co = [p0[p][0], p0[p][1], p0[p][2]]
    return c0, o0, spline

def read_files():
    p0_fname = 'p0.txt'
    p1_fname = 'p1.txt'
    p0 = numpy.loadtxt(p0_fname)
    p0.tolist()
    p1 = numpy.loadtxt(p1_fname)
    p1.tolist()
    return p0, p1

# to be called inside console after testing
def cleanup():
    bpy.ops.object.mode_set(mode='OBJECT', toggle=True)
    bpy.ops.object.delete(use_global=False)

def test():
    print('hello')
    p0 = []
    p0.append([1, 0, 0])
    p0.append([0, 0, 0])
    p0.append([0, 1, 0])

    p1 = []
    p1.append([1, 1, 0])
    p1.append([0, 1, 0])
    p1.append([0, 0, 1])
    loft(p0,p1)

def test1():
    # cleanup()
    p0, p1 = read_files()
    loft(p0, p1)
    bpy.ops.export_mesh.ply(filepath='loftsurf.ply')

def loft(p0, p1):
    c0, o0, s0 = new_curve_from_points(p0,'first')
    c1, o1, s1 = new_curve_from_points(p1,'second')

    # join curves into a group
    bpy.data.objects[o0.name].select = True
    bpy.data.objects[o1.name].select = True
    bpy.context.scene.objects.active = bpy.data.objects[o1.name]
    bpy.ops.object.join('INVOKE_REGION_WIN')

    # create a mesh to store the final surface
    me = bpy.data.meshes.new("outputLoft")
    ob = bpy.data.objects.new("outputLoft", me)
    scn = bpy.context.scene
    scn.objects.link(ob)
    scn.objects.active = ob
    ob.select = True

    # curves + object should be selected
    # call lofting
    bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT', toggle=True)
    bpy.ops.mesh.reveal()
    bpy.ops.gpencil.surfsk_add_surface('INVOKE_DEFAULT')

if __name__ == "__main__":
    test1()

The Issue
The current solution works from the GUI python console, but I'm still having a hard time calling it from commandline without the '-b' option.

Cheating by calling without '-b' and calling bpy.ops.wm.quit_blender() in the end main works OK as prototype.
This is basically a context problem

Remarks

Besides the current issue above, I would like to call the script directly from C or standalone python so that we don't have to set up blender entirely each time we're lofting between curves.
I cannot use a lower-level API than bpy with this solution since BSurfaces is very intertwined with bpy to the basic level.

This discussion should be useful for anyone writing tools that seemlessly use blender in the background. I am not very experienced with blender.
My main question is whether this all looks like a decent way to go, besides the above specific issue.
Note: After I initially wrote this question, partial solutions have been evolving and I have been updating this accordingly. Sorry if it seems like a multi-question question during this process. Feel free to post partial answers and evolve, this would already be useful, though I will accept the answer if it is thorough enough.

Edit: I quickly wrote the script listed in the question as a partial answer, now moved into the question body.

Why are you making two Curve Objects when you can make a single Curve Object which contains two disjoint Beziers? (this is what the Bsurfaces code wants anyway) call data.splines.new('BEZIER') a second time on the same object and it will return a new reference to the next disjoint bezier.

@zeffii true. good to learn. I just hacked it quickly, thats why.. tks.

You have something like this and that's throwing errors? - it throws errors here GPENCIL_OT_SURFSK_add_surface object has no attribute 'is_fill_faces'

@zeffii awesome, I wasn't sure even if I should open a new question and have to explain it all over again. I'll do what you suggested.

@zeffii done. thanks. I might link to a git repository, but I'd avoid that for now for locality and archival purposes.

@zeffii yes, that's what this evolved to. I edited the question. Yes, same error.

if there's isn't some kind of way to easily get past all those errors, it's probably faster to write your own bezier->points->UVsurface code :) than to try to excavate the working code from the add-on.

@zeffii except that the add-on has a bunch of other stuff I want that's already debugged; and any change we make goes to the community. But you're right, it might not have so much stuff in it worth scraping.


text:
3x4 camera matrix from blender camera
In computer vision, the transformation from 3D world coordinates to pixel coordinates is often represented by a 3x4 (3 rows by 4 cols) matrix P as detailed below. Given a camera in Blender, I need code that returns P.
Context where this shows up
It is common for people to want the reverse: to set Blender or OpenGL camera transforms from a given 3x4 P. This is so due to Augmented reality where 3x4 cameras are computed from real imagery using computer vision / structure from motion algorithms which are then used in CG to render registered synthetic models.
In my case, I am using Blender to generate synthetic data to validate a 3D structure from motion (3D reconstruction) algorithm. I need to use the synthetic Blender cameras inside a computer vision pipeline based on 3x4 P.
Some Details
An image pixel $(u,v)$ is generated from world $(x,y,z)$ coordinates through a 3x4 matrix using projective coordinates:
$$kx = PX,$$
where $k$ is a constant, $x = (u,v,1)^t$, $X = (X,Y,Z,W)^t$, and $P$ can be decomposed as
$$P=K[I|0] \begin{bmatrix}
R & T\\
0^\text{t} & 1
\end{bmatrix} = K[R|T],$$
where $K$ can be written as
$$K=\begin{bmatrix}
\alpha_u & s & u_o\\
0 & \alpha_v & v_o\\
0 & 0 & 1
\end{bmatrix},$$
where
$$f=\text{focal length}$$
$$\alpha_u=\frac{f\times u\text{ pixels}}{\text{unit length}}=\frac{f}{\text{width of a pixel in world units}}$$
$$\alpha_v=\frac{f\times v\text{ pixels}}{\text{unit length}}=\frac{f}{\text{height of a pixel in world units}}$$
$$u_o=u\text{ coordinate of principal point}$$
$$v_o=v\text{ coordinate of principal point}$$
$$s=\text{skew factor}$$
I need to generate this from a Blender camera (e.g., from the Cycles engine).
Preliminary Research
I could certainly detail this up further in terms of all the coordinate systems and work out the solution myself if need be, but I'm looking to reuse well-tested shared code. Perhaps there could be something in libmv.
Directly related to:
What is blender's camera projection matrix model?, blender camera from 3x4 matrix
Other related questions:
How can I get the camera's projection matrix?,
How to find image coordinates of the rendered vertex?

Is that 3x4 matrix you are talking about any different from a 4x4 Blender matrix with the 4th row removed? Some game engines use this kind of optimization to save some memory (CryEngine afaik). The 3x3 part contains rotation and scale information, the 4th column the location and the 4th row is rather unneeded - unless for 2D/3D transformation, because you need to devide by the value of the last cell (it's usually 1 though for 3D transformations, and the other 3 are 0).

@CoDEmanX, the 4x4 blender matrix you mention, e.g. camera.matrix_world, does not contain the internal camera parameters (see get_calibration_matrix_K_from_blender below). Moreover, the rotation part of the blender matrix needs to be transposed for it to represent coordinate change instad of the camera rotation, and rotated appropriatedly if the desired 3x4 matrix is to represent a camera coordinate system commonly used in computer vision where x is horizontal, y is down (to align to the actual matrix pixel coordinates) and z is positive for look-at direction.

@rfabbri, Thanks for your answer.  How can we get the projection equation of a fisheye camera ? What is model of fisheye have been used?

@startingBlender Your comment-question merits a real question. This is related to lens distortion, which is taken into account separately, see my answer to http://blender.stackexchange.com/questions/38208/distortion-coefficients-and-camera-intrinsic-of-blenders-cameras/38460#38460

Now there is a Blender add-on for Computer Vision applications that does this automatically for you: VisionBlender

I wrote the function get_3x4_RT_matrix_from_blender to do this, listed below.
import bpy
import bpy_extras
from mathutils import Matrix
from mathutils import Vector

#---------------------------------------------------------------
# 3x4 P matrix from Blender camera
#---------------------------------------------------------------

# Build intrinsic camera parameters from Blender camera data
#
# See notes on this in
# blender.stackexchange.com/questions/15102/what-is-blenders-camera-projection-matrix-model
def get_calibration_matrix_K_from_blender(camd):
    f_in_mm = camd.lens
    scene = bpy.context.scene
    resolution_x_in_px = scene.render.resolution_x
    resolution_y_in_px = scene.render.resolution_y
    scale = scene.render.resolution_percentage / 100
    sensor_width_in_mm = camd.sensor_width
    sensor_height_in_mm = camd.sensor_height
    pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y
    if (camd.sensor_fit == 'VERTICAL'):
        # the sensor height is fixed (sensor fit is horizontal),
        # the sensor width is effectively changed with the pixel aspect ratio
        s_u = resolution_x_in_px * scale / sensor_width_in_mm / pixel_aspect_ratio
        s_v = resolution_y_in_px * scale / sensor_height_in_mm
    else: # 'HORIZONTAL' and 'AUTO'
        # the sensor width is fixed (sensor fit is horizontal),
        # the sensor height is effectively changed with the pixel aspect ratio
        pixel_aspect_ratio = scene.render.pixel_aspect_x / scene.render.pixel_aspect_y
        s_u = resolution_x_in_px * scale / sensor_width_in_mm
        s_v = resolution_y_in_px * scale * pixel_aspect_ratio / sensor_height_in_mm

    # Parameters of intrinsic calibration matrix K
    alpha_u = f_in_mm * s_u
    alpha_v = f_in_mm * s_v
    u_0 = resolution_x_in_px * scale / 2
    v_0 = resolution_y_in_px * scale / 2
    skew = 0 # only use rectangular pixels

    K = Matrix(
        ((alpha_u, skew,    u_0),
        (    0  , alpha_v, v_0),
        (    0  , 0,        1 )))
    return K

# Returns camera rotation and translation matrices from Blender.
#
# There are 3 coordinate systems involved:
#    1. The World coordinates: "world"
#       - right-handed
#    2. The Blender camera coordinates: "bcam"
#       - x is horizontal
#       - y is up
#       - right-handed: negative z look-at direction
#    3. The desired computer vision camera coordinates: "cv"
#       - x is horizontal
#       - y is down (to align to the actual pixel coordinates
#         used in digital images)
#       - right-handed: positive z look-at direction
def get_3x4_RT_matrix_from_blender(cam):
    # bcam stands for blender camera
    R_bcam2cv = Matrix(
        ((1, 0,  0),
         (0, -1, 0),
         (0, 0, -1)))

    # Transpose since the rotation is object rotation,
    # and we want coordinate rotation
    # R_world2bcam = cam.rotation_euler.to_matrix().transposed()
    # T_world2bcam = -1*R_world2bcam * location
    #
    # Use matrix_world instead to account for all constraints
    location, rotation = cam.matrix_world.decompose()[0:2]
    R_world2bcam = rotation.to_matrix().transposed()

    # Convert camera location to translation vector used in coordinate changes
    # T_world2bcam = -1*R_world2bcam*cam.location
    # Use location from matrix_world to account for constraints:
    T_world2bcam = -1*R_world2bcam @ location

    # Build the coordinate transform matrix from world to computer vision camera
    # NOTE: Use * instead of @ here for older versions of Blender
    # TODO: detect Blender version
    R_world2cv = R_bcam2cv@R_world2bcam
    T_world2cv = R_bcam2cv@T_world2bcam

    # put into 3x4 matrix
    RT = Matrix((
        R_world2cv[0][:] + (T_world2cv[0],),
        R_world2cv[1][:] + (T_world2cv[1],),
        R_world2cv[2][:] + (T_world2cv[2],)
         ))
    return RT

def get_3x4_P_matrix_from_blender(cam):
    K = get_calibration_matrix_K_from_blender(cam.data)
    RT = get_3x4_RT_matrix_from_blender(cam)
    return K@RT, K, RT

# ----------------------------------------------------------
# Alternate 3D coordinates to 2D pixel coordinate projection code
# adapted from https://blender.stackexchange.com/questions/882/how-to-find-image-coordinates-of-the-rendered-vertex?lq=1
# to have the y axes pointing up and origin at the top-left corner
def project_by_object_utils(cam, point):
    scene = bpy.context.scene
    co_2d = bpy_extras.object_utils.world_to_camera_view(scene, cam, point)
    render_scale = scene.render.resolution_percentage / 100
    render_size = (
            int(scene.render.resolution_x * render_scale),
            int(scene.render.resolution_y * render_scale),
            )
    return Vector((co_2d.x * render_size[0], render_size[1] - co_2d.y * render_size[1]))

# ----------------------------------------------------------
if __name__ == "__main__":
    # Insert your camera name here
    cam = bpy.data.objects['Camera.001']
    P, K, RT = get_3x4_P_matrix_from_blender(cam)
    print("K")
    print(K)
    print("RT")
    print(RT)
    print("P")
    print(P)

    print("==== Tests ====")
    e1 = Vector((1, 0,    0, 1))
    e2 = Vector((0, 1,    0, 1))
    e3 = Vector((0, 0,    1, 1))
    O  = Vector((0, 0,    0, 1))

    p1 = P @ e1
    p1 /= p1[2]
    print("Projected e1")
    print(p1)
    print("proj by object_utils")
    print(project_by_object_utils(cam, Vector(e1[0:3])))

    p2 = P @ e2
    p2 /= p2[2]
    print("Projected e2")
    print(p2)
    print("proj by object_utils")
    print(project_by_object_utils(cam, Vector(e2[0:3])))

    p3 = P @ e3
    p3 /= p3[2]
    print("Projected e3")
    print(p3)
    print("proj by object_utils")
    print(project_by_object_utils(cam, Vector(e3[0:3])))

    pO = P @ O
    pO /= pO[2]
    print("Projected world origin")
    print(pO)
    print("proj by object_utils")
    print(project_by_object_utils(cam, Vector(O[0:3])))

    # Bonus code: save the 3x4 P matrix into a plain text file
    # Don't forget to import numpy for this
    nP = numpy.matrix(P)
    numpy.savetxt("/tmp/P3x4.txt", nP)  # to select precision, use e.g. fmt='%.2f'

Detailed Tests

I included some helper functions and tests to cross-check the 3D-2D projection process with another approach using world_to_camera_view from @ideasman42's answer to How to find image coordinates of the rendered vertex? The floating point coordinates match up perfectly up to many decimal places. To get the integer pixel coordinates after projection, just round them.

I tested this visually and analytically with a few scenes, to make sure both routines were exactly correct on actual rendered images.

I represented e1, e2, e3 and O with small cone objects whose tips were at the desired positions
and coded with different colors: Red for X, Green for Y, Blue for Z
I placed the camera at a convenient location at first,
R = identity, T = (0,0,5)
I used default Blender parameters for the camera intrinsics
I computed the P matrix by hand and computed it using my rountines and they match perfectly
Visually comparing both the Cycles render and the OpenGL render in GIMP show that the produced coordinates match well visually (up to perhaps +- 1 pixel error, which is the sort of thing this careful testing was carried out anyways - to be investigated).
I then arbitrarily rotated and translated the camera such that the world e1, e2, e3 remain visible and at general locations. The projections match visually in the rendered images, and also match to the ones given by the object utils routine given above.

Here is an example of a test output:
  K
<Matrix 3x3 (2100.0000,    0.0000, 960.0000)
            (   0.0000, 2100.0000, 540.0000)
            (   0.0000,    0.0000,   1.0000)>
RT
<Matrix 3x4 (-0.0594, -0.9483, -0.3118, -0.6837)
            ( 0.6234,  0.2087, -0.7536, -0.1887)
            ( 0.7797, -0.2391,  0.5787,  4.2599)>
P
<Matrix 3x4 ( 623.8236, -2220.9482,   -99.1637, 2653.7441)
            (1730.0916,   309.2392, -1269.9426, 1904.1343)
            (   0.7797,    -0.2391,     0.5787,    4.2599)>
==== Tests ====
Projected e1
<Vector (650.3716, 721.1436, 1.0000)>
proj by object_utils
<Vector (650.3716, 721.1436)>
Projected e2
<Vector (107.6402, 550.4857, 1.0000)>
proj by object_utils
<Vector (107.6403, 550.4857)>
Projected e3
<Vector (527.9586, 131.0692, 1.0000)>
proj by object_utils
<Vector (527.9586, 131.0693)>
Projected world origin
<Vector (622.9655, 446.9949, 1.0000)>
proj by object_utils
<Vector (622.9656, 446.9949)>

Here is the test set with the blender rotation and location for the camera.

Here is the OpenGL render. The coordinates output above match the tip of the cones visually (up to +- 1 px error, perhaps due to aliasing).

Limitations: this code currently does not support certain intrinsic camera parameter configurations, see my answer to What is blender's camera projection matrix model? for a list of the limitations to get_calibration_matrix_K_from_blender.
Object coordinates: to deal with object coordinates, first transform to world coordinates, see my answer to How to find image coordinates of the rendered vertex?
Matrix multiplication used to be * before Blender 2.8, newer versions use @ instead

Where I can find information details about the 3 coordinate system involved to get the external parameters in blender documentation?

@startingBlender just figure it out from basic facts: 1) look at the blender xyz glyphs - they show you blender uses a right-handed coordinate system 2) in graphics an image's coordinates's x is horizontal, y vertical pointing up, and the origin is on the bottom-left corner 3) Since the camera's coordinate system must be right-handed to be expressible as a rotation and translation from the right-handed world coordinates, the camera look-at direction must be negative z. The third coordinate system "cv" is up to you; just keep this convention in mind when interpreting projected coordinates.

Thanks! Do you have any idea about the projection model of the panoramic camera with fisheye equisolid lens ?

@startingBlender please ask that in a new question

I have asked this question http://blender.stackexchange.com/questions/40702/how-can-we-get-the-projection-matrix-of-the-panoramic-camera-with-fisheye-equiso

Thanks a lot for this wonderful answer. I am aware that this post was long before, yet I cant help wondering how you could figure out the coordinate system of blender camera? I was trying to get that information confirmed when I came across this post of yours.

Can you also show how we can get the same information for 2 cameras in a stereoscopic pair? I have asked my question at https://blender.stackexchange.com/questions/81100/stereo-camera-extrinsic-parameter

Helpful post, but in get_calibration_matrix_K_from_blender(), u_0 and v_0 needs to take camd.shift_x and camd.shift_y into account.

You also have to import Vector from mathutils

Thanks for the script! Unfortunately there seems to be an issue with it regarding the sensor fit. It produces the wrong values for me no matter whether the fit is AUTO, HORIZONTAL or VERTICAL. If I set alpha_v = alpha_u it works for the AUTO and HORIZONTAL fits. If I set alpha_u = alpha_v it works for the VERTICAL fit.

@HaozheXie someone updated the code for the latest Blender. Use * instead of @ for your Blender version.

@KarimSherifi This answer was originally written for 2.79 so I think it's important it remains compatible with 2.79. Maybe it would be better to add a note about the change in syntax for 2.8 or to add another code block for the 2.8 version.

@rfabbri Probably misunderstanding something here but doesn't Blender have a z-up coordinate system? Your comments say it is y-up, regarding Blender camera coordinates "bcam". Or does it not matter in this case?

I guess I was mixing up the global and view orientations of Blender, see here

@rfabbri The mapped 2d points are divided by the last element, p3 /= p3[2], what is this last element? Depth perhaps?

rfabbri's excellent answer works in many cases but not always. Based on his version I created a new one that (at least in my tests) works in all cases, including portrait and landscape pixel aspect ratios, automatic, horizontal and vertical sensor fitting as well as principal point offset (shift).
I had to dig a bit through Blender's source code to figure this out but it seems to work so far:
import bpy
from mathutils import Matrix, Vector

#---------------------------------------------------------------
# 3x4 P matrix from Blender camera
#---------------------------------------------------------------

# BKE_camera_sensor_size
def get_sensor_size(sensor_fit, sensor_x, sensor_y):
    if sensor_fit == 'VERTICAL':
        return sensor_y
    return sensor_x

# BKE_camera_sensor_fit
def get_sensor_fit(sensor_fit, size_x, size_y):
    if sensor_fit == 'AUTO':
        if size_x >= size_y:
            return 'HORIZONTAL'
        else:
            return 'VERTICAL'
    return sensor_fit

# Build intrinsic camera parameters from Blender camera data
#
# See notes on this in
# blender.stackexchange.com/questions/15102/what-is-blenders-camera-projection-matrix-model
# as well as
# https://blender.stackexchange.com/a/120063/3581
def get_calibration_matrix_K_from_blender(camd):
    if camd.type != 'PERSP':
        raise ValueError('Non-perspective cameras not supported')
    scene = bpy.context.scene
    f_in_mm = camd.lens
    scale = scene.render.resolution_percentage / 100
    resolution_x_in_px = scale * scene.render.resolution_x
    resolution_y_in_px = scale * scene.render.resolution_y
    sensor_size_in_mm = get_sensor_size(camd.sensor_fit, camd.sensor_width, camd.sensor_height)
    sensor_fit = get_sensor_fit(
        camd.sensor_fit,
        scene.render.pixel_aspect_x * resolution_x_in_px,
        scene.render.pixel_aspect_y * resolution_y_in_px
    )
    pixel_aspect_ratio = scene.render.pixel_aspect_y / scene.render.pixel_aspect_x
    if sensor_fit == 'HORIZONTAL':
        view_fac_in_px = resolution_x_in_px
    else:
        view_fac_in_px = pixel_aspect_ratio * resolution_y_in_px
    pixel_size_mm_per_px = sensor_size_in_mm / f_in_mm / view_fac_in_px
    s_u = 1 / pixel_size_mm_per_px
    s_v = 1 / pixel_size_mm_per_px / pixel_aspect_ratio

    # Parameters of intrinsic calibration matrix K
    u_0 = resolution_x_in_px / 2 - camd.shift_x * view_fac_in_px
    v_0 = resolution_y_in_px / 2 + camd.shift_y * view_fac_in_px / pixel_aspect_ratio
    skew = 0 # only use rectangular pixels

    K = Matrix(
        ((s_u, skew, u_0),
        (   0,  s_v, v_0),
        (   0,    0,   1)))
    return K

# Returns camera rotation and translation matrices from Blender.
#
# There are 3 coordinate systems involved:
#    1. The World coordinates: "world"
#       - right-handed
#    2. The Blender camera coordinates: "bcam"
#       - x is horizontal
#       - y is up
#       - right-handed: negative z look-at direction
#    3. The desired computer vision camera coordinates: "cv"
#       - x is horizontal
#       - y is down (to align to the actual pixel coordinates
#         used in digital images)
#       - right-handed: positive z look-at direction
def get_3x4_RT_matrix_from_blender(cam):
    # bcam stands for blender camera
    R_bcam2cv = Matrix(
        ((1, 0,  0),
        (0, -1, 0),
        (0, 0, -1)))

    # Transpose since the rotation is object rotation,
    # and we want coordinate rotation
    # R_world2bcam = cam.rotation_euler.to_matrix().transposed()
    # T_world2bcam = -1*R_world2bcam @ location
    #
    # Use matrix_world instead to account for all constraints
    location, rotation = cam.matrix_world.decompose()[0:2]
    R_world2bcam = rotation.to_matrix().transposed()

    # Convert camera location to translation vector used in coordinate changes
    # T_world2bcam = -1*R_world2bcam @ cam.location
    # Use location from matrix_world to account for constraints:
    T_world2bcam = -1*R_world2bcam @ location

    # Build the coordinate transform matrix from world to computer vision camera
    R_world2cv = R_bcam2cv@R_world2bcam
    T_world2cv = R_bcam2cv@T_world2bcam

    # put into 3x4 matrix
    RT = Matrix((
        R_world2cv[0][:] + (T_world2cv[0],),
        R_world2cv[1][:] + (T_world2cv[1],),
        R_world2cv[2][:] + (T_world2cv[2],)
        ))
    return RT

def get_3x4_P_matrix_from_blender(cam):
    K = get_calibration_matrix_K_from_blender(cam.data)
    RT = get_3x4_RT_matrix_from_blender(cam)
    return K@RT, K, RT

# ----------------------------------------------------------
if __name__ == "__main__":
    # Insert your camera name here
    cam = bpy.data.objects['Camera']
    P, K, RT = get_3x4_P_matrix_from_blender(cam)
    print("K")
    print(K)
    print("RT")
    print(RT)
    print("P")
    print(P)

    print("==== 3D Cursor projection ====")
    pc = P @ bpy.context.scene.cursor.location
    pc /= pc[2]
    print("Projected cursor location")
    print(pc)

    # Bonus code: save the 3x4 P matrix into a plain text file
    # Don't forget to import numpy for this
    #nP = numpy.matrix(P)
    #numpy.savetxt("/tmp/P3x4.txt", nP)  # to select precision, use e.g. fmt='%.2f'

Note that the sensor fit returned by get_sensor_fit is intentionally not used as the first parameter in the call to get_sensor_size. This is how Blender's source code does it and this is where the difference between VERTICAL and AUTO fits comes from.

I think there is a mistake in your script, which I found while rendering pictures for testing algorithms for stereoscopy. If you set the camera to a preset, e.g. GoPro Hero3 Black, the box for sensor size height does not show up and it appears, that it is not used. alpha_v equals alpha_u in this case. At least I get the right results this way.

Do you know how to set a blender camera to match the camera intrinsic of a real camera?

A life saver! The sensor size problem in rfabbri's code was giving me trouble, and your modifications fixed it. Thanks!

@Daniel Is there any mistake in the script? I am trying to verify my results obtained from your approach along with the results obtained from Blender's world_to_camera_view() and the results seem to be different.

@Tejus I just checked with the latest Blender version and it still seems to work. Some points to note though: The script uses "Computer Vision" conventions, so the coordinates you get will be between (0, 0) and (resolution_x, resolution_y) for points that project onto the image plane. Note that the x axis goes right, the y axis goes down. Blender's world_to_camera_view() will give values between 0 and 1, so you need to multiply those with  C.scene.render.resolution_x or  C.scene.render.resolution_y and  C.scene.render.resolution_percentage. Also, Blender's y goes up.

@Daniel I'm sorry, but your implementation is spot on. You're right about world_to_camera_view() giving values about 0 and 1. But its implementation in Blender versions <2.83 is wrong. They don't account for any horizontal/vertical shift in the camera. This issue has been addressed and fixed in the latest version (https://developer.blender.org/T74577).


text:
Help sculpting Malwiya mosque
I need help to sculpt the Mawiya mosque depicted below:
.
I tried to do that in Blender 2.81 but I couldn't bring the same spiral walking path. That is what I came out with:

I have used Cylinders to preform that but I was stuck with creating the walking path from the ground to the top of the mosque! I imagine that should be easy for an expert to do in Blender.

I think you can probably achieve what you're looking for using (mostly) the Screw modifier. Here are 3 approaches...
Method 1: Screw + Proportional Editing
I forgot to make sure the walking paths aren't partially above one another on the Z-axis in this approach, but I think it can be adjusted to get that right:
Start with a simple plane:

Apply a Screw modifier:

Then we'll apply the Screw modifier to the mesh, and get ready to use proportional editing to adjust the mesh's shape:

Next we'll actually do the proportional editing. Note that I'm doing this with Shift+Z (to only edit the width & length, not the height, of the structure), that my proportional editing circle-of-influence is quite large, and that I've set the Pivot Point to my 3D cursor (which is set to a position in the center of the structure's X-Y plane):

This process leaves an open hole in the center of the structure, so I then added a single cylinder to fill it in. I think you'll probably need a separate cylinder for each layer, but the same basic idea should work:

Method 2: SimpleDeform + Screw + SimpleDeform
We start with a plane in the same setup as in Step 0 above (not shown here). We can then add the 3 modifiers in the title of this method, with setting as given below, and get a reasonable facsimile to the Malwiya mosque's structure:

You may then want to apply modifiers and edit this, but it seems like a good starting point for the desired structure. To give a little bit of intuition for why this particular modifier stack seems to work: I started by observing that the Malwiya mosque looks like, well, a screw, except that its walkway's radius tapers off as you approach its summit. Simple deform gives us the option to taper (either before or after the Screw, or both, as we did here), and so playing with a few combinations of these two modifiers seemed natural.
Method 3: Archemedian Spiral with Extrusion
I couldn't quite stop playing with options, so here's a third one: you should be able to pretty easily generate the desired shape using a curve to model the desired spiral, adding Bevel & Taper objects to get the desired walkway shape/height, and finally filling in any gaps with cylinders or other objects as appropriate.
In particular, there is a very nice "Archemedian Spiral" object available for free (though I believe you have to turn on the "extra objects" add-on to see it):

If we add a Bezier curve with 3 points as the Archemedian spiral's Bevel object, then we can play with it a bit to get a nice basis for the kind of spiral walkway that wraps around Malwiya mosque:

You would then probably want to rotate this a bit to get the walkway to angle in the same fashion as in your image, and convert it to a mesh and extrude the geometry to fill in empty space.

You could use two of the shipped add-ons help you make the basic structure in a few steps:

Activate the add-ons 'Add Curve: Extra Objects' and 'F2'.
Set your snap to 'Vertex' and 'Active'
Create a Curve > Curve Spirals > Archimedean, and adjust the settings to the outside profile of your tower
Header > Object menu > Convert the curve to a mesh
In Edit Vertex mode, with all selected and a  convenient vertex active, EZ extrude the walls upwards, snapping the active vertex in Z to the one above it
In Edge Mode, select the opposite sides of the bottom section of the pathway and hit F
Select the upward edge of the new face, and hold F down until the pathway is filled.

Thanks @Robin your method worked for me so far http://prntscr.com/ptzz5h however I couldn't add a subdivision surface to enhance the smoothness of the Malwiya as when I add it the whole building gets distorted!  http://prntscr.com/ptzz5h why is that?

Hi @Robin, sorry for that ;-) http://prntscr.com/pu51zz. hmmm, would the loop cuts fix that issue? I will give it a try

Ok @Robin, I have tried that also and it didn't help that much.

Hi @Robin, Actually the loop cuts with the shade smooth made the trick,  but without adding the subdivision surface. check it here:  http://prntscr.com/pu5lii

@Omar it'll be  a question of your topology, so wireframe would need to be visible, Yes, loop cuts/bevels.. and have a look for duplicate vertices in there (select all, alt-M, merge by distance)


text:
How to create a galvanized pipe with a twist?
How to create a twisted pipe like in the picture below? I've tried using curves, bezier, point and circle but no luck. Perhaps I am just doing it incorrectly.

Add an Archemedian Curve spiral and edit its parameters.

Extrude on Y and change Mean Radius of 4 vertices.

Add some Bevel Depth.

Add and edit another spiral.

Copy on the other side, right click > Convert to Mesh, add materials and lights.

Thank you so much to josh sanfelici for taking the time to provide this helpful answer! Really appreciate this community!


text:
Getting water out of the canoe!
I have a canoe(s) in my scene. The water is represented by a low poly plane. Of course when the canoe is in the water the plane cuts into the interior of the canoe. How can I organise to have it where there is no water in the canoe. I couldn't find anything on youtube. Just point me in the right direction. Cheers

Try adding a Boolean Modifier to the plane, and use the canoe as the object, selecting Difference mode

Here's an example:


text:
Blender 4.1: background image: not visible
So ...
I followed this video: https://www.youtube.com/watch?v=3PoEVlObMv0
I opened a brand new project to try it, since in my previous project I got troubles.
nothing ... I'm not able to get the JPG as background.
Where do I wrong? Here below, inthe animated GIF, what I'm doing.

Hello ! You just missed what the tutor did at 6-7 seconds which is going into camera view mode. See the answer

@Gorgious even this: it's not clear to me form the video. he gave it for granted that "everybody knows" but it's not the case. "Kid with glasses" answered and helped on this.

The background image is only available when the viewpoint is the camera. To view the background image you can either push [0] on the number pad, or you can click on View - Viewpoint - Camera. Also, please note that the background image is supposed to be more of a reference image for modeling, painting, etc. See Blender Background Image Documentation.
You can add a reference image that is viewable outside of the camera by pushing on the Add button, selecting Image, and selecting the type of image import you would like. Unless you have the "Import images as planes" addon selected, the image types in the menu will only be viewable in the viewport, and not the render.
If you wish to have an image as the actual background in the render, make (or go to) the shading window. From there select World from the top left of the Shading tab. It is in the "Shader Type" drop-down. Delete the Background node and make a new "Environment Texture" node. In that node, select your image with the Open button. That should apply it as an HDRI (a panoramic image often used for 360 degree lighting). It will only be viewable in the viewport when you switch to Rendered view, or you switch to Material view.  If you chose material view, click on the down arrow next to the render view options and select Scene World under the Lighting category.

Great for the camera.. By pressing 0 indeed I got it. Thank you
But for the World option: there I have the same effect: no image. I tried different sizes, format but nothing.

Ah, sorry about that. I'll update my answer.


text:
How To Recreate The Bullet Time Slow Shutter Effect From Fight Club?
There is a scene in Fight Club that I won't link to as it is very NSFW and I'm sure that's not allowed here, but it is a bullet time sequence done entirely in CGI that features a very original simulation of a slow shutter speed that you would get in an actual camera for a photo. I have obtained the actual steps it took for the VFX studio to achieve these shots from someone that worked there, but for the slow-shutter effect they programmed their own piece of software. I found something close for Blender but it utilizes multiple cameras and that isn't quite the effect, as it is influenced by the animation of the characters. Here are the steps:

Early version of what we would think of as photogrammetry / scans today for the people.

Bodies are mostly unlit textures with baked lighting.

Bodies have basic deformer rigs with a single animation arc between 3 or 4 poses.

A script runs at render time to change the rig animation (not camera) to make the renderer think it moves really far on an arc over the course of the blur shutter. Imagine over the shutter blur samples the whole body rig is animating from the normal frame 0 to frame 100, and you did 100 samples cross your blur, on each frame. So you see the full blurred animation, every frame.

Camera shutter blur is cranked way higher than normal.

End result is this cool blur effect where it looks like they are in bullet time every frame.

So it's pretty straight forward except for Step 4. Is this possible to do in Blender using Python? Thank you again for your continued help and support.
Example Shot From The Movie:


text:
Geo Node Instanced Objects Cannot Both Have Materials
I followed this tutorial series to create a rigged wing with geo nodes. The setup is beyond my expertise, and I've encountered an issue. I have two different feathers with two different materials, but only one feather when instanced in the setup is actually visible with it's material while the other feather's material is turned invisible. I assume this has something to do with the attributes, but there are so many I don't know where to start. I even added Set Material in all four node setups but that just flipped which feather is visible and which is not. I'm including the blend as the deeper geo node setup is too complex for me to get a good screen grab of.

Blend File

I received this solution from Blender Artists:
"It has to do with your UV maps (which are, yes, attributes).
You have two maps: FeatherMap and SmallFeatherMap.
Right now feather materials refer to Texture Coordinate > UV, which means it picks whichever map is set to Active (represented with “camera” icon in UV Maps) from the list.
The “small feathers” are basically unwrapped in FeatherMap, and vice versa, meaning the “map” is a tiny point in the corner of the map (where the texture happens to be invisible).
Either rename the maps to have the same name (which is probably a preferable solution, if you don’t actually use two different maps in the same material).
OR specify maps in Shader Editor with Input > UV map node."


text:
Blender 2.80 - Image Editor - how does Set Curves Point work?
I have found two Set Curves Point entries in the keymap in the Image section in Blender 2.80.
Only the mask mode provides curves in the image editor. But here the hotkeys does exactly nothing. And we seem to have a key overriding problem here anyways. Since with ctrl + lmb you paint a freehand curve already with Mask add vertex and slide. Also a hotkey only functionality, to find in the keymanager.
Searching in the Blender Manual did not lead to any success. Only the Python API has a thin comment. This seems to be an old functionality, i have found the corresponding entry also in the 2.78 API.
bpy.ops.image.curves_point_set(point='BLACK_POINT')
Set black point or white point for curves

So we paint black or white points at curves. But how? Under what circumstances?
How is Set Curves Point meant to work?

Sometimes it's best to ask the developers directly. Thanks for the explanation.
This hotkeys is to pick the color under the mouse, and set the black and white level values in the curves sub panel in the Color Management panel.
To see the result you need to tick View as Render in the Image Panel in the sidebar.


text:
Fix triangular lighting artifacts
I'm trying to make a sword, but I ran into some weird shading on one portion of the blade.

Any ideas for the reason for this shading? Thanks!

Avoid having triangular faces when working with subdiv

Triangles are notoriously difficult to shade. Unfortunately, EVERYTHING gets turned into triangles by the renderer before rendering happens. Consequently, long, thin quads are also notoriously difficult to shade... because they're actually triangles once they get rendered.
Firstly, turn any triangles into quads. The renderer has a much easier time knowing which direction the quad should be split so that the triangles get smoothed the right direction, than it does trying to figure out which direction your triangle is supposed to be smoothed (without having come from a quad).
Secondly, make your quads as square as possible. It's not always necessary to make them perfectly square, but if you can add a couple of edge loops to make them shorter, that will probably help.
Lastly, (and I doubt this is the problem, but it's worth checking) recalculate your normals (ctrln or Mesh -> Normals -> Recalculate Outside) to make sure they're all facing the same direction.

Without knowing the purpose of your mesh (still render, animation, game asset, 3D printing) I just list the obvious problems here.

You have double vertices in your mesh.
You use flat shading on a non-flat surface.
You should activate the clipping option in your mirror modifier.
Instead of flat shading you should use sharp edges and an edge split modifier.
The normals face inwards.

Overall, you should start with simpler shapes and raise the density later on by using a Subsurf or Multiresolution Modifier. If you have a mesh with a convex or concave surface, different mesh densities on the object almost always result in shading problems. This happens due to the fact that even a slightly bent surface will produce a visible line, no matter what shading method you use.


text:
How to change root (first) bone in armature
This seems like a common question but I can't find anyone talking about it.
I made a very complex armature, spent a couple days on it, only to realize the root bone (I call handle) is in the wrong place. It is in the middle of the spine, I want the "butt" bone to be the new root bone so that I can bend the spine normally. Messing with parenting in edit mode doesn't seem to work or is too complicated for me.
Here is the .blend file:

And a screenshot:

How do I fix this ?

It will be impossible to answer this without the blend file I'm afraid. Could you please upload it to http://blend-exchange.giantcowfilms.com/ ? From a screenshot no one can really judge which bone is the parent of which, etc. The rig itself should do, you don't have to implement a mesh.

It might be in the armature tab of the properties panel and then perhaps a field to set the name? But I don't have access to Blender right now to confirm.

Ok, I added the .blend file. The problem is when I bend the spine both halves of the body bend around the "handle". I really wouldn't have realized until after I made the mistake.

Seems like a common problem.....I guess not ?

Just “add bone” from menu to add a new bone that isn’t the child of anything. Then Ctrl+P make it the parent of the existing root and choose “keep offset.” The root is “the bone that has no parent.”

that doesn't change the root there is a point that looks like a compass with a circle in the middle and 4 lines around it pointing up down left and right that is the root question is how do we relocate it to another place without moving our character or any bones but to make it the new point which all else moves around, I have the same problem
thanks

You can evaluate if its worth erasing the root and his child bones, until you reach the bone which you want to be the root. This work for me in a horse armature in which the root bone was the last tail bone and I wanted an spine bone as the root.


text:
New edge does not split face
I subdivided a face. I then connected the newly added vertex to an existing vertex by selecting both vertices and pressing F
The now newly created edge crosses an existing face, but the face is not partitioned by the new edge (as can be seen in the screenshot below). So, I obviously did something wrong.

So, my question is: how do I split the existing face in two right where the edge is?
P.S.
I'm reaaly new to blender so I don't know the correct terminology to search for; I hope this question is not answered here already.

Delete this old face. Select all the unconnected edges and press F to make a new face. This will fix the current situation. Otherwise, before creating the edge use the knife tool to cut the face. The knife tool can snap to the vertices which you want to connect.

Thanks for the super quick comment, it worked. Maybe expand your comment into an answer so I can accept it.

@Duane Dibbley, your solution works a lot faster than deleting a face, with all the possible complications it implies. Post it as an answer. :o)

By selecting the vertices and pressing F you are simply creating a new edge. The faces connected to the vertices are not changed, this behaviour correct.
In this position, delete the problematic face.Select all the vertices and/or edges, which need to be fill and press
F to fill them with new faces.
Alternatively, before creating the edge which intersects the face, press K to cut the face with the Knife Tool. The knife tool can snap to the vertices along the faces' edge.

F will create non-manifold (bad) geometry. In practice, if J cuts the edge you want, use it. Use F to fill in new geometry. Use J to modify existing geometry.

Providing keyboard shortcuts without saying what the shortcut does is not very helpful for new users. What does "J" do?  If you don't explain your answer, they'll just be back the next time they have the same problem but don't know that the same solution applies.

 J instead of  F works perfectly for this.
Select the vertex you want to divide with and press  J.

Hi, thanks for the post. This site is not a regular forum, answers should be substantial and thoroughly explain the solution and required workflow. One liners and short tips rarely make for a good answer. If you can [edit] your post and provide some more details about the procedure and why it works feel free to restore it, otherwise it may be deleted or converted into a comment. Perhaps add a few images illustrating the workflow and final results. See How do I write a good answer?


text:
AttributeError: '_RestrictContext' object has no attribute 'space_data'
I work at an addon that works with external icons. When I run the script from within Blender then all is fine. When I make it an add-on, and install it, and try to activate it, then I get an error:

AttributeError: '_RestrictContext' object has no attribute 'space_data'

The vital code part that throws the error is:
script_path = bpy.context.space_data.text.filepath

Why does it work when i run it inside Blender, and not as an addon?
The problem reduced to one icon button:
import bpy
import os
import bpy.utils.previews

bl_info = {
    "name": "Icon problem as addon",
    "author": "X",
    "version": (1, 0, 0),
    "blender": (2, 76, 0),
    "location": "",
    "description": "Test",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
    "category": "User Interface"}

# ¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸

def addon_button(self, context):
    layout = self.layout

    global custom_icons

    row = layout.row(align=True)
    row.operator("object.mode_set", text="", icon_value = custom_icons["icon_not_available"].icon_id).mode = 'OBJECT'

# global variable to store icons in
custom_icons = None

def register():

    bpy.types.VIEW3D_HT_header.prepend(addon_button) # Here we add our button in front of the View 3D header.

    # Our external Icons
    global custom_icons
    custom_icons = bpy.utils.previews.new()
    script_path = bpy.context.space_data.text.filepath
    icons_dir = os.path.join(os.path.dirname(script_path), "icons")

    custom_icons.load("icon_not_available", os.path.join(icons_dir, "NOT_AVAILABLE.png"), 'IMAGE')

def unregister():
    global custom_icons
    bpy.utils.previews.remove(custom_icons)

# This allows you to run the script directly from blenders text editor
# to test the addon without having to install it.

if __name__ == "__main__":
    register()

Go to the section marked Restricted Context here https://wiki.blender.org/index.php/Extensions:2.6/Py/API_Changes  You prob don't need script_path = bpy.context.space_data.text.filepath in an addon anyhow?  For an addon consider using icon_dir = path.join(path.dirname(__file__), "icons")  (path is os.path)

Well this line of code detects the script path, and so the path of the icons. How should the icon path be found without this? I tried to comment out the line, and made the icons dir to icons_dir = ( "icons"). The addon now loads. But then the icons doesn't show anymore.

This is explained here: http://blender.stackexchange.com/questions/32335/how-to-implement-custom-icons-for-my-script-addon/32336#32336. You will find answers how to get the path for an addon and for running it within Blender.

And this is what does not work. I overlook something it seems :/ . Wouldn't it be easier to tell me the solution instead of linking me around? :)

I have already understood that bpy.data.texts does not work. But i still search for a working solution, the substitute for it. Also your linked solution does not work, it gives me a UnboundLocalError: local variable 'bpy' referenced before assignment at the line import bpy.utils.previews.

Thanks zeffi. I thought it is already reduced enough. But i will try to reduce it. Give me a few moments ...

Make it so it only tries to load / display one icon. The result of your reduction doesn't even have to be a useful add-on, as long as it attempts to display a single custom icon :) and then try to work the code linked to by Jerryno or the custom icons Template in TextEditor, or a working example add-on https://github.com/zeffii/mesh_tiny_cad

Thanks for the advice. The reduced example is up. I have edited the first post. Now i will try to follow the advice in your link.

@brockmann lol here's another one re  the confusion over that icons path from textblock question we edited a while back

The solution was as easy as replacing
script_path = bpy.context.space_data.text.filepath
icons_dir = os.path.join(os.path.dirname(script_path), "icons")

by
icons_dir = os.path.join(os.path.dirname(__file__), "icons")

Problem solved.
Full example script:
import bpy
import os
import bpy.utils.previews

bl_info = {
    "name": "Icon problem as addon",
    "author": "X",
    "version": (1, 0, 0),
    "blender": (2, 76, 0),
    "location": "",
    "description": "Test",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
    "category": "User Interface"}

# ¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸¸¸♫·¯·♪¸¸♩·¯·♬¸¸

def addon_button(self, context):
    layout = self.layout

    global custom_icons

    row = layout.row(align=True)
    row.operator("object.mode_set", text="", icon_value = custom_icons["icon_not_available"].icon_id).mode = 'OBJECT'

# global variable to store icons in
custom_icons = None

def register():

    bpy.types.VIEW3D_HT_header.prepend(addon_button) # Here we add our button in front of the View 3D header.

    # Our external Icons
    global custom_icons
    custom_icons = bpy.utils.previews.new()
    # Use this for an addon.
    icons_dir = os.path.join(os.path.dirname(__file__), "icons")

    # Use this inside a script
    #script_path = bpy.context.space_data.text.filepath
    #icons_dir = os.path.join(os.path.dirname(script_path), "icons")

    custom_icons.load("icon_not_available", os.path.join(icons_dir, "NOT_AVAILABLE.png"), 'IMAGE')

def unregister():
    global custom_icons
    bpy.utils.previews.remove(custom_icons)

# This allows you to run the script directly from blenders text editor
# to test the addon without having to install it.

if __name__ == "__main__":
    register()


text:
Add dupli_extrude_cursor to Extrude dropdown box
There are two items that are not in the UI, but just available by a hotkey. Dupli Extrude and Dupli Extrude Rotate.
I want them to be visually available in the Extrude dropdown box in the tool shelf in the Tools panel. So I added them to the submenu for it, which is in the space_view3d-py file, the class VIEW3D_MT_edit_mesh_extrude. And there I am stuck.
The operator is mesh.dupli_extrude_cursor. With a flag to tell if the target object rotates randomly or not. And this flag is the trouble maker here. I can add a normal button that way:
        col.operator("mesh.dupli_extrude_cursor" , icon='DUPLI_EXTRUDE',  text = " DupliExtrude    ").rotate_source = False
        col.operator("mesh.dupli_extrude_cursor", icon='DUPLI_EXTRUDE_ROTATE', text = " DupliExRotate  ").rotate_source = True

But when I do the same in the dropdown box menu then the whole Blender menu vanishes. VS marks me the whole code red then. I also tried to include the flag with the operator. But then Blender doesn't find it and gives a missing srna error in the console. I cannot leave the flag away, that's what separates the tools. And also curious, the dropdown box entry does not show the hotkey for it.
What's the right way to put those two items into the dropdown box?
class VIEW3D_MT_edit_mesh_extrude(Menu):
    bl_label = "Extrude"

    _extrude_funcs = {
        'VERT': lambda layout:
            layout.operator("mesh.extrude_vertices_move", text="Vertices Only"),
        'EDGE': lambda layout:
            layout.operator("mesh.extrude_edges_move", text="Edges Only"),
        'FACE': lambda layout:
            layout.operator("mesh.extrude_faces_move", text="Individual Faces"),
        'REGION': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_normal", text="Region"),
        'REGION_VERT_NORMAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_shrink_fatten", text="Region (Vertex Normals)"),
        'DUPLI_EXTRUDE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor(rotate_source = False)", text = "DupliExtrude"), # does not work, Blender does not find the operator
        'DUPLI_EX_ROTATE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor", text="Dupli Extrude Rotate").rotate_source = True,  # does not work, Blender Menu vanishes

    }

EDIT: I could of course add two helper classes. It works. See this example. But i am not a happy bunny with this solution. I want to add the operators in the way the other operators in this dropdown box are added too. There should be a solution.
class VIEW3D_MT_edit_mesh_extrude_dupli(bpy.types.Operator):
    """Duplicate or Extrude to Cursor"""      # blender will use this as a tooltip for menu items and buttons.
    bl_idname = "mesh.dupli_extrude_cursor_norotate"        # unique identifier for buttons and menu items to reference.
    bl_label = "Duplicate or Extrude to Cursor"         # display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # enable undo for the operator.

    def execute(self, context):        # execute() is called by blender when running the operator.
        bpy.ops.mesh.dupli_extrude_cursor('INVOKE_DEFAULT', rotate_source = False)
        return {'FINISHED'}

class VIEW3D_MT_edit_mesh_extrude_dupli_rotate(bpy.types.Operator):
    """Duplicate or Extrude to Cursor Rotated"""      # blender will use this as a tooltip for menu items and buttons.
    bl_idname = "mesh.dupli_extrude_cursor_rotate"        # unique identifier for buttons and menu items to reference.
    bl_label = "Duplicate or Extrude to Cursor Rotated"         # display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # enable undo for the operator.

    def execute(self, context):        # execute() is called by blender when running the operator.
        bpy.ops.mesh.dupli_extrude_cursor('INVOKE_DEFAULT', rotate_source = True)
        return {'FINISHED'}

class VIEW3D_MT_edit_mesh_extrude(Menu):
    bl_label = "Extrude"

    _extrude_funcs = {
        'VERT': lambda layout:
            layout.operator("mesh.extrude_vertices_move", text="Vertices Only"),
        'EDGE': lambda layout:
            layout.operator("mesh.extrude_edges_move", text="Edges Only"),
        'FACE': lambda layout:
            layout.operator("mesh.extrude_faces_move", text="Individual Faces"),
        'INDIVIDUAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_individual_move", text="Individual"),
        'REGION_VERT_NORMAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_shrink_fatten", text="Region (Vertex Normals)"),
        'DUPLI_EXTRUDE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor_norotate", text="Dupli Extrude"),
        'DUPLI_EX_ROTATE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor_rotate", text="Dupli Extrude Rotate")
    }

    @staticmethod
    def extrude_options(context):
        mesh = context.object.data
        select_mode = context.tool_settings.mesh_select_mode

        menu = []
        if mesh.total_face_sel:
            menu += ['INDIVIDUAL', 'REGION_VERT_NORMAL', 'FACE']
        if mesh.total_edge_sel and (select_mode[0] or select_mode[1]):
            menu += ['EDGE']
        if mesh.total_vert_sel and select_mode[0]:
            menu += ['VERT', 'DUPLI_EXTRUDE', 'DUPLI_EX_ROTATE']

        # should never get here
        return menu

    def draw(self, context):
        layout = self.layout
        layout.operator_context = 'INVOKE_REGION_WIN'

        for menu_id in self.extrude_options(context):
            self._extrude_funcs[menu_id](layout)

Can quite simply ap(pre)pend those operators to the menu
import bpy
def draw_dupli_extrude(self, context):
    col = self.layout
    col.operator_context = 'INVOKE_REGION_WIN'
    col.operator("mesh.dupli_extrude_cursor" ,  text="DupliExtrude").rotate_source = False
    col.operator("mesh.dupli_extrude_cursor", text="DupliExRotate").rotate_source = True
# prepend to menu
bpy.types.VIEW3D_MT_edit_mesh_extrude.prepend(draw_dupli_extrude)

NOTE: The operators are kind of useless in the menu as that's where the mouse is to invoke... which could be why they are not there in the first place.
Always look at system console for errors, as in your sample code there are no icons for
icon='DUPLI_EXTRUDE'
icon='DUPLI_EXTRUDE_ROTATE'

which will lead to a TypeError.

Thanks batFINGER for this working solution. I would still be happy though to have a direct way to put the dupli_extrude_cursor into the menu, already with the flag. But i guess there is really no way. - The point to have them visually available is to know that the tool exists, to show the hotkey, and to give a way to modify the hotkey. Border select for example is also a menu item ... - And sorry for the icon code. I've added those icons in my custom build here. There those icons really exists. Currently those two items are buttons. I will remove the icon code from the initial posting.

Hm. Still in trouble. The menu items does not show up that way. Most probably because of the extrude_options.

Added an image as "proof".  AFAIK ap(pre)pended draw methods wont be affected by the code in the original draw method.

Interesting. I wonder what i do wrong here :(

Okay, works in native Blender 2.77. The error must be in my custom build. I will find out where. Thanks :)

Have it. It works fine in Blender 2.77. But my custom build is 2.76 based. And in Blender 2.76 the menu items doesn't show up neither. Another riddle solved. I will stick with my upper workaround.

Edited screenshot to one taken from version  2.75.1, would think it would be same for well before too... 2.6 maybe even 2.5.  Remember to remove the non-existent icons if not a custom build.

It stays curios :D I tried with native 2.76b at the native space_view3d.py, and it did not work. So icons  or custom code was definitely not in the way. I have no clue why it doesn't want to work in 2.76. In 2.77 it works :)

authors: Игорь Леденев

authors: Станислав Лейнерт


text:
Python - how to make a BoolProperty local?
I need subtabs. I have several settings and elements to hide. So i made me a BoolProperty and two subtabs with it. The problem is, this BoolProperty is global. Means when i open one subtab, then the other subtab opens too.
My problem is that i have more than one panel where this subtab could be. Think of the background images tabs in the properties sidebar where you can have more than one panel. One for every new background image. Now think that you have a subtab at each of them. And then all of them opens when you click at one of it. That's the kind of problem that i have at the moment.
Is there a way to make the BoolProperty local? So that just one subtab opens when i click at it?
I want the subtab BoolProperty to be unique per instance. Something that can be reused where ever you need it in the UI. A good example is again the Background Images tab where you can close every panel individually.
Code:
import bpy

class MyData(bpy.types.PropertyGroup):
    subtab_bool = bpy.props.BoolProperty(name="A checkbox", description="Do this or that", default = False) # Our prop

class SubtabProp(bpy.types.Panel):
    bl_label = "Subtab prop"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'

    def draw(self, context):
        layout = self.layout

        scene = context.scene # Our data is in the current scene

        if not scene.my_addon_data.subtab_bool:
            layout.prop(scene.my_addon_data,"subtab_bool", emboss=False, icon="TRIA_RIGHT", text="- Settings -")

        else:
            layout.prop(scene.my_addon_data,"subtab_bool", emboss=False, icon="TRIA_DOWN", text="+ Settings +")

            layout.operator("mesh.primitive_plane_add", text="Plane", icon='MESH_PLANE')

        if not scene.my_addon_data.subtab_bool:
            layout.prop(scene.my_addon_data,"subtab_bool", emboss=False, icon="TRIA_RIGHT", text="- Othersettings -")

        else:
            layout.prop(scene.my_addon_data,"subtab_bool", emboss=False, icon="TRIA_DOWN", text="+ Othersettings +")

            layout.operator("mesh.primitive_cube_add", text="Cube", icon='MESH_CUBE')

# ---------------------------- register

def register():
    bpy.utils.register_class(SubtabProp)
    #Our data block
    bpy.utils.register_class(MyData) # Our data block
    bpy.types.Scene.my_addon_data = bpy.props.PointerProperty(type=MyData) # Bind reference of type of our data block to type Scene objects

def unregister():
    del bpy.types.Scene.my_addon_data # Unregister our data block when unregister.
    bpy.utils.unregister_class(MyData) # Our data block
    bpy.utils.unregister_class(SubtabProp)

if __name__ == "__main__":
    register()

Not exactly. I want the subtab boolproperty to be unique per instance. Something that can be reused where ever you need it in the ui. Editing the question once more ...

I fear i miss the skills to describe the problem more clear than how it already is described. Even more because my mother tongue is not english. I basically want to work with a local variable instead of a global one. Something that should work in any language. Thus my confusion here.

@zeffi, i have understood that it doesn't work that way with a BoolProperty. What i search for now is the substitute. A solution that can have different local states. But yes, maybe i really run into a Blender Python limit here, and the problem is unsolveable. Nevertheless thanks for your patience and help :)

Within the one panel you will need multiple BoolProperties (And you should update your snippet to reflect that you understand that)..and then we can move on to another problem . namely, finding a convenient way to register a PropertyGroup/Collection per visible 3dView (to get the same effect as the BackgroundImages tab you mention)

@zeffi, i don't understand. How could i update my snippet with the solution that i ask for? For that i would need the solution ...


text:
UV Unwrap at seams gives unexpected result
I'm trying to learn UV unwrapping.
I've an object where I marked the seems. When I UV unwrap it, some (planar polygon) faces unwrap in an unexpected way:

It appears blender detects something that is not there.
What causes the distortion and how do I get rid of it?
Is this because I use polygons (all polygons are planar) instead of triangles?

Update
I posted the .blend file on blendexchange:

It seems you didn't add a seam across the length of your model.
This would help you to control the unwrap a bit more.

I unwrapped your model again and the other side also gave the same result. Then I tried Smart UV Project and all your shapes came out nicely. In conclusion I think you are better off doing the Smart UV Project instead of the standard Unwrap and as far as why the standard unwrap does this, I think it's because of the way Blender's default unwrap algorithm works.
Hope this helps

It looks like you have an extra face there. Try deleting the face and see if it clears up. Ideally you want to make sure you limit your ngons. You can always fill that area (Ctrl+F), then convert the face to triangles (Ctrl+T), then convert to quads (Alt+J). That's a quick way of getting rid of ngons.

Is there a method to 'see' the extra face?


text:
Denoising in Blender results in a black screen (Render layer node is connected)?
So I've seen a lot of people complain about their experience using the compositor. Usually people forget to actually connect render layers to the output. However, I have not forgotten this, yet it still turns black sometimes. Not always, but not at predictable times. Has anyone experienced this issue?
Also, connecting the render layers directly to composite results in a perfectly fine image. It is only when connecting to the denoise node that the screen jumps to black. I use Blender 2.82a.

Hello :). There was a very similar question recently https://blender.stackexchange.com/q/174063/. Perhaps it's a bug in 2.82?

I'm thinking it might be yes. I'm sorry I really did search for similar questions but I missed that one.

Well, you can report it as a bug through Help > Report a bug in Blender :).

I will, thank you for your help.


text:
How to select vertices on the left side of a plane using python?
I would like to select only the vertices on the left side of my plane using Python (like on the screeenshot), does anybody have an idea how to do it ?
I try the following to get all vertices but i'm unable to isolate those on the left.

My actual code to get all the vertices:
bpy.ops.import_image.to_plane(
  files=[{'name': os.path.basename(file)}],
  directory=os.path.dirname(file)
)
obj = bpy.context.object
group = obj.vertex_groups.new(name = 'Group' + str(number))
index = 0
verts = []
for v in obj.data.vertices:
    verts += [index]
    index = index + 1
    print(v.co)
group.add(verts, 1.0, 'REPLACE')

You need to somehow define what is 'on the left side'. Is it global space, is it local, which way you are looking from?.. Anyway, you can compare the coordinates to something. Let's say you are looking from the top as in the screenshot and left is the most negative X point of the object in global space plus 0.5 units:
import bpy

obj = bpy.context.object
data = obj.data

the_matrix = obj.matrix_world

on_the_left_side = (the_matrix @ obj.data.vertices[0].co).x # have to start somewhere

for v in data.vertices:
    co = the_matrix @ v.co #Let's say "on the left" is in global space
    if co.x < on_the_left_side:
        on_the_left_side = co.x

offset = 0.5

#Element selection is a bit weird in bpy - you can select faces,
#but not vertices for example like user cannot, so let's deselect
for e in data.edges:
    e.select = False
for f in data.polygons:
    f.select = False

for v in data.vertices:
    co = the_matrix @ v.co
    if co.x < on_the_left_side + offset:
        v.select = True
    else:
        v.select = False

I wasn't very clear about the space indeed. It was local space i think. I tried your script and it works well to get my selection. Thank you very much. I would like to put those selected vertices in a new vertex group (group.add(verts, 1.0, 'REPLACE') in my previous code snippets. Where can i put these part in your code ?

Read: https://blender.stackexchange.com/a/145975/31447 @NicolasSouthside If this solved your issue please accept the answer. How this site works: https://blender.stackexchange.com/tour

@NicolasSouthside add this line bpy.ops.object.mode_set(mode = 'OBJECT') and this line group.add([v.index for v in data.vertices if v.select], 1.0, 'REPLACE') at the end of the script. Don't forget the line from your answer where you create the vertex group.

You can always suggest an edit @Gorgious


text:
How to apply a glass shader on my imported geometry?
I'm new to Blender so I'm doing all my modelling in Maya and transfer to Blender using wavefront obj. I have create a simple wine glas, no texture applied, just geometry. I can apply color to it but when I increase the transmission value nothing happens.
Do I need to import my .mtl file? Tried to unwrap the UV's as well.

Assuming you are using the Eevee renderer.
Go to Properties Editor > Render Properties tab and check Screen Space Reflections as well as Refraction. It brings a glass look to your material.
With Glass object selected go to Shader Editor > Properties panel N switch to Options tab and check Screen Space Refraction.
This enables other objects visible behind glass.


text:
How To Use Force Fields In Geometry/Simulation Nodes? [W/ .Blend]
I apologize if this is obvious, but I'm still learning Geometry nodes and I'm stuck. I built this node tree from a video on YouTube, and what I have it doing is behaving like snow particles blowing away from a mound of snow. I figured out how to integrate gravity into the particle simulation, but I'm stuck trying to find a way to use a wind force field object to blow the particles off to the side. I know I can use the vector node that is making the gravity, but I want it to be more dynamic and easily controlled than that. Thanks for the continued help and support!

You can edit your question, you don't have to delete it and ask again. Your first screenshot is still illegible. And as I said the last time - wind is just a force like gravity is. You say you figured out how to integrate gravity.  Now do the same again but with values for X and Y instead of Z. I cannot give you example values because I don't know how much you want the wind to blow in which direction (hint: the axis in which direction you want the wind to blow is where you have to add or subtract something).

@GordonBrinkmann Hey Gordon, thanks for helping me again. I deleted my old post and reposted because it was downvoted and buried now. I just wasn't sure if providing the blend would help any. I did make a cheat way to use the wind force object, but it only used the location to determine the direction the particles move. If there's no real way to integrate it, I'll just use my Vector values.

The method of closing and opening duplicate questions will only lead to more downvotes in the future when people perhaps already commented and get annoyed to have to do it again and again... Anyway, Geometry Nodes is not a physics engine, that's why you cannot integrate existing force fields and for the same reason you have to create a gravitational force by yourself as well.

...of course when I say you cannot integrate them I mean as a physical force. You can still use them with an Object Info node to get their location, rotation etc.

@GordonBrinkmann Gotcha, so I already reached the extent of what I can do. I assumed since Simulation Nodes exist now, it would incorporate like, the things that get used for simulations, but I imagine that's in the pipeline down the road somewhere.

Well, but the name Simulation Nodes does not mean it incorporates simulations outside of Geometry Nodes. Just like a Rigid Body simulation is not affected by a Fluid simulation as another example. The different physics engines do not (or only to some extent) work together. And the Simulation Zone is not even a physics engine. You only "simulate" movements in geometry by mathematical operations that you can (or rather have to) define manually by yourself.

@GordonBrinkmann Ohhh, I see. I was wondering why I had to use Vector Math to mimic physics, I thought I was missing something. So what is the extent of Simulation Nodes? I thought they were meant to replace the Physics tab, but it's more an addition to what Geometry Nodes do?

The Simulation Zone allows to have the result of one frame influence the next frame (similar to a physics simulation), what was not possible without it. Before, calculations could be based on the frame number but were independent from previous frames. I hope you get an idea now. The comments section is not intended for long discussions or chatting.


text:
Are Advanced Snow Simulations Now Possible In Blender 4.0?
I am creating a little Eevee animation of a baby duckling popping out of snow and going for a stroll. I know dynamic paint can make footprints, but when the duckling pops out of the snow, I want a little clump of snow on his head to remain for a second and then crumble off of him. I found people asking for this in previous versions and there didn't seem to be much possible without buying add-ons. Now that we have simulation nodes, is this actually possible?
Here is a sample of what Disney did for Frozen that I am going for, particularly the bottom right:

Looks like molecular addon has been used, you can get it here https://github.com/scorpion81/Blender-Molecular-Script/releases. But it is look a bit outdated

@Crantisz Yeah, I spotted that, but I can't find solid examples of it working. There's a couple videos that are 10 years old that are very voxellized and then one that is more recent but it is not a good example. If there are no other options, I'll give it a try.

For footprints in snow, I recommend the following video tutorial: https://youtu.be/HMpKmzTGwiE?si=9grCbxvRQf68YVlX I wouldn't say that snow simulation with nodes is impossible, but I have to be honest it's not user friendly in its current form. Not something I'd recommend to take on as a project unless you're advanced at using simulation nodes. If I was to tackle your particular shot (snow falling off the head of a small duckling) I'd say that simulation is overkill. You could easily achieve your shot with simple keyframe animation - fracture your object into clumps (studying your reference fo

I found this video that with some modifying makes a dissolving clump of snow that turns into particles that is controlled by an empty. I think it's the best current solution in Blender for the effect I was going for. https://www.youtube.com/watch?v=pD5_d0r4yv4&list=PLrlvL_yQcl5cPYysRArmQkDGR2DzO6dCR&index=59


text:
Using Object Info/Random Node To Change Snow Mask Per Instance
My journey into rendering snow continues, this time I'm using the Object Info node for the first time to randomize how much snow is on a tree model per it's instances. I nearly have it down, except I can't figure out how to prevent the trees from being completely white or have no snow at all. I started with a Color Ramp, but I think random just selects one of the colors that is in the Color Ramp? So I added a Map Range node, which almost fixed it, but when I get rid of a white tree, it makes the others have no snow, and vice versa. I tried a Math node after the random node, but that didn't seem to be the answer, either. I have a feeling I'm just missing the right node to put in here, so I welcome all of your immense knowledge. Thank you for your patience, and helping me, even when I'm helpless.

Blend File

The object info random output creates a differnt number between 0 and 1 for each object the material is assinged to.
Your map range node is starting at 0.2, I think what you want is the to min to be 0.2, to get a result between 0.2 and 1.
However that still would not solve the problem, since the map range node is just a monochromatic colorramp that computes faster, so having both is redundant.
My guess is that the outgoind color from the ramp is the amount of snow you're rendering. If you don't want any trees to be completely white, or don't have snow at all, simply don't choose black or white with any of the stops.
or: easier, but less control: set the map range to:

from min: 0
from max: 1
to min: 0.2 (min amount of snow)
to max: 0.8 (max amount of snow)

now take that value and multiply it with the z channel (blue) and you should get adjustable amount of snow.
Awesome solution from someone else:
https://pantarei.xyz/posts/snowline-tutorial/

Thank you, I now have a better understanding of the Map Range node! You are right, the output determines where the snow appears. However, I seem to be doing something wrong because there's no longer variance between the trees. I tried doing the Multiply with the Blue channel from the Separate Color node with the Map Range coming from the Geometry node, and then I tried doing the multiplication after the Add and Map Range node and same thing:  Current Setup


text:
Flip Fluids - Settings For Volume Force Field To Turn Fluid Back Into Object?
I'm still learning Flip Fluids, I've been reading through the docs and watching YouTube videos but the settings I try don't remedy what I'm looking to do. I have a vape object, and it liquifies up through the air on a curve, and I want it to come back around and be drawn back into the vape shape. I have a volume force field of the object set up but when I activate it, depending on the strength, it either turns the fluid into a tiny glob, a bunch of tiny globs, it just disappears, or it goes right through it or gets pushed away. I tried a demo scene to make sure it would work first, and it did, so I'm not sure if I have a setting wrong elsewhere in my setup that is causing this issue. My CFL is set to 1. I've been able to try several things as it only takes an hour to bake on my machine, but it's at the point where it's glitchy like this so I'm seeking help. Thank you.
Before Force Field Activates

After Force Field Activates


text:
How to turn a linked group into independent objects?
I created a group and added objects to it,
then Add -> Group Instance. How to turn this linked instance into
a completely independent, ungrouped "deep" copy of the objects in the group?
I've tried the options I get by RMB on the outliner, to no avail.
PS: I need this to export collada; the exporter code won't output the objects within a group if they're linked/instantiated from another scene.

You can make objects instantiated by group to be real ones.
While group instance selected, execute Make Duplicates Real operator (or press Ctrl+Shift+A if in 2.79 or prior) to make objects from group as real ones. You can now deal with them as with meshes, because they already are.
Then you can run Make Single User operator from Object menu (or press U > Object Data if in 2.79 or prior) to make these objects use their own mesh datablock (if there is needed possibilty to edit them individually).

While this will work, it has it downsides:
Pros

Make objects from group finally editable (sometimes may be useful)

Cons

Additional geometry will be added that can lower scene processing or rendering time.
Additinal objects will appear in Outliner (if objects were made to use their own mesh datablocks), so in case of there are many objects in the scene, you may want to avoid this so not to slow down 3D View.

minor suggestion: you meant lowercase U key.

This works. PS: the first step is already enough for a collada export to include the data. The second step of making the link data local just duplicates the data in the export which may be useful for locality and individual edits, as mentioned.

whats the menu action of ctrl + shift + a ? Probably the shortcut is different now in blender 2.8 ?

@igrek in 2.8 most of shortcuts from previous versions were dropped. This operator though has its shortcut In 2.8, now it's Ctrl+A (same as for applying transform)


text:
Show panel, only when a collection is loaded
How to show a panel, only when a particular collection exist (or appended)?
Here a bit more explanation of what I am aiming for in case the question is not clear:

In the screenshot above you see there is a panel called 3point light Ctrl. What I want is that the panel "3Point Light Ctrl" only shows up after the user clicked on "Add 3 Point Light" in the "Add to scene" panel.
Often I see a poll function in other addons like:
@classmethod
    def poll(cls, context):
        return context.active_object is not None

And so I thought I could do it as follows:
@classmethod
    def poll(cls, context):
        return return bpy.data.collections[“ThreePointLight”]

But that doesn't work, and I realize it is expecting context, not bpy.data.  Any idea how I can do this?  (It's for Blender 2.80).

You are going to want to use python's membership operator: in
@classmethod
def poll(cls, context):
    return "ThreePointLight" in bpy.data.collections

Using bpy.data.collections[*name string*] would result in an KeyError in the event the name does not exist.

Would be a  KeyError if the name doesn't exist. Could also use collection.get(key) is not None

@proxeIO That was the trick. That makes it quite easy to make a dynamic menu.  Thanks!  See answer: return "ThreePointLight" in bpy.data.collections

@batFINGER Corrected