text:
How can I print the string of a parameter from a property?
Let's say I have this custom property fu3dm_model_gender: bpy.props.EnumProperty(name="Gender", description="Choose model's gender", items= [('OP1', "Male", ""), ('OP2', "Female", "")], default='OP1') and I want to print the string of name parameter. How can I do this?
UPDATE
Actually, my property is part of an operator. In the following example I'd like to get the string of name parameter and display it where the three X's (XXX) are:
class fu3dm_WM_OT_Model_Prefs_Operator(bpy.types.Operator):
    bl_idname = "wm.fu3dm_model_prefs"
    bl_label = "Model Preferences"
    bl_description = "..."

    fu3dm_model_gender : bpy.props.EnumProperty(name="Gender", description="Choose model's gender", items= [('OP1', "Male", ""), ('OP2', "Female", "")], default='OP1')

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)
        bpy.ops.wm.fu3dm_model_prefs('INVOKE_DEFAULT')

    def draw(self, context):

        layout = self.layout

    # BODY PREFS BOX - START
        box = layout.box()
        col = box.column()

        row = col.split()
        row.label(text=XXX)
        row.prop(self, "fu3dm_model_gender", text="")
    # BODY PREFS BOX - END

    def execute(self, context):
        pass
        return {"FINISHED"}

Yes. Once registered you can use bl_rna.properties to access the name, its type, the items, the description etc... I'd suggest use the python console to test:
>>> test_items = [
...     ("RED", "Red", "", 1),
...     ("GREEN", "Green", "", 2),
...     ("BLUE", "Blue", "", 3),
...     ("YELLOW", "Yellow", "", 4),
... ]

>>> bpy.types.Scene.my_enum = bpy.props.EnumProperty(name="Foo", items=test_items)
>>> bpy.types.Scene.bl_rna.properties['my_enum'].name
'Foo'
>>> bpy.types.Scene.bl_rna.properties['my_enum'].enum_items[0]
<bpy_struct, EnumPropertyItem("RED")>
>>> bpy.types.Scene.bl_rna.properties['my_enum'].enum_items[0].name
'Red'

In case of an operator property, I'd suggest read the values from the operators annotation dict:
class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    my_prop: bpy.props.StringProperty(name="foo")

    def execute(self, context):

        # via bl_rna
        print (self.properties.bl_rna.properties['my_prop'].name)

        # using annotations
        print (self.__annotations__.items())
        print (self.__annotations__['my_prop'][1]['name'])

        return {'FINISHED'}

Hm... I didn't get it!!! Maybe I described it wrong. Can you please take a look on my question again? I updated it...

Yep, your description was not precise enough @SimonetosTheGreek

Yes I am sorry!!! So, if you have some time more, some clarifications so to understand 100% what I am learning and not just copying code. When do we use the bl_rna way? In self.__annotations__['my_prop'][1]['name'] why do we use 1 and not 0since name is the first parameter?

Basically a python question - the second item is dict we are looking for. Recommend make yourself familiar with dir() -> print(dir(self.__annotations__['my_prop'])) @SimonetosTheGreek

Thank you for your time!!! :)

You're welcome @SimonetosTheGreek


text:
Disable resize gizmo of area light in viewport?
Every time I try to transform an area light I end up clicking on the edge of the light icon and resizing it. This is really messing with my workflow. Is there a way to disable this behavior? I want to control the light size through the parameters only.
How can I disable area light resize gizmo in the viewport?

You can either disable the 'Size' gizmo under 3D View > Viewport Gizmos > Lights or just turn off all Viewport Gizmos temporarily by using the Show Gizmo switch (Ctrl`) in the header of the 3D View:

Alternatively I recommend try to get used to g and r hotkeys to transform the light, it's just faster. In terms of workflow, I can also recommend to transform the light from the lights perspective by temporarily making it the actual viewport camera (Ctrl+Numpad 0).

I am not sure what is going on here. I answered my own question yesterday. Did you edit my answer? Where did it go? So bizarre.
Anyway, thanks, I had figured it out already. The G and R hotkeys are not going to work for me. I find transforming things without a cursor to be very non-intuitive. This is one of my least favorite things about Blender. Constantly being dumped into a mode where there's no cursor on the screen, but the mouse controls the position of something until the user makes a click. Like make a duplicate, create a shading node, etc. It really is poor design.

So yeah, it looks like you trampled over my answer? What kind of power trip is this? You can't just leave it alone? It's helpful to expand upon an answer, but it is extremely bad etiquette to delete. This is why I stopped contributing to Wikipedia, people are egomaniac jerks.

I just "suggested an edit" to improve your (low-quality) answer to help out future visitors, you can always roll it back: https://blender.stackexchange.com/posts/234128/revisions. Consider that this no regular forum. We do that all day btw, you're welcome.

My answer gave the essential information. I'm sorry that I don't have all day to contribute to this place, I actually have a job and a life. But I must reiterate that expanding on an answer is helpful. Just blasting over the top of it is offensive. You can do that all day if you want, but that doesn't make it right.

I don't get your attitude, what's so "bad" on having a complete explanation and an image to support that? See: https://blender.stackexchange.com/help/how-to-answer

source: Stack Exchange

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

sort: votes


text:
How to fill up every part of a geometry with a fluid?
While fiddling around getting the letter F filled up by a fluid for an animation, I don't get the fluid to reach the horizontal parts of the F.
So far I´ve tried:

Domain resolutions: 32-128
Effector thickness: 0.2 (it leaks!) to 1.5 (its so thick the fluid runs over the entire letter)
Varying the size of the flow source

Tried it now it just leaves me with no visible fluid after baking at all.
Pretty much the same way as if I´m adding a new fluid simulation to any existing work. Don´t know if this is a bug or what not because whenever I apply a fluid simulation during a work it doesn't show any fluid. But when I do the same in a new project (so that the fluid simulation is alone) it works.
Switching from All to Replay on the cache displays the fluid but it doesn't behave the right way.

Q: How to fill up every part of the letter with a fluid?

please use this https://blend-exchange.com/ to upload your file. thank you.

Did you follow my instructions? Did you add solidify modifier? Did you move it to the top?

Start from your uploaded file. Not from any file you changed in the mean time.

After playing around with this, I think the problem is with the Effector settings. The collider is a very thin shell but with a Surface Thickness set to 0.5. I believe this results in the collider being unable to determine the 'inside' and 'outside' of the mesh when allocating obstacles in the domain.
Simply changing the Effector settings to set Surface Thickness to 0.0 and enabling 'Is Planar' seems to fix the problem :

The 'Is Planar' option tells the simulation to treat the mesh as a set of faces instead of a manifold volume.

Wow. That did it! Big thanks. Imagine... ticking the planar-box was it.

Select your 'F'

add solidify modifier

move solidify modifier before fluid

bake fluid again (by the way, i use 80 as resolution (much quicker to bake))

and you get:

Tried it now... it just leaves me with no visible fluid at all after baking..!? Pretty much the same way as if I´m adding a new fluid simulation in an existing work. Don´t know if this is a bug or what not... because whenever I apply a fluid simulation during a work it doesn´t show any fluid at all. But when I do the same in a new project (so that the fluid simulation is alone) it works.

Change to modular and check is resumable in domain. Then you can bake again.

Hi. Nope... still no visible fluid after doing that. Weird....

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


text:
How can I add a collection using Python?
I'm new to Blender. Tutorial information as recent as January this year appears to be out of date and I can't figure out how to create a new collection and add an object to it. The most recent relevant question I could find suggests this:
bus_collection = ops.collection.new(name="BusRoutes")
context.scene.collection.children.link(bus_collection)

and apparently at least needs to be changed to this:
bus_collection = ops.collection.create(name="BusRoutes")
etc.

which throws the error:
TypeError: CollectionChildren.link(): error with argument 1, "child" -  Function.child expected a Collection type, not set

The API entry for Collection operators is beyond sparse, and I'm not even sure what Add the object to an object collection that contains the active object even means.
May I ask someone to give me a minimal Blender 2.83 Python example of how to create a named collection and add an object to it? Many thanks.

BlendDataCollections.new(name)
Recommend use the python console to figure out:
>>> D.collections.new(
new()
BlendDataCollections.new(name)
Add a new collection to the main database
...

>>> my_coll = D.collections.new("MyCollection")
>>> C.scene.collection.children.link(my_coll)

Demo on how to create a new collection and add the default cube using CollectionObjects.link(object):
import bpy

# New Collection
my_coll = bpy.data.collections.new("MyCollection")

# Add collection to scene collection
bpy.context.scene.collection.children.link(my_coll)

# Get cube object
obj = bpy.context.scene.objects.get("Cube")

if obj:
    # Link the cube
    my_coll.objects.link(obj)

Thanks for the quick and helpful reply - works. Thanks also for the console tip.

On reflection: what is the difference between "ops.collection.create(name="BusRoutes")" and "data.collections.new("BusRoutes")"?

Cool @Richard That's the high level call (for the user) and always requires a certain context eg. the outliner, an object in selection or what not, related: https://blender.stackexchange.com/questions/2848/why-avoid-bpy-ops

@Richard Notice this answer matches method used in question link.  A simple test print will confirm Operators return a status set, for example {'FINISHED} or {'CANCELLED'}  indicating the success  of the  "operation", not a reference to a newly created instance.  The error message in question reflects this..  Changes made by operators are reflected in context. When successfully run  the operator bpy.ops.collection.create(name="Foo") the newly created collection will contain the selected objects.  It is not however linked to the context scene or given context.


text:
How to prevent black holes when baking diffuse colors?
I am trying to bake a high poly model onto a low poly model I created using Instant Meshes. However, when baking the diffuse colors I get a lot artifacts (black holes under the chin and in the eyes):

Q: How can I bake the diffuse colors onto the low poly model in a clean fashion?

Try to increase the ray distance and/or shrinkwrap the low poly onto the high poly version.

Adding a shrinkwrap modifier helped a lot. thanks! I have a second question: What does the option extrude stand for? Can I use it to get a better result?

blender newer than 2.8
black holes / black spots while baking a cavity map For those, who follow the udemy "Blender Character Creator for Video Games design", section "bake the orcs cavity map": use Extrusion 0.01 and max ray distance 0.04 for example.

Hi, thanks for the post. This site is not a regular forum, answers should be substantial, stand on their own, and thoroughly explain the solution and required steps. One liners and short tips rarely make for a good answer, and may be converted to a comment.


text:
Can't invoke pop-up of operation?
I want to make an interface so that I can control my python methods I have already made. So I am trying to make a pop-up of an operation I made (see code below). But I get an error in the last line where I test to call it:
RuntimeError:

Operator 'MESH_OT_generate_mold' does not have register enabled, incorrect invoke function

import bpy

class GENERATEMOLD_OT_template(bpy.types.Operator):
    """Generate Mold"""
    bl_idname = "mesh.generate_mold"
    bl_label = "Generate Mold"

    z_height: bpy.props.FloatProperty(name = "Z height: ")

    #@classmethod
    #def poll(cls, context):
    #    return context.active_object is not None

    def execute(self, context):

        self.z_height = 3
        bpy.ops.mesh.primitive_cylinder_add(vertices = 32, radius = 1, depth = self.z_height)

        return {'FINISHED'}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_popup(self, event)

def register():
    bpy.utils.register_class(GENERATEMOLD_OT_template)

def unregister():
    bpy.utils.unregister_class(GENERATEMOLD_OT_template)

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.mesh.generate_mold('INVOKE_DEFAULT')

The name "MESH_OT_generate_mold" is not something I called it. Any ideas what's wrong?

You did call it MESH_OT_generate_mold, but indirectly. The bl_idname is mesh.generate_mold which translates to the expected class name MESH_OT_generate_mold. However, your chosen class name doesn't match. The actual error is in the missing bl_options though.

Thanks. Actually I figured it out. I needed this: bl_options = {'REGISTER', 'UNDO'}    But it turned out these pop-up wasn't what I needed :-(


text:
How to use a Red/Green color map in Blender?
(I have modified my initial question after finding out more about the normal maps.)
I am playing around with some ripped models and I am trying to figure out how to use the normal maps that come with them. They only have the Red and Green color channels and it seems the Blue channel needs to be generated. Is this something Blender can do easily? Can I use a material node setup to create the Blue channel at run time?

Edit:
I have found two plausible ways to fix the normal maps. The first is suggested by Christopher below and is  to invert the normal map and to invert the green channel afterwards to get the correct direction.
The second is from Substance in an article about Normals in Unity engine. It seems that the blue channel can be dropped because the normals are always of length 1, so the Blue channel can be recovered by:
B = sqrt( 1 - R*R - G*G)
which I have implemented using nodes below.
I am leaning towards the Substance approach, however, when I check the RGB values in Python, it seems that parts of the mouth have Normal vectors with length greater than 1, so this would be invalid for the approach suggested by the substance article.
Does anyone have any further suggestions about the correct approach?

maybe if you plug that image in both Red and Blue sockets of CombineRGB node and something else in blue socket (maybe the standard normal map color), it could work. It will work only if that map really was used as normal map because color of the map doesn't mean anything

It seems like the normal map is a BC5 type normal map. I found something on it here: https://docs.substance3d.com/integrations/working-with-normals-in-unity-194216104.html

Try inverting the image before connecting to the Normal Map Node to get back the purple (tangent space) colors (and map) you're used to seeing (color not shown).

However, looking more closely, I'm assuming the eyelids and nostrils are supposed to be protruding from the "outwards" face (hard to tell using the low res sample). If this is how you need it to be, you may also need to do a DirectX to OpenGL conversion:

I found this article on compressed normal maps from Substance. It seems that the blue channel is removed and can be recovered later.
https://docs.substance3d.com/integrations/working-with-normals-in-unity-194216104.html

I have tried both your method and the method suggested in the Substance article. Your method gives better results. Is this a common way for Normal maps to be saved for games?

To be honest, I'm not sure. At first I thought it was an Object Space or World Space Normal map (based on the color), but connecting it using either of those didn't give very nice results. So, I just started trying some of the conversions I know, and this one seems to give correct results for a Tangent Space Normal map, providing the desired surface deformation directions and accurate "shadow" angles.


text:
Why are particles instances in Blender rotated by default?
It's counterintuitive to me that objects rendered through the particle (hair) system are rotated under default settings. what I'm talking about is shown in this image:
The object I made has the appropriate colors aligned to the XYZ axis, but the instanced objects are x-axis up.
Is there a reason for aligning objects in this way? Asset packs from Blendermarket (like the Realistic Nature Asset Pack) come with their objects lying on their side to compensate for this but I think ideally this shouldn't be necessary.
So is there a reason for why particles work in this way or is it just a quirk of Blender?

I think it's just one of those Blender quirks, perhaps it will be fixed in the future

I see. An impact of this choice is that the Geometry nodes instancing and particle system instancing do not use the source object rotation in the same way. It would be nice if this was more consistent.

Some legacy reason for this that I read once and could never find again.  Quick fix: select object to be used as a particle, and R, X, -90.  Apply rotation.


text:
How to create equi-triangle-remeshed object?
I'm trying to make many round holes on a smooth-shaped mesh (scanned for 3D printing) as evenly as possible, and currently I found a way to do that by:

create a low-res remeshed version of original shape, whose grid is used as a guide;
spawn many small cylinders by Object Properties - Instancing;
apply instances, then boolean modifier.

However, the Remesh tool in Object Data Properties only creates quad meshes, and the result grid is not so even: it tend to spawn tighter edges along one direction and looser on the other direction, which make holes distribute uneven. So how could I create a low-res evenly-distributed triangle mesh from an original one?

Could you add an image of an object as an example? I think I understand, but an [edit] would be helpful to understand what you are beginning with, working with etc.

@Timaroberts images added for explaining the situation


text:
Changing the position of the camera using python script and then rendering using the new location
I am currently using blender version 2.92 and am trying to change the camera position using a python script.
I am passing the coordinates for the camera using a JSON file and the snippet for the same is as :
"camera_locations":[
    [
      2.576395273208618,
      -4.465750694274902,
      1.094475507736206
    ],
    [
     100.87639527320862,
      -9.465750694274902,
      400.094475507736206
    ]

I am creating a function and passing the camera object and the camera locations (that I have read from the JSON file ) as parameters. Further, I am then trying to change the camera location and render. Following is the code snippet:
def render(camera_locations,object):

    camera_location=object.location
    print("the current camera position is as: ", camera_location)
    for locations in camera_locations:
        count=0
        for location in locations:
            object.location[count]=location
            count+=1
            if(count==3):
               count=0
        bpy.context.scene.render.filepath=output_path+str(i)
        bpy.ops.render.render(use_viewport=True,write_still=True)

However, when I render I do not see any changes in the images with respect to the camera location. The images look identical.
I have tried printing the above variables and those do show the updated values.
I am not sure what I am missing here. Can someone guide me with this or suggest a better way to tackle the problem?

@brockmann The indentation is actually a copying mistake from my end. I have edited the question now. I am getting two output images currently and they look identical. Sorry for the confusion.But I will try the below approach

Make the render operator and the output path assignment part of the actual for-loop. Demo code using a regular dictionary for the camera locations based on this answer.
import bpy
import os.path

camera_locations = {
    0: (2.576395273208618, -4.465750694274902, 1.094475507736206),
    1: (-0.573695343202619, -1.863753624223357, 1.094235453632562)
}

# Scene variables
scn = bpy.context.scene
cam = scn.camera
output_path = scn.render.filepath

# Iterate through the dict, set the locations and render
for k, v in camera_locations.items():
    # Set the locations
    cam.location = v
    # Assemble the path (.jpg is a placeholder)
    scn.render.filepath = os.path.join(output_path, "cam_{}.jpg".format(k))
    # Call the render operator
    bpy.ops.render.render(write_still=True)

# Reset the output path to "/tmp/"
bpy.context.scene.render.filepath = output_path

Render output (default scene), output file type set to OpenEXR:
/tmp/
├── cam_0.exr
├── cam_1.exr
...

Render output of our famous classroom scene (make sure to remove the location keyframes of the scene camera before running the script):

cam_0.png (left), cam_1.png (right)

In case there is no way around a two-dimensional list as provided, I'd suggest use python's build-in enumerate() as mentioned in the comments, makes the code nearly identical:
import bpy
import os.path

camera_locations = [
    [2.576395273208618, -4.465750694274902, 1.094475507736206],
    [100.87639527320862, -9.465750694274902, 400.094475507736206]
]

# Scene variables
scn = bpy.context.scene
cam = scn.camera
output_path = scn.render.filepath

# Iterate through the list, set the locations and render
for c, v in enumerate(camera_locations):
    # Set the locations
    cam.location = v
    # Assemble the path (.jpg is a placeholder)
    scn.render.filepath = os.path.join(output_path, "cam_{}.jpg".format(c))
    # Call the render operator
    bpy.ops.render.render(write_still=True)

# Reset the output path to "/tmp/"
bpy.context.scene.render.filepath = output_path

Note: object is an identifier in python hence the different syntax highlighting, I'd suggest use obj as variable name and I'd also recommend against string addition for paths, either use os.path.join() as above or have a look into the pathlib module.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Int property not displaying in my panel?
I am new to writing UI for Blender (2.92) and I am having a really difficult time understanding what is going on. I would like to add a panel for integer input by the user. When I look at reference code snippets they don't make sense to me and copying these bits of code across also doesn't seem to work.
I would appreciate some help in this regard so I can figure out what I have to do here. The examples I have attached are some last desperate attempts to copy across work from other examples found on the web (marked as blue) + the panel I am working on with a blue dashed line showing where I would like to display a user input.
A description would be nice instead of a vague example. I actually want to understand what is happening.
import bpy
from bpy.types import Panel

from bpy.props import IntProperty

class SMG_PT_Buttons(Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = "SMG Naming Button"
    bl_category = "SMG"
    bl_idname = "smg.naming"

    def draw(self, context):
        layout = self.layout
        bpy.types.Scene.my_use_x = bpy.props.IntProperty()

        # Button 1

        layout.label(text="Parent Object")

        row = layout.row()
        row.operator('smg.write_region', text = "Write Regions")

        row = layout.row()
        row.prop(context.scene, 'my_use_x')

        row = layout.row()
        row.operator('smg.write_territory', text = "Write Territories")

To see any error feedback https://blender.stackexchange.com/questions/6173/where-does-console-output-go  Declare the property bpy.types.Foo.prop = BarProperty(...) outside the draw method, is  most often seen in an addons register method.  https://blender.stackexchange.com/questions/57306/how-to-create-a-custom-ui/57332?r=SearchResults&s=1|0.0000#57332

Ok will comment since  the question was closed.  Answer gives a fix, Reasons behind:  If you look in console when viewing panel AttributeError: pyrna_struct_meta_idprop_setattro() can't set in readonly state 'Scene.my_use_x' ie you cannot set (or declare ID types properties  from within a draw method. context.scene.my_use_x = 10 will throw the same error.   There is also a warning on running script Warning: 'smg.naming' doesn't contain '_PT_' with prefix & suffix  suggesting you leave out bl_idname,   defaulting to   the class name, which in this case follows the naming convention.

Just declare your scene property in register() and remove it in unregister():
import bpy
from bpy.types import Panel
from bpy.props import IntProperty

class SMG_PT_Buttons(Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = "SMG Naming Button"
    bl_category = "SMG"
    bl_idname = "smg.naming"

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

        layout.label(text="Parent Object")
        row = layout.row()
        row.operator('smg.write_region', text = "Write Regions")
        row = layout.row()
        row.prop(context.scene, 'my_use_x')
        row = layout.row()
        row.operator('smg.write_territory', text = "Write Territories")

def register():
    bpy.types.Scene.my_use_x = bpy.props.IntProperty()
    bpy.utils.register_class(SMG_PT_Buttons)

def unregister():
    bpy.utils.unregister_class(SMG_PT_Buttons)
    del bpy.types.Scene.my_use_x

if __name__ == "__main__":
    register()

As for detailed explanation, I can't think of much to say - the scene is not inside the panel, so its properties live outside panels as well, that's all.

IMO place it in the register method to define the property when the addon is registered not when it is imported.

Look for errors.
On running a script in blender always keep an eye on the system console
Where does console output go
After adding a call to register this class
bpy.utils.register_class(SMG_PT_Buttons)

a warning is printed.
register_class(...):
Warning: 'smg.naming' doesn't contain '_PT_' with prefix & suffix

Suggest you leave out bl_idname, defaulting to the class name, which in this case follows the naming convention. To find this registered class
bpy.types.SMG_PT_Buttons

names like "smg.foobar" are for operators --> bpy.ops.smg.foobar(..)  Another option is to
class SMGButtonsPanel(Panel):
    bl_idname = "SMG_PT_buttons"
    ...

if you prefer having your own class names,
Draw methods are read only.
You cannot declare or set an ID object property from within a draw method.
On viewing the panel
Python: Traceback (most recent call last):
  File "/Text.003", line 17, in draw
AttributeError: pyrna_struct_meta_idprop_setattro() can't set in readonly state 'Scene.my_use_x'

hence as shown in other answer declare the property from within your register method.
import bpy
from bpy.types import Panel
from bpy.props import IntProperty

class SMG_PT_Buttons(Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = "SMG Naming Button"
    bl_category = "SMG"

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

        # Button 1

        layout.label(text="Parent Object")

        row = layout.row()
        row.operator('smg.write_region', text = "Write Regions")

        row = layout.row()
        row.prop(context.scene, 'my_use_x')

        row = layout.row()
        row.operator('smg.write_territory', text = "Write Territories")

def register():
    bpy.utils.register_class(SMG_PT_Buttons)
    bpy.types.Scene.my_use_x = IntProperty()

def unregister():
    bpy.utils.unregister_class(SMG_PT_Buttons)
    del bpy.types.Scene.my_use_x

if __name__ == "__main__":
    register()

Test via python console.
If I have script above as blender textblock "Text.003" I can emulate importing and registering in the python console
>>> m = D.texts['Text.003'].as_module()
>>> m.register()
register_class(...):
Warning: 'smg.naming' doesn't contain '_PT_' with prefix & suffix

Whoops, forgot to take out the idname, edit go again
>>> m = D.texts['Text.003'].as_module()
>>> m.register()
>>> m.unregister()
>>>


text:
How to weight paint complicated meshes?
I'm trying to make wings. I want to animate them later so I have to rig and weight paint it.
Does anyone know if there is a simple way to weight paint the space between the layers of feathers? Or ho to make it simpler in another way

Is the wing one mesh object or a number of unjoined mesh objects?

Currently it is 7 sepperate meches. but I will unite them before I weight paint it.

I found a solution. I read that you have to turn of Front faces only and activate 2d falloff.
Then all of the sides of the mech will be painted.


text:
Rotate all the objects in the array in the same way
I want to make windows blinds. I create slats by using Array modifier.
Now I want each slat to rotate in the same way. When I rotate them now - they are also moved.
How to make it in an easy way?
In 3dsMax I was able to create array of objects as an instances of the original one and when I was rotating the original one, all the rest rotated the same way.

You can rotate them in edit mode, but that may have repercussions if you wanted to edit later..  You could always instance on points in geonodes

An old-school method would be, in Edit Mode, with all selected, to CtrlH give your slat a Hook modifier. Its mesh can then be controlled by an Empty, without transforming the object, so the Array transform remains constant.

The controlling Empty can be given a Limit Rotation constraint, to prevent the blind from flipping out, or intersecting itself.

But if you're making a re-usable Venetian Blind asset, with a convenient interface for variations, then a Geometry Nodes modifier is probably a better way to go.

You can create your own more powerful array modifiers using geometry nodes.

In the above image you can control the count, offset factor, and rotation (in radians) in the modifier:

Tip: if you connect a group socket to the socket of a node that uses degrees as value (e.g. Curve Spiral) and then disconnect it again, the group socket remembers the setting and you can change the angle in degrees instead of radians. Alternatively you can use a Math node and the setting To Radians.

@quellenform .. sneaky !


text:
Custom ordering in UI List
If somebody is versed in UI lists code, can you help me with custom ordering? It seems impossible. I want items sorted by custom property integer value, instead of name and can't get it to work.
I'm using
ordered = bpy.types.UI_UL_list.sort_items_helper(items, key=lambda item: item.get("custom_property", 0), reverse=False)

And its not working. I'm getting this error
File "C:\Program Files\Blender Foundation\Blender 4.0\4.0\scripts\startup\bl_ui\__init__.py", line 221, in sort_items_helper
    sort_data.sort(key=key, reverse=reverse)
AttributeError: bpy_prop_collection: attribute "sort" not found

What type is items? It seems to be a bpy_prop_collection that has no sort() function. This is the reason for the error. -  items should be a list of tuples according to https://docs.blender.org/api/current/bpy.types.UI_UL_list.html and sort_items_helper returns a list (... of tuples? of indexes?). Try ...sort_items_helper(items.items() .... I guess, you need to create a new collection from the result list then.

You can sort items in the UIList using the rather convoluted bpy.types.UIList.filter_items.
eg
class YOUR_UI_LIST(bpy.types.UIList):
    def draw_item(
        self, context, layout, data, item, icon, active_data, active_propname
    ):
        layout.label(text=item.name)

    def filter_items(self, context, data, propname):
        items = getattr(data, propname)
        items_sorted = sorted(items, key=lambda it: it.get("custom_property", 0))
        filter_neworder = [items.index(item_sorted) for item_sorted in items_sorted]

        filter_flags = [self.bitflag_filter_item] * len(items)
        return filter_flags, filter_neworder

If you want to hide certain items depending on context using filter_flags, instead of self.bitflag_filter_item set the item index to 1 for example.
eg if you want to hide the first item :
filter_flags = [self.bitflag_filter_item] * len(items)
filter_flags[0] = 1  # This will hide item index 0

filter_neworder is a list that contains the new indices for each item in the list.
eg for a list with 2 items, if item at index 0 is sorted at index 1 and item at index 1 is sorted at index 0, (reverse list) filter_neworder = (1, 0).


text:
Export alembic frames to OBJ
I have an alembic file. Is it possible to export the individual frame data to OBJ files with blender script?

import os
import sys
import bpy

filepath = sys.argv[1]

# https://blender.stackexchange.com/a/220016/165060
while bpy.data.objects:
    bpy.data.objects.remove(bpy.data.objects[0], do_unlink=True)

# Loading alembic file

bpy.ops.wm.alembic_import(filepath=filepath)
scene = bpy.context.scene
startFrame = scene.frame_start
endFrame = scene.frame_end

for frame in range(startFrame, endFrame + 1):
    scene.frame_current = frame
    filename = (sys.argv[1] + str(frame).zfill(4) + ".abc")
    bpy.ops.export_scene.obj(filepath=filename[:-3] + "obj")
```


text:
Weight painting mass distribution?
Does anyone know if it's possible to use weight painting to distribute mass within a mesh for physics simulation purposes?  Like say I had a uniform mesh pole and I wanted to adjust the weight of one end vs. the other without changing the dimensions of the mesh at all. I'm just getting starting to get to grips with physics simulations, so forgive me if I'm missing something obvious. One idea I had would be to weight paint and then use the weights to distribute instances of a weight-bearing particle at different points on the mesh, but my gut says that it should be simpler than that.  Thanks in advance for any help!

Rigid body simulation can’t be adjusted by weight painting but you can get pretty much the same effect by moving the centre of gravity by changing the Origin on the object. This will have the effect of making the object behave the same as if the weight was redistributed.

Thanks, Rich.  I had discovered the trick of moving the cursor around to represent the center of mass.  Just wondered if there was a way with weight painting, since it would have facilitated an animation I had in mind.  But if it can't be done, fair enough.


text:
Hinge animation not working. Seems a bake problem
I´ve been meddling with this issue for weeks and still don´t know what the problem is. I want to make an animated object with a hinged part but the results are random: sometimes I get the hinge working when the object is static but not when I animate it and so on.
I suspect it´s something related to the baking, but I´ve tried to delete it, change the animation parameters to reset it, append in a new project... and nothing works.
Any suggestions?
I attach the project, in case you want to check it out.
https://wetransfer.com/downloads/9bbff0cd03b80a95dc507d8e55640edd20230405111629/3d845c5b16f140d4a946c0923594f2c420230405111650/c0d60c

Hello, so what animation are you trying to do and why are you using a rigid body instead of keyframes?

I want a character to throw the object, then it breaks when hits the ground. I want the hinged part to flap and bounce realistically when the object is carried by the character and later thrown. I thought that it would be faster and more reallistic if I made it with a simulation. Yes, at this point it would have been faster to keyframe it, but now I just want to learn what´s wrong.

just increase your speed of your pan like this:

then it works.
Physics is most about weights, speed, acceleration and how you have to combine them altogether so that it works ;)

you should give the upper part passive body too so that it looks more realistic...


text:
How to import a STL file using the file browser?
I'm trying to import a stl file manually via python. My code below is pretty straight forward, but I'm struggling with the following line. I'm not sure about the syntax and format of the arguments:
bpy.ops.import_mesh.stl(filepath=???, files=???)

The current state of my operator:
import bpy

class FILE_OT_import_stl(bpy.types.Operator):

    bl_idname = "file.import_model_stl"
    bl_label = "Import Model STL"
    bl_options = {'REGISTER', 'UNDO'} # Must have REGISTER!

    def execute(self, context):
        #my_filepath = 'K:/PQJ/Mold Generator/Blender test/'
        #filepath = '//898L-OutputModel-SLA[]_09'
        #print(filepath)
        all_files=[bpy.types.Scene.import_path]
        #print(file[0])
        bpy.ops.import_mesh.stl(filepath=my_filepath, files=all_files)
        return {'FINISHED'}

class FILE_PANEL_PT_import_export(bpy.types.Panel):
    bl_label = "Import/Export"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    # bl_context = "object" # object vs edit mode

    def draw(self, context):
        layout = self.layout
        layout.label(text="Import")

        layout.prop(context.scene, "import_path")
        row = layout.row()
        row.operator("file.import_model_stl")

classes = (
    FILE_OT_import_stl,
    FILE_PANEL_PT_import_export
)

def register():
    for cls in classes:
        bpy.types.Scene.import_path = bpy.props.StringProperty(name='Import path', subtype='FILE_PATH')
        bpy.utils.register_class(cls)

def unregister():
    del bpy.types.Scene.import_path
    for cls in classes:
        bpy.utils.unregister_class(cls)

if __name__ == "__main__":
    register()

Q: How to import a certain STL file using the file browser (and add a custom material)?

Do bpy.ops.import_mesh.stl(filepath="your/path/here.stl").

I tried that but it didn't work. Also I am trying not to hard code the path but get it from my custom prop.

Depending on the situation you can just call bpy.ops.import_mesh.stl('INVOKE_DEFAULT') or use layout.operator("import_mesh.stl", text="Import STL", icon='FILE_NEW') in your draw method if you want to import 1 file. Have a look into the Operator File Import template (magic is done by its ImportHelper class). Related: How to use the File Browser's (with ImportHelper) execute function?, batch import example: How to batch import Wavefront OBJ files?. Do you'd like to import 1 or a few files?

It's just 1 file and it needs to be selected by mouse click. After import I need to do a few things to the object - otherwise I could just use the import in the menu

It is selected anyway...

You can just add the built-in operator import_mesh.stl to your draw method of your panel which will open up the File Browser as usual and allows the user to select one .stl file:

import bpy

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

    def draw(self, context):
        layout = self.layout
        #layout.operator_context = 'INVOKE_DEFAULT' #'INVOKE_AREA'
        layout.operator("import_mesh.stl", text="New", icon='FILE_NEW')

def register():
    bpy.utils.register_class(OBJECT_PT_CustomPanel)

def unregister():
    bpy.utils.unregister_class(OBJECT_PT_CustomPanel)

if __name__ == "__main__":
    register()

Related: How to call a confirmation dialog box?

In case you want to import and modify the .stl object for whatever reason, have a look into the Operator File Import template (operator_file_import.py) that comes with Blender.

Demo operator based on the template, allows to import the file, print the object reference and assigns a new material to the incoming object in one go:
# ImportHelper is a helper class, defines filename and
# invoke() function which calls the file selector.
from bpy_extras.io_utils import ImportHelper
from bpy.types import Operator

class ImportSomeData(Operator, ImportHelper):
    """This appears in the tooltip of the operator and in the generated docs"""
    bl_idname = "import_test.some_data"
    bl_label = "Import Some Stl File"
    bl_options = {'REGISTER', 'UNDO'}

    # ImportHelper mixin class uses this
    filename_ext = ".stl"
    filter_glob: bpy.props.StringProperty(
                default="*.stl",
                options={'HIDDEN'})

    def execute(self, context):
        if self.filepath:
            bpy.ops.import_mesh.stl(filepath=self.filepath)
            # Print the imported object reference
            print ("Imported object:", context.object)
            # Create a material
            mat = bpy.data.materials.new(name="STLMaterial")
            # Append the material to the last slot
            context.object.data.materials.append(mat)

        return {'FINISHED'}

Further reading:

How to assign a new material to an object in the scene from Python?
Import multiple STL files and modify the incoming objects in one go?

Yeah. The 'INVOKE_DEFAULT' works like a charm. But I need to change the name of the object right after import (and maybe a few other things). This only imports (like in the menu)

I have seen the template and it just says: "bpy.ops.import_mesh.stl(filepath=self.filepath)". I can't find where "self.filepath" is set.

Comes from the ImportHelper class, see my demo code.


text:
Why some parts of the object don't move with the armature?
I tried to fix the bones so that things could look better but these things keep staying in place. And when I subtract weight paint on some parts it becomes bumpy.

The first reference picture looks like some vertices have no vertex groups (weightpaint) assigned.
You can fix it by selecting the responsible vertex group in the Properties Tab -> Object Data Properties (the green triangle icon), switch to Weightpaint Mode and use some blur brush on those lacking parts.
This helped me a lot so far.


text:
Light Area under Glass
I have a scene with a glass floor and a cavity underneath the glass. I would like to be able to actually see the cavity instead of just black glass (which is black for some reason that I'm hoping you guys can figure out a workaround to).

What is the workaround so that I can still have the slight darkening and reflections that come with glass, but also be able to see through relatively well? I'm going for a steampunk piano with some circuitry under the floor (not yet fully modeled).
A .blend (minus Image Textures because they're huge) to play with:

You have your Light Paths set to 0 Bounces in the Render tab. Try changing all these settings back to their default. I did and this is how it rendered.

Ha, totally missed that. Thanks for catching my error!

You need to configure the enlightenment of the whole scene. For now you have only one source light, and it's a "point" - this is not a light for lightning surfaces (even if it have 1000000000 value - like you have...) Second, all the scene is in a dark box. Apply the array modifier that you have to this hexagon and move the faces that behind the camera - that will allow to point a light source on the scene from the face.
It's all about the lights. After that you can play with the glass shader to polish the look you want.
PS. And It's not a cavity... It's just a background of the scene...

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


text:
Z-depth of Microdisplacements and Adaptive Subdivision Surface
In Blender 2.78, there are two very cool features called Adaptive Subdivision surface and Microdisplacements. BlenderGuru has a great video on it.
If you don't have time to watch the video, here is a summary in lamens terms (written by me; just wanted the quote format to emphasize it):

Both of these features are Experimental features for Cycles render.
Adaptive Subdivision surface is an extension of the Subdivision surface modifier that calculates decreasing levels of subsurf the farther away the object is. It can even change the level across an object.

Image by BlenderGuru.
Microdisplacements uses the Displacement input of the Material Output node. It generates extra geometry at the time of the render. It's like a Displace modifier that only displaces during the render and uses any combination of Cycles material nodes.

However, when I try to use these features on a plane and use a Separate XYZ > Z node in my node setup, it doesn't work. I am theorizing that this is because the plane does not have any Z depth before the render. Is there a way around this?

Havent actually used any of the new features myself yet, but my guess is that micro-displacement is preformed at render time only, and processed after, or at least along with other shader calculations, and as such there are no different Z values to display at the time the generated texture coordinates are calculated, since they seem to comes directly from the object mesh data.

As Duarte mentioned, generated coordinates do not factor in the displaced mesh. So you need to get a Z coordinate from something that does. You can use either "object" coordinates (available from the texture coordinate node or the geometry node, their "object" outputs are the same) or "global" (aka world space) coordinates from the geometry node's "position" output. These do not rely on precalculated geometry, instead they simply use the shading point's location.

The difference between the two is that object coordinates are in "object space", meaning they account for the transformation of the object. That means they won't move when you move the object, which is good for animated objects (otherwise they might appear to "swim through" the texture). It also means that multiple copies of an object will always have the same texture, although that one may or may not be desireable. Global/world space coordinates are absolute and do not account for object transformations and locations at all. They're nice when you need to keep consistent texture locations across multiple objects (such as adding a waterline to objects below the level of your water mesh) or if you want different textures across multiple static copies of an object

authors: Владислав Гоголь

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


text:
Apply Object Texture Coordinates
Recently, I used Cell Fracture on a wall to split it into pieces. I then used an Empty and Object Texture Coordinates to map a Brick Texture over the wall. However, when I simulated the wall (Rigid Body Simulation), all of the textures changed (kind of like I expected).
What I was wondering is is there a way to "apply" Object Texture Coordinates, or otherwise, how can I fake it?

Here's my current result:

New .blend:

You can run the texture coordinates through an emission shader, then bake it.  (Remember, XYZ and RGB are identical.)

@PGmath I am not familiar with baking. Would you consider adding an answer and explaining it more in depth?

Does this answer your question? How do I bake a texture using Cycles bake

final Blend file:
The workflow PGMath suggested works, there is a few traps however on the way to get that to work on the shards as well. I'll explain as I walk through the solution found. What's needed to get it done is the assistance of the TextureAtlas addon. Enable it in the Addon Section of Blender:

It's important to mention that without the initial idea by PGmath, I'd had no clue as of how to do it, so you might consider accepting his answer as the one which worked. The workflow is like this:
Create your scene as desired, with mapping set to object coordinates as requested. Next, create an image Texture, which will serve as the target of our baking:

For me, using 2048 x 2048 with 32 bit depth worked fine for your demo scene. Save this image as an OpenEXR to Disc. Now to the material setup. You want to bake the UV Map of this material here:

So you've used Object coordinates, and did some mapping inbetween as well. The part we need is only the part including the mapping node, so everything which affects the UVs. Feed that into an Emission Shader and connect it to the material output node (it is called Viewer in this screenshot, because, lazy as I am, I was using Node Wrangler to hook it up quickly, but it is nothing than a default Emission Shader):

If you render this now, you see something like this:

This is nothing else than the representation of our UVs as RGB channels. Now, add another image Texture Node, and select the Object_UVs Texture from there. At the moment it will be black or empty, but in a few seconds we have the UVs in there.

This material needs to be assigned to every shard of your simulation before you proceed. This has very likely been done by the cell fracture addon anyways, but just double check it. Now we need to create UVs for the shards. The tricky thing is, we want to bake a UV map that fits all shards at the same time, but we can only unwrap one at a time. So how to make sure UVs never overlap? TextureAtlas solves this by temporarily combining shards, unwrapping (lightmap pack), packing, and then separating them again.
Go to the TextureAtlas tab in the Rendering section, using the plus sign add an Atlas, and set these settings:

So the resolution should match your Texture, you add all shards to it by having them selected and clicking 'add selected', set the mode to Lightmap, and the margin to 0.05 (I got this value by testing). The margin will make sure there is some space inbetween shards, otherwise one shard's UVs overwrite anothers.
Now, make sure that this texture node is selected before starting the baking! Regarding performance, you can set the samples as low as 4, lower samples for me caused artifacts in the emit pass, resulting in distorsion. If clamping has an effect I did not test, but just set it to 0.0 for safety measures. Most important is the margin: set it to 1 pixel, as the 2K map will be really tight! Now use the Emit Pass as the result of your bake, and click 'bake':

If you have an image editor open at the same time, you can follow the progress. Once done, it should look something like this:

Save this image, so it won't be forgotten after you exit Blender. Regarding the File Format, since you need 32bit information ideally, choose OpenEXR with Float Full Color Depth, so 32bit per channel, as in this screenshot:

You can choose RGB instead of the default RGBA if you want to save some disk space, the Alpha won't be used. Now, you can create a node setup like this, while getting the exact same result as before:

The logic is: The RGB values in the Object_UVs texture represent the coordinates in the UV image editor, however the blue channel is unused. R represents U coordinates, G the V coordinates. Blender doesn't care if they come from a node, the uv editor or a texture, you can feed them in nonetheless!

Standard SE etiquette is that if someone posts an idea in the comments, give them a little time to put in in an answer before copying it in your own answer, see this meta post.

no worries, I'll delete mine

post updated after getting in touch with PGmath

You can do this by creating a special new material of the texture coordinates and baking it, then using the baked image for the texture coordinates of your split objects.  Note thatt this should be done before cell fracturing your object.
First unwrap your object.  It doesn't have to be a super clean unwrap, just something not too distorted.
Now create a new material and name it something like "MappingCoords" or whatever makes sense to you.  For the material just plug the Object texture coordinates into an emission shader.  Since color and vector datatypes are no different from each other the XYZ texture coordinates will now be represented by RGB values.

Now go to the UV/Image Editor and add a new blank image by clicking on the New button at the bottom.  What resolution to use will depend on how big your model is and the resolution of the texture you will be using.

Next go back to the node editor and add an Image Texture node.  Don't plug it into anything or modify your nodes, just select the blank image you just made and make sure the node is selected.  Now go to the Render Properties tab and scroll all the way down to the Bake Rollout.  Select Bake Type Emit and hit the Bake button.

The bake should look something like this:

Now go to the UV/Image Editor and save the baked image as an OpenEXR file (other file formats will undesirably clamp the <0 and >1 values to 0 and 1).  You can then load the image and plug it into the Vector of the image texture for your material.

Now when you cell fracture the object each fractured piece should retain its UV unwrapped coordinates, which are being used to map the baked texture coordinates for the actual image texture.

Here is my .blend so you can take a closer look at what I did:

You will have to either re-bake the coords or download the above image (it's a PNG not EXR, but it will work in this case since I used generated coords which are in [0,1]) since the file was too big to fit on Blend Exchange.

Perhaps I should have been a bit more clear. I have multiple objects that need to be uv unwrapped. I have achieved this by joining them, using Smart UV Project, Margin: 1, separating them with By Loose Parts, and realigning their origins with Origin to Geometry. I will say that after baking and following your steps to the best of my abilities, my results are still really weird. If you have the time, please consider problem solving with my .blend file, available in my question.

@ShadyPuck  Sure, I'll take a look at it!  I guess I didn't realize you have already cell fractured the object, it would make it easier if you bake the texture coords before cell fracturing it.  Is that possible?

Probably. I'll try that in the morning.

Ok, I tried baking on the cube I used before cell fracturing, and I still get this weird result. I tried the openEXR thing, which I hadn't before, but it didn't change anything. Any more thoughts? I also uploaded a new .blend file that includes my newer exploits, minus the .exr because it was too big to go to Blend Exchange.

I've got a working solution now which keeps the mapping on the shards intact. It is based on your file, however this time I'll wait for PGmath to post his answer, don't want to offend the forum members any further.

@aliasguru  No worries, I'm not offended at all!  I didn't intend for you to delete your answer either, just something to remember for the future.  We don't expect every new user to read every single meta post before doing anything! :D  So please feel free to post if you have an answer that works better than my current one.

@PGmath glad to hear that! I was just wondering because you mentioned you'd be working on an extended solution today, so I was wondering if I should wait for that (and according to the meta post, I should wait for a few days). If you don't mind, I'll update and undelete my message in the next few minutes.

@ShadyPuck  OK, I have updated my answer with more details.  I am working on trimming down the .blend to <30MB (EXR files are huge) for Blend Exchange.

@PGmath Fantastic! I've been on vacation, but I'll be home tonight. I'll check it out then!


text:
How to create a cross point for two nearby non-crossing edges?
After some object modifier operations (actually solidify), sometimes it generates edges that should be crossing but actually not, and I want to specify them a crossing point by creating it.
By middle-school geometry, we know that for any two 3D lines that are neither crossing nor parallel, we can always find a third line crossing them and are vertical with both two lines. And I can use the middle point of the third line as the crossing point of the two non-crossing lines. Is there any way to do it in Blender?
The image below shows an example of this situation. The geometries are generated from solidify modifier. The selected lines in orange and white should be crossing, but are actually not, and they are very nearby.

I'm not sure what you mean. Can you post some screenshots to clarify what you mean?

I agree with Harry McKenzie. It's a bit confusing since you wrote in the title "a cross point" and in the text "find a third line crossing them". Is it a point or a line what you are looking for?

I understand this as asking for the shortest line between two skew lines.  This is an interesting problem for me-- I can imagine a couple of sampling based solutions, either make a bunch of points and sample nearest or do a mesh boolean, but that's not as appealing as a non-sampling-- precise!-- solution.  A non-sampling solution would probably involve solving for it mathematically, which you could probably do by doing some googling, but in my opinion, where's the fun if you do that?  The fun for me is in the solving.

Are you looking to create an operator to do this to, say, 2 selected edges? How do you want to isolate relevant pairs, ignoring the ones you don't want affected?

@Nathan As I know some computational geometry, actually I can make the mathematical calculation for it, however I don't know how to do it in blender.

@HarryMcKenzie I have attached the screenshot.

@RobinBetts Yes, I probably need to create a custom plugin that operates on two selected edges, if there aren't existing function for this. I have a few experience on blender plugin ten years ago, and I guess the API has changed a lot.


text:
Rigging - How do I change pole angle without affecting the mesh?
The title says it all. When I change the pole angle of a bone to match the bones that control the direction knees and elbows are facing the mesh gets all twisted. How do I avoid this?
I'm using this rigging method:
https://www.youtube.com/watch?v=cGvalWG8HBU
EDIT: As you see the elbow is bending up, but I want it to bend back without the arm getting rotated (because of how the arm is shaped)

Propably the vertex group for this bone is all over the body, try to find the vertex group delete it and weight paint the parts of the mesh for that bone your self

@IgorTatarnikov The weight painting is fine. I added a picture and some additional details of the problem which should make understanding the issue a little bit easier.

It would be easier if you will add your blend file

This appears to be a duplicate of Rigging - Is it normal for limbs to rotate when you set their pole targets? ...unfortunately there's no answer there either.


text:
How to scale an animation in blender
I have an animation in blender, but its very small in dimensions. I have to scale it to a factor of around 10. However, I just realized that just scaling an object won't actually scale the whole animation ( while rendering ). Is there anyway with which I can scale the whole animation ( including each keyframes )?
Thanks
EDIT: Sorry for the confusion, I dont want to extend the moving area of the animation. I want to increase the dimensions of the image used in animation. When I am trying to scale up the object in 3D view, it does scale the animated object placed on the scene, however, when I play the animation, the scaled dimensions aren't preserved.

I hope its a bit clear now what I want to do.
Thanks

Do you mean scale over time?

@JaxXxon no, i meant to scale from the start itself. The fbx i have have quite tiny dimensions, and i have to project them over to a surface, where at present they are hardly noticeable. Thus, have to scale them up to match surface size

So, instead ,for example, an object would move 10 meters instead of 1 meter?

@JaxXxon Sorry for the confusion, I dont want to extend the moving area of the animation. I want to increase the dimensions of the image used in animation. When I am trying to scale up the object in 3D view, it does scale the animated object placed on the scene, however, when I play the animation, the scaled dimensions aren't preserved.

@JaxXxon Please refer to the question edit section

Sorry, it's still not clear to me what is happening.
Please share a blend if you can.

What do you mean by "the image used in animation"?

Go to the graph editor,

place the 2D cursor at the origin (the arrow on the screenshot below),
choose the 2D cursor as pivot . (the rectangle below)
select all A (or only the keys you want B)
scale S on the vertical axis Y

Thanks however, I believe I wasnt clear in describing my problem. Please refer to the edit section of the question. Sorry for the confusion.

works great, (btw rotation keyframes usually don't need to be scaled)

I think I have managed to do what I wanted to achieve. I used export fbx option and increased the scaling size, and it seems to work.
However, if there exists some other better way please share.
Also, while exporting FBX, some animated objects are rotated randomly and they loose their original x,y,z coordinates in the space. I believe it has something to do with the two parameter 'forward' and 'up' in the export fbx option.

I loved your solution to this problem! Thanks for coming back here to share.

Scaling an inamation can be done in the graph editor. First select the object you wish to scale the animation for. Then open a graph editor in one of your views. Then follow the steps in attached image. I used a cube which was animated on the Z-axis in my example.

Hope this answers your question!

You can add an empty and parent your animated object to it.
Then scale your empty, it will scale your animated object too.

Could you illustrate the steps to achieve this?


text:
Offset for Mesh?
With text, you have a really handy control called 'offset', which allows you to easily increase/decrease the size of your letters from their centres not by changing the shape proportionally but by adding/detracting from its outline, which looks like this (border remains uniform):

By contrast, when trying to scale down a mesh object using the 's' it looks like this (borders not uniform):

Is there a similar 'offset' control that allows similar for mesh objects or any other way of achieving the same result? Seems odd that such a useful tool would be exclusive to text.

You can scale a mesh along normals (Alt+S). It may be quite difficult to scale it so faces to remain perpendicular, but still it may be a workaround

When I do Alt+s my object disappears and undo doesn't even get it back. I'm confused, what am I doing wrong?

@marklovin make sure you move your mouse slowly (it's an interactive feature), if your cursor speed is too fast that might be the issue, also left click to confirm.

For me it just behaves exactly the same as if I just press 's' on its own, i.e. it just scales it proportionally....

It depends on your mesh. If it's default cube, then yes, there won't be any difference. If even that default cube is subdivided several times, then there will be difference. So you might want to include screenshots of what you're after and what are you trying to do

@MrZak I have added an extra screenshot to show what I mean. Thanks

It would be clearer with the .blend file added. At the moment it seems you're trying to scale down the top layer instead of scaling it up. While scaling such objects it may work changing its origin and Pivot Point, so scaling will be done taking in account another pivot point and may be more accurate

The thing to understand here is alt+s scales vertices along the NORMALS, unlike scale which moves all vertices towards the object centre. It looks like you may have to convert to a mesh before trying alt+s.

@beiller If these layers, both top and bottom, have no thickness (i.e just converted from 2D curve, for example) than even after converting to mesh Alt+S won't work predictably on them. It will just "grab" these letters by Z axis. That's why I think it would be hard without .blend here

Okay I have added another screenshot and rewritten the question. Hoping that will help you all understand what I mean. Would be great if someone out there has a solution.

I think this is the answer: https://blender.stackexchange.com/questions/42643/offset-edges-along-a-plane

To get the desired behavior from 'alt + s', you need to be in edit mode with vertices selected. (Sounds like all vertices should be selected in your case)

Depending on how good your mesh is, the inset tool can do a pretty good job of offsetting inwards with odd shaped outlines. Press I and move the mouse to adjust the amount.
Even with the messy mesh created from converting some text to mesh, only a couple of points need fixing.


text:
How to export model with pivot in the center?
I'm trying to export a model as an .obj file from Blender and import it into Unity. In Blender the object has the pivot right in the center of the model, but when I put it into Unity the pivot appears at the bottom of the model. Here are a couple of images to better describe what I'm trying to explain:
Model in Blender:

Model in Unity:

This disorientation causes problems with rotation, transformation, etc, in Unity. I want to know how this can be fixed. Any help is appreciated.

With the object selected in Object mode, press ⎇ AltG to reset the position of the object to the world center. Some exporters will consider your object origin to be the world center, so you won't have any issues if you center your object.

There's also a posting in the SE Unity site about this: https://forum.unity.com/threads/wrong-pivot-point-from-blender-to-unity.423176/

@JohnEason yes, I decided to post here because I thought it was something more related to Blender than Unity, but it's helpful too, thanks.

@Daniel You'll see that happen occasionally with two popular programs. Don't worry about it! The same thing occasionally happens with folks using Python in Blender. :^)


text:
Emission Node, Object and Irradiance Volume Does not Get Along
Newbie here in blender.
I'm trying to understand how emission node and light probe works together.
I have set up a simple scene that has a light source, floor and a circle.
There are things that I need help in understanding:

Whenever I move the plane closer to the light source, the light is not visible anymore on the plane surface.

When I do the opposite, moving the plane away from the light source, the light is getting distorted (see image).

Lastly, whenever I place an image in front of the light source it does not cast a shadow and the bottom of the circle is also filled with light (I was expecting to have the bottom of the circle darker since it is already beneath). Rather, its having this dark part at the top.

Below are the set up:

I hope that I'll be as accurate as possible in my explanations:
When you bake the Indirect Lighting, the Irradiance Volume will catch all the light sources of your scene (lights, objects with emission, world) through the little dots that you can see in the cube. Once you've baked, these same dots will give back what they've saved, as if they were small light sources themselves. If they were behind an object and couldn't catch a light, they won't emit anything of course, and therefore will recreate a kind of shadow.
Note that they won't cast shadows themselves. Also, the bake precision will depend on the cube resolution. As for this kind of artefacts, it comes from the combination of these several dot lights, you can avoid that with the Irradiance Smoothing value.
Irradiance Volume came to compensate the light limitations in Eevee (as Eevee doesn't calculate indirect lights, or doesn't take emission into account, etc), it may be useful in some situations but it's probably easier to create new light sources in order to fake indirect lighting, to create shadows for emission objects and so on...


text:
Flickering strokes when changing stroke depth order to 3D location in Grease Pencil
Hello Blender Community,
When I change the stroke depth order to 3D location, strokes drawn with a brush that has opacity appear to flicker depending on the viewing angle. Is there any solution or workaround to fix it?

Thank you in advance for any assistance you can provide.
Best regards,

The problem that you are encountering may be Z-Fighting. It is typically caused by overlap. Grease pencil objects are most effective when used in 2D Layers. Therefore, the reason you are encountering this problem is most likely because you switched to 3D Location. In 3D space, your grease pencil object will encounter similar problems that other 3D-objects face.
A quick fix is to adjust the Clip Start of your view to a bigger value.

If this doesn't work, then you may need to share an example file using https://blend-exchange.com/. To determine the actual reason for your flickering or provide an in-depth solution would require more detailed information.

Thank you so much for your answer! Unfortunately, the Clip Start method didn't work well in my side :(
I have deleted the blender data using for the original post, but I have made the same file has the same problem.

I understood the grace pencil is made for making 2D animation, but I want to make a hand-drawn 3D artwork, so It would be great if there are some tricks or something to avoid this issue.

Ah, now I see what is happening in your file. It was not any of the settings, but the Air brush that you were using that caused the flickering. That brush has always been problematic. I've rarely seen anyone use it because of the issues it causes. I think the work around would be create your own custom Air brush with the opacity settings.


text:
Addon: how to update filename on EnumProperty change?
I'm working on a Blender (2.93) addon that outputs models to a few different formats. There is an EnumProperty in the filebrowser which lets the user choose which format to output to. The formats are different enough that I feel they should each have their own filename extension, but I cannot figure out how to do this properly.
This is the code I'm using for exports, with some of the irrelevant properties trimmed out:
class ExportData(Operator, ExportHelper):
    bl_idname = "export.gtd"
    bl_label = "Export"

    filename_ext = ".buf"

    def update_ext(self, context):
        new_ext = ".buf"
        if self.output_type == 'vertex_buffer':
            new_ext = "buf"
        else:
            new_ext = "gml"
        params = context.space_data.params
        context.space_data.params.filename = f"{Path(self.filepath).stem}.{new_ext}"

    filter_glob: StringProperty(
        default="*.buf;*.gtd",
        options={'HIDDEN'},
        maxlen=255,
    )

    output_type: EnumProperty(
        name = "Output Type",
        description="The type of data to output",
        items = (
            ('vertex_buffer', "Vertex Buffer", "A vertex buffer that can be loaded at runtime"),
            ('debug', "GTD Script (debug)", "A human-readable script that can be used to import and debug"),
        ),
        default = 'vertex_buffer',
        update = update_ext,
    )

    def execute(self, context):
        return export_gtd(context, self.filepath, self.output_type)

When I run this code, I can use the console to verify that the filename_ext changes, and it will print the correct filename if I print context.space_data.params.filename. There are two problems, however:

The filename_ext variable always forces a single filename extension on the output, and I can't figure out how to change it.
The actual filename at the bottom of the filebrowser doesn't update when I change the choice in the EnumProperty.

I've been studying this answer: Addon: how to make Blender run check()/redraw when option changed?, but the suggestions/solutions there don't seem to work. Would appreciate any help pointing me in the right direction on this!

https://blender.stackexchange.com/questions/203747/addon-how-to-make-blender-run-check-redraw-when-option-changed  https://blender.stackexchange.com/questions/198831/right-way-to-stop-export-operator-from-saving-with-empty-filename/198924#198924

The code I ended up with is this. Most obvious difference is the update function is a free function, not a member function like you have.

Thanks for the replies - still a little unclear on what makes the filename update, however. @scurest - Just to test, I can drop in the two functions you've written, on_export_format_changed and ensure_filepath_matches_export_format, and I can print out what's returned at the end to see that the correct filename is produced.
The filename in the window does not update, though - and any attempt to change the extension by typing a new one in is just reset every time the filename box loses focus.
Is there some aspect of the filebrowser window that needs to be overridden?

Oops - I just noticed in the link that @batFINGER shared that you added the check() to your export class, and now that seems to be working correctly for me.
I think that might be the solution I was missing. Thank you both for your help!


text:
How to make the insets on either side of this cyllinder symmetrical
From there, I'll be adding asymmetrical elements, like the cavity you can see on the one side, and a protruding element on the other. I want to stick multiple cyllinders together and have them fit end to end using that cavity-protrusion method (like an electrical socket). This, I assume, means I can't just use a modifier.

Tl;dr I just want the insets to be symmetrical

Thanks!

I am not sure what you are trying to achieve, have you tried using the mirror modifier along Z with "bisect" checked ?
Could you add a little diagram of the expected end result ?

Apologies the original question was vague, I added a diagram to better explain. I want symmetrical insets on both flat ends of a cylinder, with a couple faces on one end extending outwards, and a couple faces on the other, moved inwards. That way, if you stack multiple length-wise, they would slide into each other. In order for that to happen though, I need to start with symmetrical insets

Well, you could build the symmetrical elements first using the Mirror Modifier first.

Then apply the modifier, and work on the asymmetrical elements.

Edit
Ok, based on that additional info, here's how you could go about doing so:
Create the first cylinder with the cuts. Then duplicate it, and flip the second one so that the insets are facing each other. Then, just grab the extruded faces, and move them in/out of the cylinder face by the same distance that you did for the first one. You can type in distances after activating the grab tool for exact distances.

I really appreciate you going through the process of building it to explain. I don't think I posed my question properly, but I meant on either side of the cylinder. I put a diagram in my original question to show what I mean. I want symmetrical insets, but on one side, I want certain faces to protrude, and on the other, certain faces to move inwards. That way, if you stack multiple length-wise, the protruding shaft of one cylinder would fit into the concave part of the next cylinder.

Alright, updated the answer


text:
Why my spot lights do not work properly?
I have set up a simple scene with an Armature and a slightly bend floor. Each object in the scene has a Principle BSDF assigned to it. After I rendered the scene using a simple World Light and one Sun Light, I wanted to introduce some proper lighting.
I made the Sun Light a Spot Light, positioned it, copied it 5 times and aligned them to a grid. While looking in Render View I noticed that none of these lights actually do something.

Q: What am I doing wrong?

From your screenshot, your lamp is only rated as outputting 1 Watt of power. You are effectively trying to illuminate your scene with around 6 Watts of power - 1/10th of a 60W lightbulb, presumably at many metres (Blender Units) range - so your scene is almost completely dark.
You need to simply increase the output of those lamps to more reasonable levels - eg, 600 Watts per lamp would be more reasonable.
I suspect you have gotten into this situation by duplicating the original Sun lamp and changing its type to 'Spot' without changing its output. Note that Sun lamps are rated in 'Strength' - with a strength of '1' equating to 1 'Sun' (our sun) - but Spot lamps are rated in 'Power' (in Watts). When you change the lamp type the Strength gets changed to Power but the value remains the same (so 1 'Sun' gets changed into a 1W lamp). When changing between types, always check the other settings to ensure they are still reasonable for your situation.
In summary, increase the output from your lamps.

Ah, thank you, i didnt even notice that. I am not used to using metric measurments in blender.


text:
Update Blend File with Many Python Scripts by Command Line
This linked post does not answer the question. That post is for a single script, and to do this, you still need the GUI. I have no GUI access and 1000 unique script files. I do not think this will work. The only work around I have found is to not use render farms and instead use a computing cluster like aws where you can use the command line below to render.

I have 1000 script files that set various parameters of my Blend scene.
Previously, I have been rendering with the command line like this:
Blender -b myFile.blend -P myScript0001.txt -f 1
Blender -b myFile.blend -P myScript0002.txt -f 2
Blender -b myFile.blend -P myScript0003.txt -f 3

In order to render this on a render farm, I cannot use the script files, they must be included in the Blend file. Is there a way to update the blend file to include the script file by the command line? I do not have the option to use the GUI to do this.
Or maybe I reference a json file in my script that I host publicly on my website? Is something like this possible, for example:
#myScript0001.txt
import bpy
bpy.data.objects["Empty"].location[0] = {link-to-json-file}

Read the files write to text, save blend.
Here is an example script.

Globs all text files in folder (hardcoded, could pass as argument)

Create a textblock with same stem name

Read the contents into textblock

Save blend to keep changes.

Script, edit directory path to suit.
import bpy
from pathlib import Path

# glob all txt files from
dir_path = "/home/batfinger/foo"
txt_dir = Path(dir_path)

# glob for txt files.
glob = "*.txt"

for f in txt_dir.glob(glob):
    text = bpy.data.texts.new(f.stem)
    text.write(f.read_text())

# save
#bpy.ops.wm.save_mainfile()

This works, thank you! Simple solution


text:
Why my texture becomes black in certain regions?
I'm trying to implement some kind of Ian Hubert style. I use a PBR texture for the wall, mixed a brick PBR texture with a moss PBR texture and used some other image textures for the windows and such. As you can see in the following image, the texture gets black for whatever reason:

The same thing happens in the viewport preview (it's a different version of the scene):

How do I mix the textures:

As you can see the texture becomes black at a certain angle. The blend mode is set to opaque:

Interestingly, there is no issue when using Eevee:

I don't get why is this is happening and what I can do to get rid of those artefacts. Can you guys please give me any advice or ideally some suggestions how to fix this in cycles?

Ummm, where does the texture get black?

hello, maybe show some screenshots of your node setup, it's hard to guess without it

Blending mode would only be related here if you were trying to render image with transparency since it controls how transparent parts of textures are rendered if at all. It looks in your case like improper rendering of bump/normal map. Unfortunately node setup isn't visible since nodes're too small

Agree with MrZak. Recommend add a better screenshot of your nodes in order to get help, otherwise it's just guessing what the issue is...

in case several textures are overlaying - I assume the green parts contain an alpha channel - have you enabled the Blend-Value within the Render-Settings?

i have enabled the blend mode to opaque and shadow mode but it's not solving the issue


text:
Sculpting models
I've heard that when you're modeling, sculpting a rough draft of your model then retopologizing (making a final draft by placing and connecting vertices) is the most conventional way of modeling.  But I'm wondering if it's conventional to use sculpting tools on a retopologized model.  Is sculpting only reserved for rough drafts?

This depends a lot on what you plan to do with the model and the type of sculpting you plan on using.
I think what you're thinking of is Dynamic topology sculpting. This is really really good for getting proportions and general form right. The issue with this type, is that it completely triangulates which ruins edge flow, making it bad for animation and texturing. It would be okay to use this for a simple shader only (or procedural) material setup.
The other type of sculpting is Multires. This is best used for detail sculpting, especially when you want to texture, or animate, because it keeps the original edge flow intact. This is probably what you want. To use it, you add a multi-resolution modifier to your mesh (which is basically a specialized subserf modifier), and you sculpt at the level of detail that it adds, then you press the subdivide button to subdivide it again, and you can work on detailing even more at that level, and the process continues. Just remember that you want to do as much detailing as you can at one level before continuing to the next.


text:
DoF works only sometimes in blender render
I'm trying to use blender render and the defocus node to shift focus over the course of a scene (by moving the empty around). This works fine.
The red bits in this image are out of focus, since the empty is way behind them:
(image removed)
In this next image, the red bits are only out of focus where they do not overlap with the structures in the background... why?

I'm stumped. Anyone have a suggestion?
Thanks!
Andrew
Edit: Here's my node editor view (had to remove one of the other images due to lack of "reputation"):
(image removed)
Edit2: 3D View
(image removed)
Edit3: Cycles renders

Looks like a "wrong" composite layer order. Could you post your composite setup?

thank you @Carlo for the swift response. Not sure what you are referring to. Where do I find the composite setup? I've setup the nodes as described in various DoF tutorials with the defocus 'image' output feeding into the composite node (Alpha: 1, Z; 1).

I mean the node editor, set to "compositing". Where you can tweak the "Defocus" node.

... ok. I've posted the node editor. I only have one layer...

Yes, I guessed wrong! May I ask if the rectangles in the render view are "the background"?

Yes, the rectangles are the background structures I was referring to.

But they are made by "real geometry", or what we see is just the background color? link a screenshot of the 3d viewport in the comments if you can

I've posted the 3D View. I'm using two dimensional objects to simulate what's going on in a microscope. The camera provides a 'bird's eye view' of the scene. By moving the empty up and down (on Z) I change the 'microscope's' focus.

I'm not able to answer your question properly, but I would post some thought about it anyway...maybe they can help.
Z-depth is a pass that stores the height information about what the camera sees.

This pass can be used to fake a lens blur effect. What has the empty's same z-value is in focus, while the other object are blurred. I might be wrong, but I think that the defocus node does not consider wich face is in front of another, but set only the amount of blur by the face z-depth

In the image above, the grey grid is the background. It has no geometry, so it has no-z informations. When the red square is blurred onto, it has no issue, there is nothing behind.
When the red square is upon the white rectangle, which is a face, and has z-info, there is a conflict in the contended area. The border pixel of the square must be blurred, so they should go upon the white square, but at the same time, that pixel should be white and in-focus, so the blur is not visible anymore.

One way to avoid this difference on the border blur is to remove the background from the view by adding a plane behind the white rectangles. You could also achieva a similar result by tweaking z-depth channel with nodes... But while we have obtain a consistent behaviour, I think that is not probably the desired one.

What you probably want is a blurred image upon a not blurred one. One way could be to separate objects in different scene, apply the node only to the geometry you know above and than mix them with alpha over node. But this is not a good solution for an animation.

A second option could be to switch to Cycles render. With his path tracing abilities, you don't need to fake the lens effect, but you can obtain a physically belivable behaviour, at the cost of longer render times.

Thanks again for the detailed explanation. I tried cycles but got the same strange result... I inserted the result in my original post...

Thtìs strange! If you could uplad your blend file whith blend-exange, I'll give a further look

Carlo, thank you for your assistance and offer for further help. Since I don't like the 'look' I get when using Cycles, I decided to use your suggestion with different render layers. The only downside is that I have to set an additional keyframes every time I move the 'empty'... I simply manually keyframe the Z height in the background's defocus node.  ... so for me, the problem is solved.

I did some experimenting yesterday with the default blender scene (cube, lamp, camera) by simply adding a sphere above the cube and an empty and playing around with things. I got the exact same issue - so it's not something with my blend file, but an intrinsic problem with the strategy blender render uses to 'fake' DoF - as you explained in your answer...

... anyway, thanks again for helping this newbie out ... I learned a lot in the past 24h!


text:
Armature/Bone Heat Failed
I have a model which have meshes that are not aligned at x axis. When I try to use automatic weight for connecting bones to meshes, I get "Bone heat weighting: failed to find solution for one or more bones" error. If I align bones to x axis, automatic heat weighting works but it is not suitable for my model.
I deleted all double vertices. And there are no open surface. Do you have any suggestion?

I would reccommend a few things:

Start with the bird in an easy rest position:
Right now you have it set so that the wings are in an up position. This can complicate rigging and could result in artifacts when the wings are in the down position.
If automatic weights do not work, you may need to weight paint manually: Automatic weights are designed to be a time saver, but may not work in all instances. It may become necessary for you to paint the weights manually

You may want to watch a few rigging tutorials and try to apply those concepts to this project, as I think there is no one right answer, but rather a set of toolsets that can be applied to each situation depending on the conditions.


text:
Drivers don't see the final rotation of a constraint. How to get copied rotation instead of (0,0,0)?
The Premise:
Say you have a driver on Bone A that makes it's rotation = 50% of the rotation of Bone B.
Bone B has a copy rotation constraint to copy Bone C's rotation.
My expectation would be that Bone A's rotation would be 50% of Bone C's rotation.
The problem:
Bone A does not rotate at all because the driving rotation property on Bone B still shows as 0, 0, 0 even though Bone B has visibly copied the rotation of Bone C.
How would I get a driver to see the final rotation of a bone after applying it's constraints?
EDIT: A tangential part of my problem was I was using the "RNA" "Single Property" for the driver, but by switching to "(x) Transform Channel" I can then specify local space and get the result I want.

Idk if this would help but maybe try using a driver on bone B that copy's bone C's rotation instead of using a constraint. Or make Bone A copy 50% of the rotation of bone C using drivers.

Let's reproduce the issue: two cubes, one copying the rotation of the other using a constraint. Each cube has a Suzanne copying the rotation of the cube in front of it, using a driver.

the driver for "sleeping" Suzanne:

Changing its type to Scripted Expression, default variable type to  Transform Channel and the property type to the rotation axis of your interest:

Thanks! It seems I've been using RNA instead of transform channel. Switching and doing what you said solved my problem!


text:
Why does perspective always have xray on?
When I toggle x-ray in Edit mode, only the orthographic views toggle. The perspective view constantly shows xray and it is super annoying. I see face handles (the square to select them) as well as edges and vertices through the faces just as if xray was on, but it's not.
How can I turn it off so that while in Edit Mode, and with Solid display mode selected, I don't see through things as if xray mode is on?
Thanks]1
Left: In Edit Mode
Right: In Object Mode
Basically I don't want to see the edges and face handles through the faces in front of them.

Could you upload a screenshot, so we get a better idea of what you mean

Are you talking about the 'Limit Selection to Visible' checkbox (just to the the right of the 'Face Select Mode' button?

I updated. I was mistaken about seeing faces blended through.

Related: http://blender.stackexchange.com/q/28443/599. Though I suspect the problem is actually this: http://blender.stackexchange.com/q/1385/599

This occurs due to your Start Clipping being to small, to fix that open up your NPanel, then go to the View section and change the Start clipping value to 0.100

Or either it could be the Limit Selection to visible button next to the Vertex/Edge/Face Select properties, as mentioned by Mike Metcalf

It was the clipping plane starting too soon. The "Limit Selection to Visible" button is what I was referring to when talking about "xray". I thought that was what it is called because the Lynda.com training refers to it as the xray mode or something.


text:
Headless render: can't find compute_device in 2.78b
On Ubuntu 16.04 (used as a headless renderer with dual GTX 970 STRIX GPUs) after upgrading to blender 2.78b I'm now seeing:
$ blender -b Lightsaber.blend -o //Lightsaber-tst-1_ -E CYCLES -F PNG -x 1 -P cuda0.py -f 1
AL lib: (WW) alc_initconfig: Failed to initialize backend "pulse"
ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave
AL lib: (EE) ALCplaybackAlsa_open: Could not open playback device 'default': No such file or directory
read blend: /home/shady/usermaatre/School/Lightsaber.blend
Traceback (most recent call last):
  File "/home/shady/usermaatre/School/cuda0.py", line 4, in <module>
    bpy.context.user_preferences.system.compute_device_type = 'CUDA'

The cuda0.py script is simple (it comes from BlenderArtists):
$ cat cuda0.py
import bpy, _cycles

bpy.context.scene.cycles.device = 'GPU'
bpy.context.user_preferences.system.compute_device_type = 'CUDA'

# this is different in each cuda[x].py file, CUDA_0, CUDA_1, CUDA_2, CUDA_3
bpy.context.user_preferences.system.compute_device = 'CUDA_0'

I had been running NVIDIA-Linux-x86_64-367.44.run and cuda_7.5.18_linux.run so we tried upgrading to the latest NVIDIA-Linux-x86_64-375.39.run and cuda_8.0.61_375.26_linux.run but that did not help.
I figured maybe the CUDA card has been renamed, so I tried running the script at  How do I get Cycles to use GPU on a linux server? and I get a similar result:
$ blender -b -P compute_device_type.py
AL lib: (WW) alc_initconfig: Failed to initialize backend "pulse"
ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave
AL lib: (EE) ALCplaybackAlsa_open: Could not open playback device 'default': No such file or directory
Traceback (most recent call last):
  File "/home/steven/usermaatre/School/compute_device_type.py", line 7, in <module>
    devt = sysp.compute_device_type
AttributeError: 'UserPreferencesSystem' object has no attribute 'compute_device_type'

Blender quit

I'm thinking that something has changed in the naming of the card? Is there a simple way to determine the card attributes? And should the 8.0 drivers work on a headless system or should I go back to 7.5? I'd really rather not have to drop back to 2.78a which had worked...

From the 2.78b, it's necessary to recover them via the preferences of the Cycles addon.
You cant get it with
bpy.context.user_preferences.addon['cycles'].preferences.compute_device_type

And for the devices:
for card in bpy.context.user_preferences.addons['cycles'].preferences.devices:
    print(card.name)

Also of note - compute_device_type is an enum - so if you try compute_device_type = 'XXX' you will get a TypeError message that lists the valid enum values.

@sambler @pistiwique Thanks, I get enum "XXX" not found in ('NONE', 'CUDA') so setting  prefs.compute_device_type = 'CUDA' works and both cards are used. I would also like to be able to address GPU0 & GPU1 separately, but prefs.compute_device = 'CUDA_0' fails.

I haven't tested this but it appears that the devices list shown in the above loop, is what you use to enable/disable devices. Set compute_device_type = 'CUDA' and then use addons['cycles'].preferences.devices[0].use = False to disable the first device and devices[1] for the second. Each device has id, name, type and use properties.

@sambler thanks - prefs.devices[0].use = False worked! The above loop printed out <bpy_struct, CyclesDeviceSettings("GeForce GTX 970")> twice but I was not able to determine the deeper structure. How did you determine to set .use = False (where the old way was .compute_device = 'CUDA_0')? I wonder what other options might exist?

I used the source @ShadyPuck ;) - You can find CyclesDeviceSettings defined in properties.py inside the cycles addon. I expect this is a simpler approach to controlling the many variations of different devices. It has just been added so expect more changes to come.

It seems this method doesnt work with 2.79?
I get the error:
AttributeError: 'UserPreferences' object has no attribute 'addon'
Edit:
Got it working!    a stupid missing 's'
Here is the working script i'm using to force the worker station to use all cuda devices:
import bpy
bpy.context.user_preferences.addons['cycles'].preferences.compute_device_type = 'CUDA'
bpy.context.user_preferences.addons['cycles'].preferences.compute_device = 'CUDA_MULTI_2'