text:
List blendfile.py fields for RenderData
I want to read various info from a blend file without opening it and know that blendfile.py is the way to go (to be found here on pypi and here on developer.blender.org.
I managed to succeed in a certain way:
path = "../tests/resources/100_frames_step10.blend"

import blendfile

try:
    with blendfile.open_blend(path) as blend:
        scenes = blend.find_blocks_from_code(b'SC')

        # For each scene find some info and print it
        for scene in scenes:
            scene_name = scene[b'id', b'name'].decode()
            frame_start = scene[b"r", b"sfra"]
            frame_end = scene[b"r", b"efra"]
            frame_step = scene[b"r", b"frame_step"]
            x_resolution = scene[b"r", b"xsch"]
            y_resolution = scene[b"r", b"ysch"]
            # This would fail:
            # fps = scene[b"r", b"frames_per_second"]
            print(scene_name)
            print(x_resolution, y_resolution)
            print(x_parts, y_parts)
except blendfile.BlendFileError:
    print("Not a blend file")

This code reads start and end frames, frame step, scene name, resolution etc.
But I don't know how to figure out how to find (or list) the other possible fields for scene[b"r", b"foo"]. I am especially interested in the render scale settings, in the frames per seconds and so on. Does anybody have an Idea where this is documented or how I can list this?

There is the blender-bam module, the blend file reading part is included with blender, it can be found inside the Blend File Utils addon.

I already use blendfile.py, but it's usage is not very well documented and also not quite straightforward unless you already know exactly how the file needs to be decoded.

The data structure seems to be python dictionaries pointing to addresses in memory.
Given your above code you can see the dictionaries by using
DNA_struct_of_scene = scene.file.structs[scene.sdna_index]
rel_dict = DNA_struct_of_scene.field_from_name[b'r'].dna_type.field_from_name

From the dict posted below, you can use
scene[b"r",b'size']

to get the render scale and
scene[b'r',b'frs_sec']

to get the frames per second
rel dict =
 {b'im_format': <__main__.DNAField at 0x7f4e476aa990>,
 b'avicodecdata': <__main__.DNAField at 0x7f4e476aa9d8>,
 b'qtcodecdata': <__main__.DNAField at 0x7f4e476aaa20>,
 b'qtcodecsettings': <__main__.DNAField at 0x7f4e476aaa68>,
 b'ffcodecdata': <__main__.DNAField at 0x7f4e476aaab0>,
 b'cfra': <__main__.DNAField at 0x7f4e476aaaf8>,
 b'sfra': <__main__.DNAField at 0x7f4e476aab40>,
 b'efra': <__main__.DNAField at 0x7f4e476aab88>,
 b'subframe': <__main__.DNAField at 0x7f4e476aabd0>,
 b'psfra': <__main__.DNAField at 0x7f4e476aac18>,
 b'pefra': <__main__.DNAField at 0x7f4e476aac60>,
 b'images': <__main__.DNAField at 0x7f4e476aaca8>,
 b'framapto': <__main__.DNAField at 0x7f4e476aacf0>,
 b'flag': <__main__.DNAField at 0x7f4e476aad38>,
 b'threads': <__main__.DNAField at 0x7f4e476aad80>,
 b'framelen': <__main__.DNAField at 0x7f4e476aadc8>,
 b'blurfac': <__main__.DNAField at 0x7f4e476aae10>,
 b'edgeR': <__main__.DNAField at 0x7f4e476aae58>,
 b'edgeG': <__main__.DNAField at 0x7f4e476aaea0>,
 b'edgeB': <__main__.DNAField at 0x7f4e476aaee8>,
 b'fullscreen': <__main__.DNAField at 0x7f4e476aaf30>,
 b'xplay': <__main__.DNAField at 0x7f4e476aaf78>,
 b'yplay': <__main__.DNAField at 0x7f4e476aafc0>,
 b'freqplay': <__main__.DNAField at 0x7f4e476ab048>,
 b'depth': <__main__.DNAField at 0x7f4e476ab090>,
 b'attrib': <__main__.DNAField at 0x7f4e476ab0d8>,
 b'frame_step': <__main__.DNAField at 0x7f4e476ab120>,
 b'stereomode': <__main__.DNAField at 0x7f4e476ab168>,
 b'dimensionspreset': <__main__.DNAField at 0x7f4e476ab1b0>,
 b'filtertype': <__main__.DNAField at 0x7f4e476ab1f8>,
 b'size': <__main__.DNAField at 0x7f4e476ab240>,
 b'maximsize': <__main__.DNAField at 0x7f4e476ab288>,
 b'pad6': <__main__.DNAField at 0x7f4e476ab2d0>,
 b'xsch': <__main__.DNAField at 0x7f4e476ab318>,
 b'ysch': <__main__.DNAField at 0x7f4e476ab360>,
 b'xparts': <__main__.DNAField at 0x7f4e476ab3a8>,
 b'yparts': <__main__.DNAField at 0x7f4e476ab3f0>,
 b'tilex': <__main__.DNAField at 0x7f4e476ab438>,
 b'tiley': <__main__.DNAField at 0x7f4e476ab480>,
 b'planes': <__main__.DNAField at 0x7f4e476ab4c8>,
 b'imtype': <__main__.DNAField at 0x7f4e476ab510>,
 b'subimtype': <__main__.DNAField at 0x7f4e476ab558>,
 b'quality': <__main__.DNAField at 0x7f4e476ab5a0>,
 b'displaymode': <__main__.DNAField at 0x7f4e476ab5e8>,
 b'use_lock_interface': <__main__.DNAField at 0x7f4e476ab630>,
 b'pad7': <__main__.DNAField at 0x7f4e476ab678>,
 b'scemode': <__main__.DNAField at 0x7f4e476ab6c0>,
 b'mode': <__main__.DNAField at 0x7f4e476ab708>,
 b'raytrace_options': <__main__.DNAField at 0x7f4e476ab750>,
 b'raytrace_structure': <__main__.DNAField at 0x7f4e476ab798>,
 b'pad1': <__main__.DNAField at 0x7f4e476ab7e0>,
 b'ocres': <__main__.DNAField at 0x7f4e476ab828>,
 b'pad4': <__main__.DNAField at 0x7f4e476ab870>,
 b'alphamode': <__main__.DNAField at 0x7f4e476ab8b8>,
 b'osa': <__main__.DNAField at 0x7f4e476ab900>,
 b'frs_sec': <__main__.DNAField at 0x7f4e476ab948>,
 b'edgeint': <__main__.DNAField at 0x7f4e476ab990>,
 b'safety': <__main__.DNAField at 0x7f4e476ab9d8>,
 b'border': <__main__.DNAField at 0x7f4e476aba20>,
 b'disprect': <__main__.DNAField at 0x7f4e476aba68>,
 b'layers': <__main__.DNAField at 0x7f4e476abab0>,
 b'actlay': <__main__.DNAField at 0x7f4e476abaf8>,
 b'mblur_samples': <__main__.DNAField at 0x7f4e476abb40>,
 b'xasp': <__main__.DNAField at 0x7f4e476abb88>,
 b'yasp': <__main__.DNAField at 0x7f4e476abbd0>,
 b'frs_sec_base': <__main__.DNAField at 0x7f4e476abc18>,
 b'gauss': <__main__.DNAField at 0x7f4e476abc60>,
 b'color_mgt_flag': <__main__.DNAField at 0x7f4e476abca8>,
 b'postgamma': <__main__.DNAField at 0x7f4e476abcf0>,
 b'posthue': <__main__.DNAField at 0x7f4e476abd38>,
 b'postsat': <__main__.DNAField at 0x7f4e476abd80>,
 b'dither_intensity': <__main__.DNAField at 0x7f4e476abdc8>,
 b'bake_osa': <__main__.DNAField at 0x7f4e476abe10>,
 b'bake_filter': <__main__.DNAField at 0x7f4e476abe58>,
 b'bake_mode': <__main__.DNAField at 0x7f4e476abea0>,
 b'bake_flag': <__main__.DNAField at 0x7f4e476abee8>,
 b'bake_normal_space': <__main__.DNAField at 0x7f4e476abf30>,
 b'bake_quad_split': <__main__.DNAField at 0x7f4e476abf78>,
 b'bake_maxdist': <__main__.DNAField at 0x7f4e476abfc0>,
 b'bake_biasdist': <__main__.DNAField at 0x7f4e476ad048>,
 b'bake_samples': <__main__.DNAField at 0x7f4e476ad090>,
 b'bake_pad': <__main__.DNAField at 0x7f4e476ad0d8>,
 b'bake_user_scale': <__main__.DNAField at 0x7f4e476ad120>,
 b'bake_pad1': <__main__.DNAField at 0x7f4e476ad168>,
 b'pic': <__main__.DNAField at 0x7f4e476ad1b0>,
 b'stamp': <__main__.DNAField at 0x7f4e476ad1f8>,
 b'stamp_font_id': <__main__.DNAField at 0x7f4e476ad240>,
 b'pad3': <__main__.DNAField at 0x7f4e476ad288>,
 b'stamp_udata': <__main__.DNAField at 0x7f4e476ad2d0>,
 b'fg_stamp': <__main__.DNAField at 0x7f4e476ad318>,
 b'bg_stamp': <__main__.DNAField at 0x7f4e476ad360>,
 b'seq_prev_type': <__main__.DNAField at 0x7f4e476ad3a8>,
 b'seq_rend_type': <__main__.DNAField at 0x7f4e476ad3f0>,
 b'seq_flag': <__main__.DNAField at 0x7f4e476ad438>,
 b'pad5': <__main__.DNAField at 0x7f4e476ad480>,
 b'simplify_flag': <__main__.DNAField at 0x7f4e476ad4c8>,
 b'simplify_subsurf': <__main__.DNAField at 0x7f4e476ad510>,
 b'simplify_subsurf_render': <__main__.DNAField at 0x7f4e476ad558>,
 b'simplify_shadowsamples': <__main__.DNAField at 0x7f4e476ad5a0>,
 b'pad9': <__main__.DNAField at 0x7f4e476ad5e8>,
 b'simplify_particles': <__main__.DNAField at 0x7f4e476ad630>,
 b'simplify_particles_render': <__main__.DNAField at 0x7f4e476ad678>,
 b'simplify_aosss': <__main__.DNAField at 0x7f4e476ad6c0>,
 b'cineonwhite': <__main__.DNAField at 0x7f4e476ad708>,
 b'cineonblack': <__main__.DNAField at 0x7f4e476ad750>,
 b'cineongamma': <__main__.DNAField at 0x7f4e476ad798>,
 b'jp2_preset': <__main__.DNAField at 0x7f4e476ad7e0>,
 b'jp2_depth': <__main__.DNAField at 0x7f4e476ad828>,
 b'rpad3': <__main__.DNAField at 0x7f4e476ad870>,
 b'domeres': <__main__.DNAField at 0x7f4e476ad8b8>,
 b'domemode': <__main__.DNAField at 0x7f4e476ad900>,
 b'domeangle': <__main__.DNAField at 0x7f4e476ad948>,
 b'dometilt': <__main__.DNAField at 0x7f4e476ad990>,
 b'domeresbuf': <__main__.DNAField at 0x7f4e476ad9d8>,
 b'pad2': <__main__.DNAField at 0x7f4e476ada20>,
 b'dometext': <__main__.DNAField at 0x7f4e476ada68>,
 b'line_thickness_mode': <__main__.DNAField at 0x7f4e476adab0>,
 b'unit_line_thickness': <__main__.DNAField at 0x7f4e476adaf8>,
 b'engine': <__main__.DNAField at 0x7f4e476adb40>,
 b'bake': <__main__.DNAField at 0x7f4e476adb88>,
 b'preview_start_resolution': <__main__.DNAField at 0x7f4e476adbd0>,
 b'debug_pass_type': <__main__.DNAField at 0x7f4e476adc18>,
 b'pad': <__main__.DNAField at 0x7f4e476adc60>,
 b'views': <__main__.DNAField at 0x7f4e476adca8>,
 b'actview': <__main__.DNAField at 0x7f4e476adcf0>,
 b'views_format': <__main__.DNAField at 0x7f4e476add38>,
 b'pad8': <__main__.DNAField at 0x7f4e476add80>,
 b'mblur_shutter_curve': <__main__.DNAField at 0x7f4e476addc8>}

Followup question:
When I try to get the im_format I will get a error: Error: ("(b'r', b'im_format') exists but isn't pointer, can't resolve field b'im_format'", DNAName(b'im_format'), DNAStruct(b'ImageFormatData')) It is clear that I somehow need to decode that DNAStruct, but I am a bit confused how.


text:
Making a chain of bones without bpy.ops
While making mesh objects with Python, I felt encouraged by the community to avoid using bpy.ops, as it is less efficient.
I am now making armature objects.
I am making a kind of snake where the body will simply follow a curve, but the 'neck' will have a 2 stage IK rig with two control bones. This code makes one neck.
The def contains my effort so far, based on what I learned from meshes. I'm still working in 2.83 due to other code I have.
I have got this far with bpy.ops and could carry on, but I would like to know the bones better.
import bpy
from math import pi, radians

# Rig A
rot_x = radians(10)
rot_z = radians(-0.33)
xlate = -0.01
bpy.ops.object.armature_add(
    radius=0.0125,
    location=(-0.009134, 0.25, 0.0),
    rotation=(pi/2, 0.0, rot_z))
ob_a = bpy.data.objects.get('Armature')

# Make a chain of bones, including some pose angles while the
# extrude bone is selected
bpy.ops.object.mode_set(mode='EDIT')
for i in range(45):
    bpy.ops.armature.extrude_move(
        TRANSFORM_OT_translate={"value":(0, xlate, 0)})
    bpy.ops.transform.rotate(value=rot_z, orient_axis='Z')
    if i > 40:
        bpy.ops.transform.rotate(value=rot_x, orient_axis='X')

arm_a = bpy.data.armatures.get('Armature')
# deselect the last extruded bone's tail, works in edit mode!
bn = arm_a.edit_bones[-1]
bn.select_tail = False

# Make a copy of two bones for use as control bones later,
# one halfway along the chain, one near the end
control_neck = arm_a.edit_bones.get("Bone.020")
control_head = arm_a.edit_bones.get("Bone.044")

arm_a.edit_bones.active = control_neck
arm_a.edit_bones.active = control_head
control_neck.select = True
control_head.select = True

# must select tail in object mode
bpy.ops.object.mode_set(mode='OBJECT')
control_neck.select_tail = True
control_head.select_tail = True
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.armature.duplicate_move(
    TRANSFORM_OT_translate={"value":(0.0, 0.0, 0.02)})

bpy.ops.object.mode_set(mode='OBJECT')

I have tried without bpy.ops and come to a halt.
import bpy
from math import pi, radians
from mathutils import Matrix, Vector

def new_armature(name):
    arm = bpy.data.armatures.new(name)
    obj = bpy.data.objects.new(name, arm)
    bpy.context.collection.objects.link(obj)

    return obj

# Rig A
rot_x = radians(10)
rot_z = radians(-0.33)
xlate = -0.01

ob = new_armature('Armature')
ob.location = (-0.009134, 0.25, 0.0)
ob.rotation_euler = (pi/2, 0.0, rot_z)
ob.scale = (0.0125, 0.0125, 0.0125)
bpy.context.view_layer.objects.active = ob
ob.select_set(True)
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
edit_bones = ob.data.edit_bones
identity = Matrix()
for i in range(12):
    bone_name = 'b.0' if i < 10 else 'b.'
    b = edit_bones.new(bone_name + str(i))
    b.tail = (0.0, 0.0, 1.0)
    if i:
        b.transform(Matrix.Translation((0,0,1)))# just a stab in the dark
        b.parent = prev
        b.head = prev.tail
        b.tail[2] = prev.tail[2] + 1.0
        b.use_relative_parent = True
    prev = b
bpy.ops.object.mode_set(mode='OBJECT')
# Parenting looks ok in Outliner, but bones don't seem connected

I am obviously missing something, or need pointing to the next step. The bpy.ops bones are connected when grabbed (G) in edit mode, but the other code they are not.
My bpy.ops code works ok; note however that 'duplicate_move' only works if a bone AND its tail are selected, and the tail has to be selected in object mode.
Nevertheless I found this was easier than adding new single bones, and orienting/scaling them to the desired bone positions.

As far as I know, with running bpy.ops.armature.duplicate() the new bones are connected by default. Not so when using edit_bones.new(). So insert b.use_connect = True at the end of the if i: block to connect bones with parents.

Thank you! I had overlooked that property and it is False by default.

source: Stack Exchange

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

sort: votes


text:
Selecting presets in Light Paths for Illumination
Trying to reduce fireflies in a dark indoor scene, lit from hdr, the Blender manual suggests trying the Limited Global Illumination preset in light paths. (Using 2.92; manual is 2.93).
I confess I cannot understand how I am supposed to select one of the presets listed, nor which preset (if any) is the default setting. The options only show '-' signs. Does a particular object have to be selected? Does it not apply to filmic rendering?
I also tried with a fresh download of 2.93 and it comes up with errors, suggesting the default cannot be changed. Also the '+' sign reveals
Error: Python: Traceback (most recent call last):
       File "C:\Program Files\Blender Foundation\Blender 2.93\2.93\scripts\startup\bl_operators\presets.py", line 171, in execute
value = eval(rna_path)
File "<string>", line 1, in <module>
AttributeError: 'CyclesRenderSettings' object has no attribute 'blur_glossycycles'

location: <unknown location>:-1

How do I change it, or can I not?
This question:
No "full global illumination" option in light path settings in Cycles?
helped me find the integrator scripts at Blender/2.93/scripts/presets/cycles/integrator/full_global_illumination.py and /limited_global_illumination.py.
This gives me a better understanding of what presets are, but leads me to imagine that the presets panel should be able to call one of the scripts?

I see I'm thinking backwards; is it  rather that changing a setting enables the change to be stored as a new preset in a script?

This seems to be a long-running problem, on and off, since 2.80. I notice that the behaviour is different even between 2.92.0 and  2.93.1.
https://developer.blender.org/T62325
"Clicking Preset doesn't change the settings immediately"

Yet in 2.93 more scripts are available, and the settings can be experimented with manually.
Scripts available are as follows:
import bpy
cycles = bpy.context.scene.cycles

# Default.py
cycles.max_bounces = 12
cycles.caustics_reflective = True
cycles.caustics_refractive = True
cycles.diffuse_bounces = 4
cycles.glossy_bounces = 4
cycles.transmission_bounces = 12
cycles.volume_bounces = 0
cycles.transparent_max_bounces = 8
cycles.use_fast_gi = False
cycles.ao_bounces = 1
cycles.ao_bounces_render = 1

#Direct_Light.py
cycles.max_bounces = 8
cycles.caustics_reflective = False
cycles.caustics_refractive = False
cycles.diffuse_bounces = 0
cycles.glossy_bounces = 1
cycles.transmission_bounces = 2
cycles.volume_bounces = 0
cycles.transparent_max_bounces = 8
cycles.use_fast_gi = False
cycles.ao_bounces = 1
cycles.ao_bounces_render = 1

# Fast_Global_Illumination.py
cycles.max_bounces = 8
cycles.caustics_reflective = False
cycles.caustics_refractive = False
cycles.diffuse_bounces = 1
cycles.glossy_bounces = 4
cycles.transmission_bounces = 8
cycles.volume_bounces = 2
cycles.transparent_max_bounces = 8
cycles.use_fast_gi = True
cycles.ao_bounces = 2
cycles.ao_bounces_render = 2

# Full_Global_Illumination.py
cycles.max_bounces = 32
cycles.caustics_reflective = True
cycles.caustics_refractive = True
cycles.diffuse_bounces = 32
cycles.glossy_bounces = 32
cycles.transmission_bounces = 32
cycles.volume_bounces = 32
cycles.transparent_max_bounces = 32
cycles.use_fast_gi = False
cycles.ao_bounces = 1
cycles.ao_bounces_render = 1

# Limited_Global_Illumination.py
cycles.max_bounces = 8
cycles.caustics_reflective = False
cycles.caustics_refractive = False
cycles.diffuse_bounces = 1
cycles.glossy_bounces = 4
cycles.transmission_bounces = 8
cycles.volume_bounces = 0
cycles.transparent_max_bounces = 8
cycles.use_fast_gi = False
cycles.ao_bounces = 1
cycles.ao_bounces_render = 1

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


text:
Can I create a custom shelf without scripting?
Coming from Maya, I find essential to have my own custom shelf with my most used shortcuts. Can I create one in Blender without scripting it with Python? I can script it if needed
EDIT:
I'm refering to this: http://worldofleveldesign.com/categories/3d-game-modeling/beginner-series/images/11-mayalt-custom-shelf-01.jpg as the thing I'm looking for. In Maya you can press that little nut in the left to create new tabs and you can press Ctrl + Shift + Clic in any of the tools to create a shortcut inside that tab.

There is no drag'n drop thing, although easy to achieve with basic python knowledge. Can you specify what you'd like to have?

Are you asking how to modal a shelf in blender?

I was refering to this: http://worldofleveldesign.com/categories/3d-game-modeling/beginner-series/images/11-mayalt-custom-shelf-01.jpg
as the thing I'm looking for. In Maya you can press that little nut in the left to create new tabs and you can press Ctrl + Shift + Clic in any of the tools to create a shortcut inside that tab.

There is no way that I know of natively in blender without using python.
That said, basic ui stuff for blender is fairly simple, so long as you just want to chuck existing operators/functions on a panel.
See How to create a custom UI? for a quick intro.
If you don't want to learn python, you could try this paid addon (it claims to do more than just pie menus, side panels as well):
https://blendermarket.com/products/pie-menu-editor
(disclaimer: I have never used this addon, so I have no idea how well it works)

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


text:
Material Overrides for view layers (per object)
I've been a casual Blender user for some time now. Really enjoying the progress in 2.8, and use this now over maya for most modeling needs, and would love to ditch autodesk altogether, but there are some serious limitations.
First on the list to make this a viable replacement for a team such as ours are some questions related to the view layers.
Maya refers to these as render layers, and a core feature of a render layer is the ability to override ANY node, object, material, or light properties on a per render layer basis.
One common usage of this workflow would be to override the material to alter output (ie change it entirely, not just an aov, not a shadow catcher, and not overriding all materials on all objects at once).
I've seen nothing covering this kind of workflow in Blender.
This goes well beyond the holdout / indirect toggles allowed in the outliner, And the only way I can see to do this (since materials are linked to mesh or object data only) is to link to object, then duplicate the object (even if the mesh is instanced), and this is still far from ideal.
Thanks for any guidance.

I think it would be helpful for others if you would rename your question to something like "Does Blender have render layers like Maya for material overrides etc.?"

I have a bunch of things that more broadly fall under this category, but since this deals with the materials I've changed the title to reflect that... Thanks

That is the answer in how to override all objects and exclude some from the override https://youtu.be/FiiizezgNAc

Actually Blender is pretty great at Render Layers:

you have collections which is kind of like a supercharged group (one object can be in multiple collections, collections can be instanced in other scenes, like Maya's references)
you have view layers, which can contain collections can set which passes to render, to override materials etc. (this is render engine specific, I'm referring to Cycles here, Eevee doesn't support that)

You can read more about it in the Blender manual on view layers

Thanks for the reply TeeTrinker, but this is not an answer to my question. The override needs to be on a per object basis, not for an entire layer... otherwise you'd have numberOfObjects * numberOfPasses viewLayers, and sometimes they still need to interact with each other.
The Blender Today stream I watched yesterday shed some light on this matter, dealing with overrides of attributes, and basically they might in some limited way be available in 2.81   :(

Sorry if I misunderstood, but even after reading your initial question again I don't think your question reflects what you are saying now, i.e. that you want to override many single options in a per object manner. I don't understand why you want so many overrides and how this can be done efficiently in any application. A detailed real world example might help to clarify your question, in this case not for your sake since you seem to have found your answer on Blender Today. Maybe answer your own question with a link to the video + explanation?

@sannyasi sorry, i think i got it now: Render layer = one layer to change anything on any object individually, right? Actually that would be quite useful, I agree.
I could think of some ways to work around that in a lot of situations, but of course not  in an unlimited way. You could take a look at cryptomattes or for stills you could just animate the changes, but again, that's not as flexible as what you are used to.

I second this question. It is a super common use case to render material variants on the same geometry on object basis. I could not find a efficient way yet to achieve this in Blender 2.9 up to now. The natural spot to look for that would be in view layers but its not available. Or i am doing it wrong.

Here is one way to have a single object with multiple materials that are selected by view layers.

Select the cube and change the data block link from data to object. You will have to reselect the material for the cube.

Duplicate the collection as linked.

Exclude the new collection from the default view layer.

Create a new view layer.

Swap the view layer exclusion settings for the new view layer so that the original collection is hidden from view. Create a new material and change it in some way.
6.Go back to the default view layer and the cube will have now show it's other material. The collection is linked so changes to anything in that collection will be reflected in both view layers.

I almost forgot, check 'Render Single Layers' so that only the collections enabled by the current view layer will show up in final render. .

With geometry nodes, which of course weren't around in 2019, we can do this a lot easier, by using geometry nodes to instance any geometry we want onto a new object and overriding its material in GN.
We can start by creating a new, empty view layer, and a collection containing all objects whose material we wish to override.  (This collection can be disabled in rendering. We won't be using it directly.)
Next, we want a new collection, enabled in our new view layer, with a single mesh object-- any kind.  Using geometry nodes, we instance the override collection on "relative" mode and then set its material to anything we want:

If we want other objects in the collection that don't get a material override, we can add them a collection that is enabled in that view layer normally.  This should be quite a bit more convenient than making a bunch of linked objects and keeping all object data up-to-date.
If we needed to override on a material-by-material basis (rather by object), it would be possible to separate materials to new objects, but this would be much more cumbersome than just objects; and this solution won't work for lights, which geometry nodes cannot work with.

In 2.81 under Render Layers go to Override > Material Override, but it overides all the the materials and not per object.


text:
Emissive Surface unknown shadow
I made a lamp rig and but whether I use the bulb or a circle in front of the bulb as an emissive surface it casts a shadow in the middle of the lit area. What might be causing this?

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


text:
Top Menu set in preferences
Windows has just done an update and now when I open Blender 2.78c the top menu line has collapsed. Is there a way of setting it to be there, in preferences or startup?
Also the pointer now has to be a few mm below anything I want to select being it a menu item or anything else it seems to be offset.

ok i worked out that i need to save the start up file Ctrl + U

however the pointer does need to be a feww mm belowanything i select and not exactly on top anyone experienced this?

Try resetting the UI with File > Load Factory Settings

difficult to post a screen shot when the pointer does not show up. If you for instance hover over an item in one of the menus the item above is highlighted so in main view it is difficult to set the 3d curser as when clicked it moves toa few mm away from where the pointer is. i am using a logitech M185 mouse but my laptop touchpad acts the same also i plugged in a USB mouse same thing.

Factory settings makes no difference.

Maybe related - https://blender.stackexchange.com/questions/82130/the-info-bar-on-top-disappeared-and-the-mouse-pointer-is-misaligned

how do i mark this question as resolved?

rolling back the driver and now works ok no offset


text:
Freestyle line is not showing
Im following this tutorial on YT https://www.youtube.com/watch?v=ZiqrCRqyLzE. But freestyle line does not appears. Freestyle checkbox is ticked, add-ons are ticked (LoopTools, PieMenu Official). I tried it with new fresh blender project, but nothing. Im in Blender 1.78, Win 7 Ultimate x64.

Just editing and adding my file since I am doing the same tutorial and having the same problem:
Adding a camera to the scene worked! (I am adding this here since I cannot comment yet) Thanks a lot!

Do you use Blender Internal like in tutorial? what are the settings for the freestyle color? What are those objects shown on screenshot, 2 cubes or just planes? Please use blend-exchange to upload the file

Regarding the file attached try adding camera object to the scene, for some reason lines render only if it's present (probably a limitation however you won't be able to output image wihtout a camera regardless unless taking screenshot)

@MrZak this seems to have worked, care to convert your comment into an answer so that it can be accepted?

@dr.Sybren I'd say answer it, I don't think I can find any info of why it works like that.

Regarding the file attached try adding camera object to the scene, for some reason Freestyle lines render only if it's present.
It's probably a limitation however you won't be able to output an image without a camera regardless unless taking a screenshot of the preview render (although in Cycles Freestyle lines will be rendered only in the final aka F12 render so screenshot won't work as well).

This limitation still seem to be present with Cycles render engine in Blender 2.79 and in 2.80 beta. Freestyle lines do only appear after the final F12 image rendering is completed and not during the preview!

Without having a look at your blend file I can only guess: Try switching the Logical OR to Logical AND to show crease edges as well as material edges.

I've tried switching the logical or or logical and, nothing.

So please consider uploading your blend file to blend-exchange.


text:
Cursor in new project is selecting attached geometry, not one face or edge?
I've been working with Blender for about a year now, teaching myself how to 3d model etc. I've never had any issues with the mouse until today, when i opened a new project and started.
The cursor seems to be stuck in a mode where it will only select the object + the surrounding geometry. It doesnt seem to matter if im in face/vertice/edge mode...it acts like its huge and its nearly impossible to manipulate my model this way.
The only difference i did in this project was select the add-on for "Images as planes". I feel like i might have activated a hotkey or misclicked an icon or something XD (Its acting like i hit c but i did not...and i cant get the cursor to make a box the normal way, it looks like the c circle)
Any help is appreciated!

have you enabled the Proportional Editing option?

I could see why you'd ask that but no, the icon for that is inactive. Toggling it did not change the issue :(

maybe show a screenshot of your full Blender interface? Or even share your file? https://pasteall.org/blend/

https://pasteall.org/blend/192878dab87e44bcb71861d614a42eba

Can't reproduce the error in the file. Everything works as expected.

Your problem is probably that you have the Select Circle selected, it will be your default select tool. Choose Tweak instead. You can also switch with the W shortcut.


text:
Is there any way to make the paint created in Texture Paint mode appear in render mode?
I noticed that when I paint anything on my sculpt and then switch to render mode, the paint doesn't show up. I use Cycles as my render engine. Additionally, I can only paint in the solid preview; painting in any other mode doesn't present the paint on the sculpt. Is there any way to make the paint painted in texture paint mode to show up in render mode? Sorry if this question sounds dumb, I am very new to Blender.

EDIT: So I think I might've figured it out. I did a test paint on the object and went to the shading workspace. I added the image texture node and played around with the connection things, and I found out that connecting the color under the image texture node to base color under the other node, it makes the texture paint appear in the final render.

if you are in Eevee you should see the painting in Render mode as well, but maybe you've chosen the bad texture image in the texture slots in the N panel?

Oh, I use Cycles as my render engine; using Eevee creates these weird visual glitches whereas Cycles has none for me. I’m guessing the render engines makes a difference?

I'm not sure what the glitches are caused by, but is your problem fixed in Eevee? If not, check the Texture Slots

In Cycles it looks like if you are in Render mode and paint you won't directly see the result, you need to switch to another mode then switch back, if it still doesn't work you need to check your nodes or the image selected in the Texture Slots

Yes. Texture paint is supposed to affect render mode. There is a good chance that the image you are painting onto is not connected to the material assigned to that area on the object (the material if you only have one on the object). Check for this in the shader editor. If you see no image texture node, add one and select the image data block you were painting onto.
Tip: click the image pull down icon on the image texture node, not the wider “Open file” button” right next to it. You want to pick an image that is already loaded into blender: an existing image data block.

I added the image texture node and add the image I am painting on, but I feel like I'm missing another step. The paint created on the image still doesn't show up in rendered mode. Is there anything I'm supposed to connect within the nodes?

@LailaB add a screenshot of the node setup?

I updated the post with the setup, and I think I might've figured it out after following your solution. I just had to play around with the node connections. Thank you for the help!


text:
Transparent material in Blender in render mode (Eevee or Cycles) in Python, Blender 2.93
I've managed to create a transparent object in viewport mode, but not in render mode:
# verts, edges, faces = ...

mesh = bpy.data.meshes.new('bboxmesh')
mesh.from_pydata(verts, edges, faces)
bbox = bpy.data.objects.new("bbox", mesh)
material = bpy.data.materials.new("mymaterial")
material.diffuse_color = (1.0,0.0,1.0, 0.05)
material.blend_method = 'BLEND'
mesh.materials.append(material)
bpy.context.collection.objects.link(bbox)

Basically, I compute optimal oriented 3D bounding box with Open3D and would like to display it a transparent cuboid.
I could not find how to easily render the wireframe (in render mode), so looking either for rendering the wireframe or having a transparent material :)
I found some tutorials for doing it in UI, but not in Python. I've been using Blender for just one week, so I'd like to avoid configuring Nodes pipelines if the same can be achieved without.
Thank you!

Personally, doing this instead of just using nodes, even nodes set up with python, seams going over a mountain to avoid a mole hill. Nodes are fairly easy to set up in python.

I don't have skills for now to convert a visual tutorial setting up Nodes into Python code :/ I'm sure I'll learn it with more experience. But even from tinkering for a week, it seems that many simple tasks are super-hard to do without falling back to Nodes :(

really, it’s not that hard. Especially if you just want to render a semi transparent cuboid. I can almost put the necessary code in a comment, but I don’t remember it just well enough. I’ll have to go look at a previous time I did this.

I think I found a snippet for configuring render-time material properties: material.use_nodes = True;  material.node_tree.nodes["Principled BSDF"].inputs[19].default_value = 0.05

Is there a way to do without constant 19? Is there a way to specify it once and having it both for viewport and render mode? How do I set color for the render mode?

yes, you can index the input by its name. node.inputs[“Alpha”] 2) Yes, in fact I think it would be very hard not to do this.

One more question: how to keep only wireframe / display edges only in rendering mode...

It depends somewhat on what render engine you’re using. A reliable method would be to use some system of grease pencil (possibly with the lineart GP modifier), or the mesh wire frame modifier which makes 3D geometry along previous edges. But to actually display just thin 1-pixel lines as they mathematically exist, you will have to use EEVEE specific settings, if it is possible at all.

I don't mind edges being thicker than 1px. So if you know a way of doing that programmatically, I would be greatful :)

Could I manually add thin cylinders to display the cuboid's wireframe? https://docs.blender.org/api/current/bpy.ops.mesh.html#bpy.ops.mesh.primitive_cylinder_add

Probably. How easy it is depends on what variation there is in the cuboid. I would just use the wireframe modifierZ

Wireframe modifier would display in render mode?  https://docs.blender.org/manual/en/latest/modeling/modifiers/generate/wireframe.html

Okay, it seems that the wireframe modifier works for me. How could I configure it from Python? It also seems that the wireframe modifier does not work for meshes consisting of only edges (without any faces)

I had not thought of that, and it is true. You maybe should switch to grease pencil

I managed to script grease pencil in viewport mode, I can see the cuboid edges. But they do not appear in render mode. Would you have any advice on how to fix this?

Setting gp_stroke.line_width = 1000 seems to help, but this is weird. Also, can't set stroke color from Python :(

I wish I knew how to switch to discussions. Anyway, I’m not sure what to tell you here. What version of blender are you using?

It's 2.93. I somehow made it work with line_width = 1000, but still not sure why it's limited to 1000 and what units it uses. Some sample output: https://github.com/facebookresearch/meshrcnn/issues/100 and my full code: https://gist.github.com/vadimkantorov/eb53ce740cb80c12444079875facff85. If you have any comments on this Blender code, please tell me :) It's a nasty pastiche of copy-pastes from various places. I don't understand internal Blender structures well for now.

Sigh :/ Grease Pencil does not work on headless setups :( https://gist.github.com/zocker-160/0688a4902421158b66f52dff3966058a#gistcomment-3743669

I wonder then if some way to render just edges exists for headless rendering :)

that wasn’t what the original question said. I think you should close this question and open a new one. The comment section is getting huge with new information and discoveries.

Thanks to @TheLabCat I found a solution using Nodes:
material.use_nodes = True
material.node_tree.nodes["Principled BSDF"].inputs['Alpha'].default_value = 0.05
material.node_tree.nodes["Principled BSDF"].inputs['Base Color'].default_value = (1, 0, 0, 0.05) # red color


text:
Symmetry settings have no effect (continues mirroring across Y)
Using Blender 3.0 in Sculpt mode. I have been (intentionally) mirroring across the Y-axis. However, now, I can't turn this off. In fact, no matter what I pick in the Symmetry settings, it continues to mirror across the Y axis.
Is there another setting somewhere to disable this - or is it a bug?

do you have a Mirror modifier?

I'm not sure waht that is. I'm very, very new to Blender. How can I check?

Bring back the Properties panel tabs: https://zupimages.net/up/22/11/1thy.jpg then click on the Modifier tab and if you see a Mirror modifier, close it by clicking on the X

if you loose the symmetry you can still click on the Symmetrize button in the top right panel (down arrow on the left of XYZ buttons)

For others, I noticed when I turned it off this way - I lost much of the symmetry between the two sides (one side became very different from the other.) After disabling the mirror modifier, I "symmetrize"ed it (+y to -y) to get it back.

Bring back the Properties panel tabs:

Then click on the Modifier tab and if you see a Mirror modifier, close it by clicking on the X button.


text:
Camera angle should follow path angle
(I'm a blender beginner but know a handful of techniques with other similar programs/systems)
I've created a NURBS to make a tracking shot. Creating a follow path object constraint on the camera lets the camera follow the track in terms of translation, however the rotation of the camera is fixed this way. In other words the camera should look to the exact way the path currently points.
I'm pretty sure this is possible with blender (everything should be possible with blender :), I just don't know which object constraints I have to use in order for the camera to do this.

What if you enable Follow Curve in the constraint?

Just so you know Dom0, I didn't know the answer either, but I went to YouTube and did a search on "Blender Tutorial camera follow path". You can find many really good tutorials on YouTube by searching on "Blender Tutorial ...." :)

@Gandalf Did you get that method to work? I couldn't. If you did, can you show how? :)

@ThomBlairIII I did, but I don't have any time to post an answer atm..

Set Parent To -> Follow Path
This effect can be achieved with the following method:

Add a curve for your path: SHIFTA -> Curve -> select a curve
Edit your curve to be your desired camera path
Make sure you have the green frame cursor set to the frame on the Timeline you want to begin having the camera follow the path
Select the curve and in Edit mode, select the point of the curve you want to be the first place you want the camera to be
Then snap the 3D cursor to that point: SHIFTS -> Cursor to Selected:

Now select the camera, then snap it to the 3D cursor: SHIFTS -> Selection to Cursor:

Adjust the rotation of your camera so that it looks forward along the path
Now first select the camera, then hold down SHIFT while selecting the path, then make the path the parent of the camera with the Follow Path option:  CTRLP -> Follow Path:

(NOTE: The order you select the two objects is very important when setting parent/child relationships: first select the child, then the parent)
Now when you play your animation, the camera will follow the path and stay oriented to the direction of the path:

This is one of the most helpful answers I've read on a stackexchange site, ever... I'd upvote it a few dozen times if I could :)

Great! I'm glad I could help! :)


text:
UV mapping not filling faces
I have tried to map this simple object, but the uv mapping does not correspond to what i see in the textured object. It cuts the image a bit on top and a bit on the bottom of the faces. It does not fill the faces with the texture, even though i have mapped them correctly. Does anyone know what could be happening?
Thanks in advance.

Do you have a subserf modifier and multiple materials assigned to your object? If not, could you upload your .blend? It's hard to say what is causing this without testing each possible cause separately.

Maybe Gandalf3 is onto something there with the sub-D thing.  An error similar to that will happen for uneven geometry if the 2 sub-division modifiers are not set correctly.  Try toggling the Subdivide UV's option on and off.  Stretching can occur if the geometry is not evenly spaced.  From the look of your mesh I'd say that you should have this option activated.  If that is the problem you can also add control loops to create evenly spaced division vertically.

Thank you  MarcClintDion and gandalf3 . My geometry was uneven and i was using the sub-division modifier and multiple materials to the object. I added control loops and created evenly spaced divisions as you suggested and now it works perfectly.

This can be caused by a combination of subsurf and multiple materials.
You'll notice that when you assign the materials to a model with subsurf, in some cases they don't line up with the edit cage. In these cases, if you either apply the subsurf modifier to the edit cage or disable it completely, the materials line up with the topology:

To fix this distortion caused by the subsurf, add supporting geometry or creases.

For adding supporting geometry, the loop cut (⎈ CtrlR) and bevel (⎈ CtrlB) tools work pretty well.
You can change the crease weight of selected edges by pressing  ⇧ ShiftE.


text:
Best way to add a face if I modeled the body first?
I'm modeling a character and am pretty far into it. I modeled the body first though and the face is in the center of the body (it's a cartoonish character). This means I'm gonna have to mess with the vertices in the center of the body to make the face. Can I make a face and then add it to the face or should I move the bodys vertices to make y face? I'm new to all of this so help from those of you is greatly appreciated.

I would say that it depends on your level of detail. If your face is mostly a texture and you can get the geometry you need by just moving vertices around on the body, then I would take that route.
But if you need to add significant amounts of geometry, then you will need to change your body geometry to keep good topology. See this article from cg cookie.
Topology (basically having your edges flow cleanly) is important for animation and texturing. Too keep good topology you will probably need to modify your body's geometry. Whether you want to split edges as needed and keep the body mesh, or just start over with a new face mesh, is up to you.


text:
how to keep sharp turns on model while sub surf modifier is active? (image inside)
I would like a sharp turn, not the smoothed round turn that the sub surf modifier causes. Is this possible? Notice the purple line for the mean crease, I would like it to look like that

Use Shift+E while in edit mode while you have the two adjacent edges selected, adding answer (only works on a 3D object) Use loopcuts for 2D ones.

if it helps, I had solidify modifier on but not applied. I increased the original edge crease weight to 1. Maybe if I applied solidify and then increase the crease weight to 1 on the whole face it would fix it?

Read my answer.  \The solidify modifier is based off of a 2D mesh, so creases do not work. You need to crease the seam. If you apply the solidify modifier it should work though.

Depending on what your mesh is like, there are several ways to do this.
3D Objects:
You can accomplish this with the shortcut Shift+E while in edit mode. Select the edge you would like to crease (the "seam") first, and then press 1 or move the cursor until the crease is maxed out.

2D Objects:
For two-dimensional objects (planes) you can use Loopcuts to simulate this effect. One of the main drawbacks to this method is your vertex count will be increased. Sadly the Edge Crease option does not work on 2D objects.
In edit mode, hover over the adjacent edges and press Ctrl+R, then click once and drag towards the seam. Now click again to finish the operation. Repeat for the other side.

yea that was my main mistake. I had solidify but I hadn't applied it. Shift + e to increase crease weight worked when I applied solidify and then did it to the whole face.


text:
Minimal object add-on UI with sub-meshes and Redo
I finally have this working UI, after exploring many rabbit-holes, so wanted to share it in the hope of improving its performance.
Follow-up to this question.
The key goal is to preserve the 'redo' action of the add-on template.
Background
Learning some OOP has really helped me with this.
My add-on requires the rebuilding of parent mesh as submeshes are added/enabled/altered,
hence the need to 'redo' the object operator.
Expected usage would be for a few submeshes, 100 enabled submeshes would be very unlikely, but...
Help
The 'draw' method was helped along by examining Blender's built-in Sapling add-on code.
Also this snippet by @Gorgious on Blenderartists in 2011.
Positives
On the whole I find it easy to understand and manage. I will continue to flesh it out for debugging as a "real-user".
Having 'always visible' items in the 'subs' EnumProperty could act as a warning to a user not to register more than necessary.
(Disabling a submesh will need to also disable its child meshes)
Negatives
I suspect this is simply not up to scratch for a good add-on.
I admit numbered attribute names in 'SubMeshSpecs' are not Pythonic; numbered attributes are 'removed' by making a list of new instances on 'execute', re-formatted for use as input argument.
Though of course that duplicates what is already present in 'self'. Not sure how abominable this is.
Usage
When added to scene, only main mesh properties show.
.
Selecting a submesh shows its properties; enable to include it
.
Enabling a 2nd submesh shows properties for Sub_2.
.
Thus the list if sub_attributes grows with only enabled submeshes
    if sub_attributes:
        print(sub_attributes)
    # sub_attributes after 2 submeshes are enabled and edited
    # [SubMesh(end='E', parent='0', length=4, SubMesh(end='N', parent='1', length=1]

Is there a cleaner way to do this?
(I guess I mean without numbered attributes, or creating SubMesh in a more Blendery way.)
In particular, if the enabled default is set to True and "user_pref_num_subs" set to a high number, the drag on performance (delay) is noticeable, even without adding meshes, whenever a value is changed.
I would prefer the meshes to be the cause of a delay, not the UI.
bl_info = {
    "name": "New Object",
    "author": "Your Name Here",
    "version": (1, 0),
    "blender": (2, 80, 0),
    "location": "View3D > Add > Mesh > New Object",
    "description": "Adds a new Mesh Object",
    "warning": "",
    "doc_url": "",
    "category": "Add Mesh",
}

# pylint: disable="no-member,wrong-import-position,line-too-long"

import bpy
from bpy.types import Operator
from bpy.props import FloatVectorProperty, IntProperty, BoolProperty, EnumProperty
from bpy_extras.object_utils import AddObjectHelper, object_data_add
from mathutils import Vector

user_pref_num_subs = 5
range_subs = range(1, user_pref_num_subs + 1)

items = [(str(sub_idx), f"Sub_{sub_idx}", "") for sub_idx in range(user_pref_num_subs + 1)]
items[0] = ('0', "Main", "")

def add_object(self, context):

    sub_attributes = []
    for sub_idx in range_subs:
        include = getattr(self, f"enabled{sub_idx}")
        if include:
            sub_mesh = SubMesh(
                end=getattr(self, f"end{sub_idx}"),
                parent=getattr(self, f"parent{sub_idx}"),
                length=getattr(self, f"length{sub_idx}")
            )
            sub_attributes.append(sub_mesh)

    if sub_attributes:
        print(sub_attributes)

    # add-on starts here with arguments in desired format
    # MyAddOn(self, sub_attributes)

    scale_x = self.scale.x
    scale_y = self.scale.y

    verts = [
        Vector((-1 * scale_x, 1 * scale_y, 0)),
        Vector((1 * scale_x, 1 * scale_y, 0)),
        Vector((1 * scale_x, -1 * scale_y, 0)),
        Vector((-1 * scale_x, -1 * scale_y, 0)),
    ]

    edges = []
    faces = [[0, 1, 2, 3]]

    mesh = bpy.data.meshes.new(name="New Object Mesh")
    mesh.from_pydata(verts, edges, faces)

    object_data_add(context, mesh, operator=self)

class SubMesh:
    """ A submesh specification """

    def __init__(self, end, parent, length):
        self.end = end
        self.parent = parent
        self.length = length

    def __repr__(self):
        class_name = type(self).__name__
        return f"{class_name}(end={self.end!r}, parent={self.parent!r}, length={self.length!r}"

def annotations() -> dict:
    """ Generates numbered properties per submesh """
    props = {}
    for sub_idx in range_subs:
        props.update({
            f"enabled{sub_idx}": BoolProperty(name="Enable selected", description="Make submesh visible",
                                            default=False),
            f"end{sub_idx}": EnumProperty(name="End", description="Direction this mesh faces",
                                        items=[('E', "East (+x)", ""), ('N', "North (+y)", ""),
                                               ('W', "West (-x)", ""), ('S', "South (-y)", "")]),
            f"parent{sub_idx}": EnumProperty(name="Parent", description="Parent of this mesh",
                                           items=items),
            f"length{sub_idx}": IntProperty(name="Length", description="Length (tile-count)",
                                          default=2)
        })
    return props

data = {
    'bl_label': "Simple Object Operator",
    'bl_idname': "object.submesh_operator",
    '__annotations__': annotations()
}

SubMeshSpecs = type("SubmeshOperator", (Operator,), data)

class OBJECT_OT_add_object(SubMeshSpecs, Operator, AddObjectHelper):
    """Create a new Mesh Object"""
    bl_idname = "mesh.add_object"
    bl_label = "Add Mesh Object"
    bl_options = {'REGISTER', 'UNDO'}

    scale: FloatVectorProperty(name="Scale", description="scaling",
                               default=(1.0, 1.0, 1.0), subtype='TRANSLATION')
    subs : EnumProperty(name="Select", description="Alter settings of this mesh",
                        items=items)

    def draw(self, context):
        layout = self.layout
        box = layout.box()
        row = box.row()
        row.prop(self, "subs")
        if self.subs == '0':
            row = layout.row()
            row.prop(self, "scale")
        for sub_idx in range_subs:
            if self.subs == str(sub_idx):
                row = layout.row()
                col = row.column()
                col.prop(self, f"enabled{sub_idx}")
                col = row.column()
                col.prop(self, f"end{sub_idx}")
                row = col.row()
                row.prop(self, f"parent{sub_idx}")
                row = layout.row()
                row.prop(self, f"length{sub_idx}")

    def execute(self, context):

        add_object(self, context)

        return {'FINISHED'}

# Registration

def add_object_button(self, context):
    self.layout.operator(
        OBJECT_OT_add_object.bl_idname,
        text="Add Object",
        icon='PLUGIN')

bl_classes = [
    SubMeshSpecs,
    OBJECT_OT_add_object
]

def register():
    for bl_class in bl_classes:
        bpy.utils.register_class(bl_class)
    bpy.types.VIEW3D_MT_mesh_add.append(add_object_button)

def unregister():
    for bl_class in bl_classes:
        bpy.utils.unregister_class(bl_class)
    bpy.types.VIEW3D_MT_mesh_add.remove(add_object_button)

if __name__ == "__main__":
    register()
```

Not sure I understand what this addon does, or what the goal is. Could you explain the use case, or show the indended workflow? Maybe show an example of usage, along with some screenshots or better yet a short GIF.

I have added the Usage paragraph with screenshots.

I guess it takes a bad script to find a good one; I apologize for anything misleading in the question and its code.
This seems to be the way forward, and is mercifully short, which is a good sign.
I think I gave up on the idea of a CollectionProperty in Operators because of registration issues, but this draw() snippet works fine.
bl_info = {
    "name": "New Object",
    "author": "Your Name Here",
    "version": (1, 0),
    "blender": (2, 80, 0),
    "location": "View3D > Add > Mesh > New Object",
    "description": "Adds a new Mesh Object",
    "warning": "",
    "doc_url": "",
    "category": "Add Mesh",
}

import time
import bpy
from bpy.props import (StringProperty, BoolProperty, EnumProperty,
                        IntProperty, FloatVectorProperty, CollectionProperty)

USER_PREF_MAX_SUBS = 10
RANGE_SUBS = range(1, USER_PREF_MAX_SUBS + 1)
items = [(str(sub_idx), f"Sub_{sub_idx}", "") for sub_idx in range(USER_PREF_MAX_SUBS + 1)]
items[0] = ('0', "Main", "")

def progress(starttime, msg):
    """ measure blocks of code """
    end = time.perf_counter()
    print(msg, end - starttime)

class SubMeshSpec(bpy.types.PropertyGroup):
    """ A submesh specification """
    enabled: BoolProperty(name="Enable selected", description="Make submesh visible",
                          default=False)
    end: EnumProperty(name="End", description="Direction this mesh faces", default='E',
                      items=[('E', "East (+x)", ""), ('N', "North (+y)", ""),
                                               ('W', "West (-x)", ""), ('S', "South (-y)", "")])
    parent: EnumProperty(name="Parent", description="Parent of this mesh",
                         items=items)
    length: IntProperty(name="Length", description="Length (tile-count)",
                        default=2)

class OBJECT_OT_add_object(bpy.types.Operator):
    """ Collection Operator """
    bl_idname = 'mesh.add_object'
    bl_label = 'Add a mesh object.'
    bl_description = 'Adds a mesh object to the scene.'
    bl_options = {'REGISTER', 'UNDO'}

    submesh_specs: CollectionProperty(type=SubMeshSpec)

    scale: FloatVectorProperty(name="Scale", description="scaling",
                               default=(1.0, 1.0, 1.0), subtype='TRANSLATION')
    subs : EnumProperty(name="Select", description="Alter settings of this mesh",
                        items=items)

    def __init__(self):
        """ Preload collection once only

        Blender can't see __init__(); not triggered on redo
        """
        for _ in RANGE_SUBS:
            self.submesh_specs.add()

    def draw(self, context):
        layout = self.layout
        box = layout.box()
        row = box.row()
        row.prop(self, "subs")
        if self.subs == '0':
            row = layout.row()
            row.prop(self, "scale")

        for sub_idx in RANGE_SUBS:
            if self.subs == str(sub_idx):
                row = layout.row()
                col = row.column()
                row.label(text=f"Edit Sub_{sub_idx}")
                col = row.column()
                col.prop(self.submesh_specs[sub_idx], 'enabled')
                row = layout.row()
                col = row.column()
                col.prop(self.submesh_specs[sub_idx], 'end')
                row = col.row()
                row.prop(self.submesh_specs[sub_idx], 'parent')
                row = layout.row()
                row.prop(self.submesh_specs[sub_idx], 'length')

    def execute(self, context):
        atts = []
        start = time.perf_counter()
        print(self.submesh_specs)
        for sub in self.submesh_specs:
            if sub.name != 'Main':
                if sub.enabled is True:
                    sub_mesh = SubMesh(
                        end=sub.end,
                        parent=sub.parent,
                        length=sub.length,
                    )
                    atts.append(sub_mesh)
        if atts:
            print(atts)
        # e.g. [
        #     SubMesh(end='E', parent='0', length=2,
        #     SubMesh(end='N', parent='1', length=3
        # ]
        progress(start, "add_ob")

        return {'FINISHED'}

class SubMesh:
    """ A submesh specification class """

    def __init__(self, end, parent, length):
        self.end = end
        self.parent = parent
        self.length = length

    def __repr__(self):
        class_name = type(self).__name__
        return f"{class_name}(end={self.end!r}, parent={self.parent!r}, length={self.length!r}"

def add_object_button(self, context):
    """ Button on the Add > Mesh menu """
    self.layout.operator(
        OBJECT_OT_add_object.bl_idname,
        text="Add Object",
        icon='PLUGIN')

bl_classes = [
    SubMeshSpec,
    OBJECT_OT_add_object
]

def register():
    """ Register classes """
    for bl_class in bl_classes:
        bpy.utils.register_class(bl_class)
    bpy.types.VIEW3D_MT_mesh_add.append(add_object_button)

def unregister():
    """ Unregister classes """
    for bl_class in bl_classes:
        bpy.utils.unregister_class(bl_class)
    bpy.types.VIEW3D_MT_mesh_add.remove(add_object_button)

if __name__ == '__main__':
    register()
```


text:
Morphing from text to shape
I am trying to morph text into shape. Is there a convenient way to do this in Blender? For example, how would I morph the text "CH3" into a sphere? Please help if you know how to do this. Thank you!

I guess it really depends how your text object looks like, etc... maybe show a video, some pictures, or even a drawing of what you want?

Please see added image. I am trying to morph the CH3 into a yellow sphere. This is one example but I'd like to eventually morph between the other spheres and text as well.

I guess you want to replace the sphere from the text , you can do that probably by linking their object data  , click both of them and do CTRL L and select object data

Can use shrinkwrap modifier and some transparency animation to do that:

We can keep the text as it is: just give it a little extrusion (text property panel), and convert it to mesh (menu "object/convert to") as we'll need a vertex group.
Then add a support sphere that is around the text. This sphere will not be rendered and is just here to be projected on.
Add a vertex group to the text and add it this modifiers:

Vertex weight proximity onto the geometry of the support sphere and using the vertex group. We'll animate "global influence" parameter from 0 to 1, so that the text vertex group progressively go to 1.
Subdivsion surface which helps to get rid of artifacts
Shrinkwrap to the support sphere, using the same vertex group and with the parameter shown above

The text shader is directly a color to get rid of normal issues (see blend file).
Now use a second sphere, which will be visible at the end, as its alpha/transparency is animated.
This sphere is itself projected on the text using another shrinkwrap modifier, with the following parameters:

This sphere is fully shaded (see blend file) and adds the color transition.

Thank you so much for the detailed explanation. I made an attempt following your directions but I must have missed something because even though the animation works, it is not nearly as nice as the one you made. I have the blend file but I don't know how to upload it here..

You can use this link to upload a file: https://blend-exchange.giantcowfilms.com/

Thank you. I uploaded my blend file here. I am using the cycles engine in Blender 2.9.

Here is your file with some modifications (commented in the viewport).  You'll have to tune the transparency effect to make it ok with Cycles (used Eevee in the answer).

Got it to work this time. Thank you!

I noticed a bounding box associated with the support sphere in your files when I switch to object mode. I was curious about where that is coming from. Thank you.

It is an option in the object property panel (viewport visibility)... that allow to see things better for elements that are not rendered (for instance).

I see. Got it! Thanks again.

Here are a basic solution and a bit more complete one, using both the Cast modifier:

Create your text, once converted in mesh, press X > Limited Dissolve to simplify it and use a grid and the Knife Project tool to subdivide it:

Put its origin at its geometry, create an empty somewhere behind, give it a Cast modifier with the empty as Object, play with the factor:

Create a sphere that has the same radius as the spherical text. Keyframe the Cast factor and the material of the text and of the sphere in order to make them disappear and appear. If you use Eevee, you need to choose Alpha Mode > Alpha Blend in the Settings of the material:

You can improve if you use shapekeys:

Create your letters, create 2 shapekeys for the object, keep the second selected, select your letters and extrude them, select the rims:

Press AltS to inflate:

Delete the extrusion to have a flat topology:

This time you will animate both the shapekeys (from the shapekey 1 to 2), the Cast modifier and the material to get the animation, keep the sphere as in the first method to make the transition to a complete sphere.

Thank you so much for the detailed explanation and two separate approaches. As the first one seemed simpler I tried that first. I got the text to work with the cast modifier but I can't seem to get the sphere animation right. I have the blend file but I am not sure how I can attach it here.

Sorry I didn't go into details, to make the sphere appear you need to create a material which is a mix (with Mix Shader) between a Diffuse and a Transparent node, then just animate the factor of the Mix Shader so that it begins 100% transparent and ends up 100% colorful

I actually did use the mix shader and  keyframed the factor values. I'll check again to see if I missed something while doing that. In any case, the information you provided is "super" helpful in teaching stereochemistry to my students. Much appreciated.


text:
Polygon with cylindrical edges
I am trying to model regular polygons (triangle, square, pentagon, hexagon, etc.) with the edges made up of cylindrical rods, kind of like the bonds in a molecule. I can get the basic shape by working with a circle mesh and changing to the appropriate number of vertices, but would appreciate some help in changing the edges to cylindrical "bonds." An example of a folded hexagon that I am trying to model is shown below. Thank you!

Hello, I'm not sure to understand what it should look like. Have you tried to add a skin modifier then a subdivision modifier ?

Sorry for not being very clear. Just added an image of a folded hexagon.

I think the easiest way to do this is to bevel a curve object.
Go to Blender Preferences > Add-ons. Type "extra" in the search bar, and activate the Add Curve: Extra Objects add-on by checking the box next to it.

Then in the 3D Viewport press Shift + a, choose Curve > Polygon and set the sides to 6.
In the Properties window, go to Object Data Properties > Bevel, and change the Depth value to give the curve thickness.

Then move and rotate the vertexes in Edit Mode to get the desired result.

If you want the corners to be less sharp and more rounded you can change the handle type of the selected vertices (from the original Vector) to Aligned. You can also use Vector and Aligned vertices together in one curve to get a more precise result.

EDIT:
Alternatively (which I quite stupidly didn't realize before) you can place Spheres to represent the atoms at the corners of the curve. If you would use a Hook modifier the curve would follow the position of the atom object.
Select the curve. Go into Edit Mode. Select a corner Vertex. Press Ctrl + S and choose Cursor to Selected. Go to object mode and Press Shift + A and choose a spherical object like Mesh > UV Sphere. (Press S to scale it down)
Now select the the sphere and Shift select the curve (in that order) so both are selected. Go into Edit model and select the curve vertex and press Ctrl + H and choose Hook to Selected object.

However if you choose to do this, you might want to parent the curve and all its atoms to an empty object, to be able to move the molecule (by moving the empty) without issues. (Add an empty, move it in the center of your molecule, select al the parts of the molecule, Shift select the empty, press Ctrl + P and choose Object(keep Transform). )

Ooops, you just beat me to it!  I'll eave mine in, just for the differences.

I didn't even realise the object should have spheres, but since it is about a scientific model of a molecule it makes sense of course. Also I think instancing the spheres is the easiest way to go. So +1 : ) Though the Hook modifier would allow different atoms to move with the curve vertices (I might edit my answer accordingly.)

Hooking! Good idea :) All depends on what OP needs to do with these models .. maybe we've both gone OTT

Quite possibly, yes : )

This is "super" helpful. Especially because I can now do this with or without the spheres for atoms depending on the model I am trying to make. I'll need the corners to be sharp rather than rounded but thank you for letting me know how to do either one. What a great community!

One route would be via Curves (make them 2D, if your polygons are planar.)

Enable the shipped add-on 'Add Curve: Extra Objects' This will give you a polygonal curve option.
Create your polygon of choice, and (for the optional next part,) Shift D make  a copy of it, and Header > Object menu > Convert that to a mesh.
In its geometry panel, ensure  the original (if 2D) curve-polygon has no fill, and give it a bevel, of whatever resolution and thickness suits.

For the second part, you could take some of the tedium out of placing atoms on your polygons by:

In the Mesh copy, Object Properties tab > Relations panel > Instancing, set instancing to Vertex.
Create a sphere at the origin (pivot) of the original Curve-polygon You can hide that one, eventually.
Parent the sphere to the mesh copy. Duplicates should appear on the corners of the curve.
You can CtrlA the dupliverts, > Make Instances Real. Then you can scale them independently in Object mode.
You can give them independent materials by associating the materials with the Objects, rather than their Data, just under the materials list panel in the  Materials tab.

Eventually, you could parent the atoms to their polygons / various polygons to one another so they move about together, or convert the whole lot to joined? meshes if you're going in that kind of direction.

Try using the Skin Modifier and the Subdivision surface modifier.

If you need more precise control over it, you can select all the vertices, hit E to extrude and then S to scale it a little bigger, and then select everything again, hit E, and extrude upward.  You can then use the subdivision surface modifier to make the edges round, and select any edges you want to be sharp, press Shit+E and then drag the mouse out to create a sharp edge.

I don't know much about the skin modifier and never used it before. So this is a good chance to try it out. Looks like this is a useful one to know for some of my other projects as well. Thanks for suggesting this different approach.


text:
How do you gradually blend between transparency based on a geometry?

I've some text geometry that I want to gradually fade out based on some geometry (two boxes in this case).
Any suggestions on how to achieve such a effect?
EDIT:
Here is a blend file based on Jakemoyo answer:

Geometry Nodes tree that looks like this.

Full tree:

Then you just access that value with a shader tree that looks like this.

Result:

Could you append the blend file?
I might be having problems recreating the geometry nodes set-up due to a version difference.

Nevermind it works after finding out I wasn't using multiply vector node, but the regular math node.
I also updated my question to include the blend file. Thanks again.


text:
blender is not using 1050ti GPU for cycles render
I have updated blender to 9.20 but after updating blender is not using 1050ti for cycles render. I have
configured it in preference and using experimental feature but still my GPU usage is 0% and CPU usage is 100%, however it was working well before updating.

Your GPU is greyed out. What mode did you have selected in the Preferences when you too the screen grab of your Render settings? You will need to leave it on CUDA to have it active.

Thank you very much for reply it, solved my problem is solved. Can you tell me what Optix and openCL Do.

https://docs.blender.org/manual/en/latest/render/cycles/gpu_rendering.html


text:
Texture suddenly behaves crazy
I hope you can help with this. I use Blender 3.5.
I have a model of a human head in Blender with texture on it. Everything looks good after I have finished the node setup in shading.
But after a while, the texture suddenly goes crazy and looks like this:

The strange thing is that this happens even though I do not touch anything in the node setup in Shading. It seems to happen out of nowhere. Sometimes, it happens when I swift viewport settings from Rendered Preview to Material preview and back to Rendered Preview. Then the texture turns into a wrong colour (much darker) and bursts into a strange abstract shape. I do not understand why the texture can suddenly behave so differently just by changing the preview, while not touching anything in the actual node setup.
If you need it this is the node setup below. As mentioned, it works totally fine at first, but after changing the viewport settings, it is almost like the texture explodes out of nowhere. Sometimes it also happens just by reopening the .blend-file.

Just to note: There should not be a problem with the linked images, both for the texture displacement or roughness map. I have tried to relink them several times. I have also tried to pack all external files into the .blend file but the error still occurs.
(Don't know if it has any relevance: the problem started after I tried to add a Subsurface Scattering Map. It didnt work, so I removed it again (as you can see, it is not present in the node setup anymore). It would be strange if this could this cause problems after removal, but I wanted to mention it, just in case).
Any suggestions of how to troubleshoot this problem?

pls provide blend file with packed resources so we can check it out, thx

99.999% probablity that the scale on the diplacement node is too much. Try lowring it. (If not that then pleasse share the file)

Thank you! The packed blend file is available on this wetransfer link. I hope it works - if not, I can also upload it by other means: https://we.tl/t-eKp87MNpuN

I agree with @TheKalaakaar. Drop the Scale of the Displacement node to .01 and it behaves itself. Increase it to .02 and you start to get distortions appearing. (You should also Shade Smooth your object. by the way.)


text:
Rigging Folding Door
I've got a huge problem with rigging B-folding door. I'm new to rigging and wanted to make an animation of the house that i am modelling now, with nice folding door opening system, and I would like to make it quite realistic, so first is opening the first door, then is folding the next two doors and opened door is slighting to the opening one, etc.
Just like in the video:
https://www.youtube.com/watch?v=FbBmIvi7U0Q&ab_channel=expressbifoldsuk
My problem is that my rig doesn't want to keep my doors in a straight line, when they are closed.

Also there is a problem with overlapping part of the doors:

And here is the file:
https://drive.google.com/file/d/1ycBS4CNLzG3btDfNItJLmSB8nGOrQP4t/view?usp=sharing
Update: 17.08.2021
This is how the doors looks a like where are the closed:

And when they are folded:

When they are folded they look perfect, but when the door are closed, joints doesn't want to jump in the right position.

you could choose the open door as the default (rest) pose. Also, do you want to be able to control each board or couldn't you control the whole animation with only one bone?

This is a possible duplicate of https://blender.stackexchange.com/q/182714/35559

Thanks Robin, No this isnt a duplicate, I already know this topic, didnt found any solution to my problem.

@Zorian Ahhh.. I see.. sorry, didn't read carefully enough.

I would take what seems to be your original approach, although you needed some parenting and bone rolls fixed:

I've basically done 3 IK segments,  the IK bone target's IK control and has a chain length of 2.  Similarly door 4's target is IK control.001 and door 2's target is IK control.002.
Each of the IK control bones is constrained so that it can only move along it's Y axis (which coincides with the world X axis.)
I've left it possible to control each door pair separately, since you didn't say whether you wanted all the doors to unfold at the same time, or for IK control to pull them open in a chain.
In my blend file I've created a 30 frame door open action that you could assign to a controller that does the chain open.  The screen shoot is from individually manipulating the IK controllers.
You'd have to put the doors back in place.  I unparented them to make it easier to work out the armature.
Blend File
I've edited the file to add an action constraint to the IK bones so that open action can be controlled by a single bone.  Here's the new version:

Thanks for you effort. I would like to open them as a chain, so it looks quite good, hovewer The biggest porblem with this door is that hinges are not in straight line, they are on both sides of the panels. I also updated my questions :)

The rig in my second blend file will solve your overlapping problem, but it's up to you to place the doors and size the bones properly.  You just have to make sure that the tips of the bones align in a straight line along the x axis

Well basic idea is quite good already but I would recommend to put smaller bones between big ones that will keep the offset of those doors. Because if you make it like this, 2 doors will have their edge at similar/same location... But if you add another bone just like this (and then you can remove them and set it to keep offset or lock rotation so it wont deform while moving):

and the second thing I have noticed is that you placed those doors wrong on bones... try to keep it precise for each bone and door. They must be placed perfectly and not with different offsets

Thanks, I used extra bones, and as it looks fantastic when it is folded, but when the doors are closed the gap between them is huge. is it any chance to fix it ?

Try to move your bones, dont make them go in the middle of the door but remember that doors have hinges, try to place bones in order where hinges will be, it needs tweaking for sure, maybe some limitations, or something

I'm not sure if I'm getting closer or not. not sure how to force middle hinge to be where is should be. https://vimeo.com/588241877


text:
How to calculate velocity and momentum of a rigid body
I have a simple animation in which there are two planes and balls on the planes. There’s one ball on an inclined plane, and a couple of balls sitting on a horizontal plane below that ball. When the animation starts, the ball on the top rolls down the slope and collides with other balls. I need to calculate the velocity and momentum of the balls.
Here’s my code so far:
import bpy
from mathutils import Vector

def distance_line(point1: Vector, point2: Vector) → float:
    return (point2 - point1).length

object = bpy.data.objects[“Sphere”]

bpy.context.scene.frame_set(1)
prev_location = object.location.copy()

for frame in range(10, 151, 10):

    bpy.context.scene.frame_set(frame)
    new_location = object.location

    distance = distance_line(new_location, prev_location)
    distance_vec = new_location - prev_location

    time = frame / 24
    velocity = distance_vec / time
    speed = distance / time
    print("frame", frame, "speed = ", speed, "velocity = ", velocity)
    prev_location = new_location.copy()

I have baked the animation otherwise the finding the location of the object in specific keyframes doesn’t work. So the problem with the above code is that if I let the for loop calculate the location for every key frame, it will show the exact same location value for consecutive frames. So, if you change the above for loop to:
for frame in range(2, 151, 1):

you will see that the speed output will be 0 or close to 0 in frames 2, 3, 7, 9, 11, 13, 16, 18, 21, 23, 25, 28, 33, 35,...,
which doesn't make sense.
If I make the loop run for 10 steps I can see the change in location, but it’s still not a gradual change, so I can’t really calculate the exact velocity at a certain point in time. I even get inconsistent values for the velocity with this method. Is there any other way to do it in Blender?

I uploaded a baked version of the file. The result is still the same...


text:
How do I get rid of weird pockmarks on the surface of my object?
I had been making some icing for a donut when I started to notice these evenly spaced out indentations in the texture of my object. I'm not sure if it's the result of adding a subsurf modifier to my mesh or a bad sculpting job. It looks like the pockmarks are directly related to my mesh though.

Could you post a screenshot of what you're seeing?

Yeah, of course.


text:
Hair particles not appearing in cycles mode
I have some hair that I've created in one of my projects. At some point, somewhere, I must have pressed a hotkey by accident, because now none of the hair is rendering in Cycles. It fails to appear in both Cycles rendered viewport or in a full Cycles render. The hair does show up in Eevee and every other viewport mode.
Potentially useful info:

Just as a test, I started another project and was able to get hair particles to render in cycles. I also created another object in this file and tried to put some hair on it. The hair on the new object also didn't render. So it's particular to this blend file and seems to be some sort of global setting.
Note that there are actually three hair particle systems in this
file (eyebrows, upper lashes, lower lashes), and none of them are showing up. So I don't think it's a setting specific to the particle system.
Nonetheless... in the particle system render settings for all three systems, I have "Render as" set to "Path", so that's not the issue. Also, there is a material applied to the hair, but the problem is not solved by deleting it.
None of the "Hair" options in the Cycles render settings have any effect.

I've googled this extensively, and there's apparently a setting called "ray invisibility" that you can turn on or off, but all of information about it I could find are from earlier versions of blender and I can't find this setting anywhere in 2.83. I don't know if that's the problem, but somebody please tell me where to find this setting so I can test it.
Please help, this problem has ground my project to a halt and I feel like I'm losing my mind here.

So I ultimately downloaded the experimental Blender 2.9 and it fixed the issue. I guess that means it's a bug.
EDIT: Another fix, should this happen to any of you, is to create a new project and append all of the assets from the original project. The hair will then render properly in the new project.

I had this and found that I'd inadvertently clicked the Disconnect All button in the Particle Properties tab, just below the list of particle systems.
Selecting each of the items in the list in turn and clicking on the Connect Hair button got them rendering again for me.


text:
No ambient occlusion in render output with eevee, whether it is displayed in the rendering preview. What is the reason and how to solve this?
As you see in the image, there is no ambient occlusion in the rendering output, whether it was displayed in the rendering preview. What is wrong in my settings?

I don see any AO in the AO pass
It seems that I destroying something using the following script.
Moreover, I have the feeling that blender uses for the rendering preview different rendering settings as with F12 or in the script.
import os
import bpy
import csv
from math import radians
import math

dims=[['BBX','BBY','BBZ']]
mdl_fpath="C:\\blender_test_folder\\7406527\\7406527.stl"
output_fpath="C:\\blender_test_folder\\7406527"

#bpy.ops.object.select_all(action="SELECT")
#bpy.ops.object.delete(use_global=True)
print('TEST')

def normtrans_to_center(mdl):
    #mdl = bpy.context.object
    mdl_dims = [mdl.dimensions[0],mdl.dimensions[1],mdl.dimensions[2]]
    max_dim = max(mdl_dims)
    mdl.scale[0]=2/max_dim
    mdl.scale[1]=2/max_dim
    mdl.scale[2]=2/max_dim
    #bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY') with attribute center = 'BOUNDS' better results.
    bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
    mdl.location=[0,0,0]
    return mdl_dims

bpy.data.scenes["Scene"].render.engine='BLENDER_EEVEE'
bpy.data.scenes["Scene"].render.resolution_percentage=100
bpy.data.scenes["Scene"].eevee.use_gtao = True
bpy.data.scenes["Scene"].eevee.gtao_distance=50
bpy.data.scenes["Scene"].eevee.gtao_factor=30

#try:
   # bpy.data.scenes["Scene"].cycles.device='GPU'
#except:
#    pass

res = 512
bpy.context.scene.render.resolution_x = res
bpy.context.scene.render.resolution_y = res
bpy.data.scenes["Scene"].render.tile_x = res/2
bpy.data.scenes["Scene"].render.tile_y = res

bpy.data.scenes['Scene'].render.image_settings.file_format = 'JPEG'
bpy.data.scenes['Scene'].render.image_settings.color_mode = 'BW'
bpy.context.scene.render.image_settings.compression = 0

file = os.path.join(output_fpath, 'test_1')
bpy.context.scene.render.filepath = file

#bpy.ops.object.camera_add(enter_editmode=False, align='WORLD',location=(0.0,0.0,5.0), rotation=(0, 0, 0))
#bpy.context.object.data.lens=50
#bpy.context.object.data.clip_end = 300
#bpy.context.object.data.clip_start = 0.001

bpy.ops.import_mesh.stl(filepath=mdl_fpath,axis_forward='Y', axis_up='Z', filter_glob="*.stl", files=[], directory="", global_scale=1, use_scene_unit=False, use_facet_normal=False)
mdl_name = bpy.context.object.name
mdl_object = bpy.context.object
print(mdl_object.type)
print(mdl_name)
dims.append(normtrans_to_center(bpy.context.object))
bpy.context.object.location=[0,0,0]

for obj in bpy.context.scene.objects:
    if obj.type == 'CAMERA':
        #bpy.context.space_data.show_only_render = True
        bpy.context.scene.camera = obj
        bpy.ops.render.render(animation=False,write_still=True)
```

Take a look at "view layer properties" -> Passes. Do you have AO enabled as a separate pass?

Hallo harriger Troll, thank's for your reply. As you aspected AO was not set under Passes. But unfortunatelly, there is still no ambient occlusion in the rendering output also with AO set under Passes. (Blender version 2.82)

Actually, it is supposed to show up in your completed rendering, when it is NOT set to be rendered as a separate pass.
But when you check the "pass"-option - can you see the pass in your render result window?

In my render result window, I can see under pass: Combined, Depth and AO.

And how does the AO pass look?

I have the same question.


text:
The Perspective view is weird. I am in solid mode and I still only have outlines of the objects
Well it might be a bug, it might be an odd function of Blender too. I am not really sure. The weird view only appears when in 'free view' in perspective mode. (The view where you gan orbit around your scene with the middle mouse button) The problem does not appear in orthografic view, in camera view, in rendered; shading and wireframe view and in the views from top, the side, bottom etc. (Also orthografic)
Second weird thing is, I cant select any of the objects with a single mouse click. I now have to use the circle selector or draw the selection box.
The grid in the viewport disappeared too.
I do not know if I clicked something wrom or used a 'bad' keyboard shortcut or if it really is a bug. I just want to get this dumb piece of garbage out of my viewport.
This picture shows the bugged view. Just as I said. In all the other view modes and in the camera etc. it is just fine.

Download .blend file

The reason why your viewport goes haywire is because of the viewport's Clip Start/End values which you set to crazy amounts.
To give you an idea, your largest object is 2 000 meters (2 kilometers) wide, yet your viewport is set to render stuff up to 100 000 meters (100 kilometers) away.
And you also stuff close up to 1 nanometer from your viewpoint, that's 0,001 millimeters!
A sheet of paper is about 100,000 nanometers thick, a strand of human DNA  is 2.5 nanometers in diameter. You really don't need those clipping values.
In most cases you shouldn't set the Clip Start below 0.001 (1 millimeter). Even that value is rarely needed, and it's only when you need to be really close to something, like when you modelize something of a few millimeters. On a large scene like that, you probably do not even need to set it under its default value: 0.1 m (10 centimeters)
As for the End Clip, it is way too large and will lead to rendering & performances issues. Unless you need to set your camera on one end of your map and be able to see everything up to the opposite end, you don't need more than 1000 m (1 kilometer).
Just a before/after comparison:
crazy clipping values

normal clipping values

Alt + Z toggles the X-Ray mode but now the materials are ghosty. I think that one should be the x-ray because everything is half-opaque. But if I press Alt + Z again, everything just gets grey like before and I only can see the outlines... I really dont know what the heck caused this mess...

Then in solid mode, check your shading options (the arrow icon at the right of voew modes icons), maybe there's something weird here.

Well I have no idea what could be wrong there. I tried unticking everything by its own and it did not change anything...

Oh well... Apparently the shading view is also a bit bugyy, since all the meshes are half x-rayed too. I am pretty sure that is not what it is supposed to look.

It's not just a matter of checkboxes, besides it's not really a good idea to toggle everything without knowing how things work. Please show a screenshot of your shading settings. Or share your original .blend file so we can dig in

I am kind of new to asking questions on stackexchange. If you can explain how I can add more files, I can upload whatever is needed.

Edit your original post, add screenshots using the editor. Send your .blend file as a url. See this page for further instructions on how to send .blend files: https://blender.stackexchange.com/a/82965/53447

I found the problem and edited my original post. Please mark it as an answer to your topic if it solves it well.

Ok I really appreciate the help. I think it was just a matter of the lower clipping distance. That solved it. But I am not sure how it got so far down. I am sure that I di not put it that low. And apparently 10.000 on the upper limit is enough for my scene. I will keep that in mind when I encounter a problem like that again. Thank you very much for your time. :)


text:
Set the graphic card, before the first blender start. (Virtual Linux System)
The problem:
Blender does not start and prints the following error message:
Error! Unsupported graphics card or driver.
A graphics card and driver with
support for OpenGL 3.3 or higher is required.

Background:
Blender should run on a virtual linux system started from a terminal with a X Server. The system gets the graphic card (NVIDIA Tesla P100 Card) by passthrough with OpenGL 4.6.
How to force blender to use this graphic card?
Is there a config file, where the graphic card could be explicit set before the start of blender?
Or is there some configuration of the X Server or the virtual system neccessary?
Usage:
I want to use blender for rendering images of 3D models.

Could you define 'use'? Blender will use the card a monitor is connected to for drawing its UI, but you can set a different card for rendering in most cases. Sometimes it is glitchy- for example I use GTX970 but I cannot run Blender on integrated Intel HD 530 graphics with GTX970 enabled as well because of bugs while both cards work fine separately. So sometimes there are issues with using one for UI and another for rendering, but with other card combinations it works fine.

Please edit your question and add information on what kind of GPU you are using. By default the drivers for nvidia cards will not use CUDA, so you need to use the proprietary drivers, not the opensource ("nouveau") driver.

The use is running blender. My main problem is during trying to start blender I get the following error message: ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
...
Error! Unsupported graphics card or driver.
A graphics card and driver with support for OpenGL 3.3 or higher is required.
But I have on the computer a NVIDIA Tesla P100 Card with OpenGL 4.6.

https://community.khronos.org/t/opengl-version-is-forced-to-1-4-but-card-can-support-4-6-0/104868

No, it is propably cause by an indirect rendering setting for the graphic card driver similar as mention under link.  The warning ALSA lib confmisc.c:767:(parse_card) cannot find card '0' is propably caused by a missing sound device, but can suppressed by ./blender -noaudio.

I was having the same problem and I fixed by coping some dll file from the video i have watched to fix in the blender folder and the problem is fixed you can watch all the full steps hereBlender-How to Fix Unsupported Graphics Card or Driver Errors

Could it be, that the issue is caused, because blender required some sound card?
No, it is probably cause by an indirect rendering setting for the graphic card driver similar as mentioned here. The warning ALSA lib confmisc.c:767:(parse_card) cannot find card '0' is probably caused by a missing sound device, but can suppressed by ./blender -noaudio.

https://community.khronos.org/t/opengl-version-is-forced-to-1-4-but-card-can-support-4-6-0/104868

Welcome to the site :) I've taken the liberty of editing your question and answer with information from your comments to make it easier for others with the same problem to find what they're looking for. If you disagree with any of my edits, please feel free to make additional edits and/or rollback my changes.

That said, is it possible you're looking to run blender on a headless system (no display)? If so, the --background option might be of interest.

Gandalf3, thank you very much for your support.

Blender was displaying the same error message to me.  My problem was that in addition to the video ports provided by my AMD RX 580 graphics card which supports OpenGL 4.6, the motherboard also provided an HDMI video port that did not support OpenGL 3.3.  However, my monitor was plugged into the less capable port.  Switching the monitor cable to the port on the graphics card solved the issue.


text:
Blender 2.83.2 - Only half of the icing's sprinkles are added to the icing
While following a tutorial by BlenderGuru, I ran into an issue where only half of the sprinkles were selected (as shown below).

I really don't know what could be causing this because I followed the tutorial step for step, and did exactly what the tutorial said.
If I make any change to the sprinkle object, like add a material, they all get effected, but if I do something like apply random colors to the sprinkles, only the selected half get effected. I have my model provided below if you need it.
The tutorial: https://www.youtube.com/watch?v=jNmnPXY9UQA
My model:

I had the same problem- I got the sprinkles part down but when I add the random colors, it seems like only half get affected (especially if we're adding more than 2 colors). I was trying to figure out the problem by remaking my sprinkle and messing around with the nodes... but it turns out nothing is wrong with it, it only looks like half is getting affected because we're looking at in through materials preview. If you go to rendered view, the sprinkle colors should be distributed more evenly according to your ColorRamp.