text:
How to call original operator from operator's override?
I would like to amend functionality of an existing operator with a condition check and then "proceed" with the original operator (if condition check allows it).
It is essentially what is done in answer to this question, however I would like to avoid writing the operator's code from scratch (as that answer does in main() ).
I know I can write a new operator and call the original from there but I don't want to add another operator, I want to replace (override) the original one.
So, is there a way to get to the "base" operator's methods from the override operator?
(In that example I managed to get the "OK?" prompt by adding invoke() and calling context.window_manager.popup_menu(). So that sort of solves my initial need, however, some operators are too complex to be rewritten from scratch and the need for calling the "base" operator still stands.)

Writing new operators code from scratch looks like it would work, then call the proceed to another operator in execute. Why don't you want to write a new operator from scratch? Can you do a OOP way and inherit the class from the parent (the operator you want to modify)  and then modify/ register your child class from that ?

Well, as I wrote in the question 4 years ago, some operators are too complex to be rewritten from scratch. Besides it has been so many projects ago that I honestly do not remember the details any more. Thanks for the down-wote, @4nof.

What's "the override operator" if you "don't want to add another operator"? Can you provide a "too complex operator to be rewritten from scratch"? Why can't you add your condition check inside the operator's execute or invoke if you "want to replace (override) the original one"?

It is possible to run the original operator in an override by temporarily unregistering the overriding class during invoke() and execute() and that way avoiding infinite recursion (at least in Blender 2.93). Combining that with a technique for forwarding properties from this forum post https://blenderartists.org/t/extending-built-in-operator/1257955/4 allows you to write a forwarding operator.
def keywords_from_prop(p_rna):
    kw = {}
    for kwname in ("name", "description", "default", "min", "size"
                   "max", "soft_min", "soft_max", "precision"):
        value = getattr(p_rna, kwname, None)
        if value is not None:
            kw[kwname] = value
    if p_rna.type == 'ENUM':
        kw["items"] = tuple((i.identifier, i.name, i.description)
                            for i in p_rna.enum_items)
    return kw

def props_from_op(idname):
    import _bpy
    props_dict = {}
    op_rna = _bpy.ops.get_rna_type(idname)
    for p in op_rna.properties:
        if p.identifier == "rna_type":
            continue
        prop = getattr(bpy.props, p.rna_type.identifier)
        kwargs = keywords_from_prop(p)
        props_dict[p.identifier] = prop(**kwargs)
    return props_dict

class NewOperator(bpy.types.Operator):
    bl_idname = "object.delete" # override delete operator and copy all its attributes
    bl_label = bpy.ops.object.delete.get_rna_type().description
    # if we have our own undo steps, the REDO panel isn't usable
    #bl_options = {'UNDO','REGISTER'}

    __annotations__ = props_from_op("object.delete")

    @classmethod
    def poll(cls, context):
        return True # you will have to write your own poll method

    def execute(self, context):
        # unregister self before calling original operator to avoid infinite recursion
        bpy.utils.unregister_class(NewOperator)
        # execute operator: use True as 3rd parametre to register undo step
        ret = bpy.ops.sequencer.split({}, 'INVOKE_DEFAULT', True, **self.as_keywords())
        bpy.utils.register_class(NewOperator)
        return ret

Note that it could be hard to get the redo panel to work with this technique. In this example I am registering the undo step with the original operator. This way the redo panel keeps working but redoing will NOT trigger your operator again, only the original one. Operators with a modal phase or ones that adjust properties in the invoke phase are also harder to use in this way.

It was very useful, worked perfectly and solved my recursive problems. Thank you so much :)


text:
Issue with IK-controlled Foot Floating in Editor during Ducking Movement with Rigify in Blender - Any Solutions?
I have an issue with GLTF file displaying on Web
Why is my IK-controlled foot floating in the editor despite looking fine in Blender during a ducking movement with Rigify
FYI
https://streamable.com/vzi3b0
It is working just fine on Blender
https://streamable.com/3wqtln
Thanks

Hello and welcome. While files, images, and external videos or links may be helpful additions they should not be the only way to obtain information about your issue. Don't make understanding your question rely on downloading a file, watching a video or visiting an external site. Use the builtin tools to upload images or gifs, along with thoroughly explaining the problem in written form so it can be indexed and searched for thus helping future visitors with similar issues.

I'll add that the glTF format does not store IK directly.  Animations with IK must be baked to sets of keyframes prior to export.

Thanks you guys, but it seems can not be resolved. I have tried baking the IK to FK, the result is the same/

source: Stack Exchange

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

sort: votes


text:
when i apply remesh(in sculpting) image texture is not working

you can see in first model I did not apply remesh image texture is woking fine . but in second model I apply remesh and image texture is not working and i am using same texture for both models

how can i   bake the texture of the original onto the one onto the remeshed version . can you explain little more

The remesh has changed the UVs, but you could bake the texture of the original onto the remeshed version, just sculpt the way you want then check for a "bake diffuse" tutorial

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


text:
How do I make double tap shortcuts?
I want to change the view angle shortcuts like Numpad1+Ctrl to double tap Numpad1, similar to pressing G twice to do something different than just pressing G once.
Is it possible to do this? I read something about modal maps but didn't understand if or how it was applicable to my case. Also, I rather not have to mess with coding just for this, but am willing to try if it is simple enough.

Go in Edit > Preferences > Keymap
Scroll at the bottom of the category 3D View > 3D View (Global) and click the Add New button.
Set the Identifier to view3d.view_axis. Set the corresponding view (here I used Back) and set the corresponding key (without double-tapping).
Then, change the Press method to "Double Click". Once might think it works only for mouse inputs because it says "click", but it works with the keyboard too.


text:
How to cut a mesh to fit into a hole in another mesh?
I'm kind of a blender noob and need some help.  The picture below sort of sums up the problem.  I have a pair of black glasses which I did not model.  I also have some "lens models" that are 8cm in diameter and modeled to the exact shape of a specific eyeglasses prescription.
The image below is an exaggerated solution, some of the prescription lenses are a bit thicker than the frames, but not this much.
The obvious solution was to select a loop of vertices on the glasses and extrude them out into a mesh I can boolen with the prescription lens to cut it to size.  This didn't work because selecting loops on these glasses didn't seem to work. So how to do it?
The prescription lenses are actually like real glasses lenses, I have to use them to get correct refraction when this is ray/path traced, so I need a way to cut them to fit the frames.
The model for these glasses is available here.  It already has some lenses in the frames but not all models I want to use do, some are empty.
https://sketchfab.com/3d-models/glasses-4b8a1e54f3084c63828fe8c324198aec

You say that "selecting loops on these glasses didn't seem to work", maybe you should share your file so that we can try, you should be able to select the frame and use it as boolean object

Hi, at the very end of my post there is a link to the model on sketchfab.  I have tried other models too and have the same problem with all of them.  By the way, the way I got the white shape above was by extruding one of the lenses in the glasses.  Doesn't work for everything though because some eyeglasses models have no lenses or have ones with odd topology.   I'm still a blender noob so maybe I'm not doing it right.

If it's a copyright free model, could you please share it on https://blend-exchange.com/ or another platform?

The model is ccattribution.  Are you unable to download it from the sketchfab link?

Yes I need to register, if it's creative commons please share it

Here it is, I had to convert it from the original USDZ which it would not let me post.
Every time I import the file I have to scale it 0.001 or it comes out gigantic, but that's a different problem.

If you select all in Edit mode and press Alt J it will untriangulate the frame and you'll be able to select the edge loop of the frame, then use it as a boolean object. That said it looks like the glass is already correctly cut off, no?

As I said, this model has lenses, others don't.  Either way I need to take one of my prescription lens models and cut it to fit into the frame.  I'll try your suggestion.

Yes Alt J works here

Took me a bit to test this, but it works....Thank you!

OK, fine then......   ;)

If you select all in Edit mode and press AltJ it will untriangulate the frame and you'll be able to select the edge loop of the frame, then use it as a boolean object.


text:
I am not able to hollow out this object (newbie)
This should be very easy but I am not able to get this to work. I have mainly used Solidworks in the past & I am new to Blender.
I'm trying to 3D print the planets from the NASA data. For example, I downloaded and imported a glTF file from here
https://solarsystem.nasa.gov/resources/2375/jupiter-3d-model/
I scaled it 0.01 since you can't import large files to Shapeways.
I then added the Solidify modifier, made the thickness 4mm, offset -1, even thickness. The rim option checked and unchecked didn't seem to make a wall thickness.
I added a cylinder to make a hole on the top, which is needed for cost effective 3d printing (you need a hold for sandstone and a hollow object). I used boolean to subtract that out.
After I created this hole, I can see there is no wall thickness to my planet. I've watched a few YouTube tutorials on hollowing out a model and I'm not getting what I am missing.
Maybe it's this type of import file? Some setting I'm not getting since I'm a newbie?
I was inspired to do this by this designer
https://www.littleplanetfactory.com/
I tried messaging him on what software he uses but no response.
Thanks for any help.

Hello and welcome. While files, images, and external videos or links may be helpful additions they should not be the only way to obtain information about your issue. Don't make understanding your question rely on downloading a file, watching a video or visiting an external site. Use the builtin tools to upload images or gifs, along with thoroughly explaining the problem in written form so it can be indexed and searched for thus helping future visitors with similar issues.

Hard to say why your boolean doesn't work, but you can create your hole without. First in Edit mode select all and AltJ to untriangulate, M to Merge by Distance (you have overlapping vertices), then select 4 faces on the top:

Then inset with i, enable the LoopTools addon and right click > LoopTools > Circle:

Delete the faces and give your object a Solidify modifier:

If your object needs to be rounder, give it a Bevel and a Subdivision Surface modifier, increase the bevel Angle value to keep the hole round:

If the hole needs to be small, select only one face, inset, subdivide, LoopTools > Circle and delete:

Before printing of course you'll need to apply the modifiers (and also I guess create some legs?)

Thank you!! Your pics look like what I'm aiming for.


text:
How to animate Texture change in Blender Internal
I want to change the texture of specific objects, making shift across the surface of the object. I don't know how to insert keyframes for UV mapping though.
How can I make the image on the object move?
Think of a magical cape, with the design constantly flowing on the cloth.
How could I achieve something like that?

Does this help: http://blender.stackexchange.com/questions/32091/can-i-have-a-unique-uv-map-for-each-frame, http://blender.stackexchange.com/questions/18363/animating-eye-texture-in-a-head-mesh ?

Related, or maybe even a duplicate? http://blender.stackexchange.com/questions/32091/can-i-have-a-unique-uv-map-for-each-frame

I dunno. It looks like it might work. They seem to be about changing the whole UV texture to another. I want to slide the texture across the surface of the material.

How about this? http://blender.stackexchange.com/questions/35887/how-to-create-and-apply-a-moving-texture

"page not found" "Page was voluntarily removed by its author"
@Gonzou found another one that says I'm  "Mildly doomed"

@BookWyrm17 See another related: http://blender.stackexchange.com/questions/36748/how-do-you-animate-image-texture-materials-in-blender-cycles-with-keyframes

@BookWyrm17 The answer below shows how to animate textures in Blender Internal as you asked. Tell me if this is the effect you want to achieve. I'll try to update an answer soon to show you how to do it in a different way (using AnimAll addon).

You may move the overlayed texture pattern over the other texture animating its Offset parameters.

Prepare the image with your pattern (use a .png image).

Set up the textures as pictured below. Check the Color box in Influence panel.

In Mapping panel animate the desired parameters.

To loop the animation indefinitely you can use a Cycles Modifier. Go to the Graph Editor, press N to open its properties shelf and add this modifier in Modifiers panel.

Yes! That is exactly what I was looking for. Thank you!

You may shift textures animating the Offset value of the gradient texture, which works as a mask for transition between two textures.

Prepare two different textures.

Add a new material to your surface and unwrap it. Give it two image textures (set their type to Image or Movie and mapping coordinates to UV). Now add one more texture. Set its type to Blend and place it between previously added ones. In Influence panel uncheck the Color box and check Alpha. Check the RGB to Intensity and Stencil boxes.

Now the gradient texture acts like a mask. In Colors panel check the Ramp box and use sliders to define the smoothness/sharpness of the transition between textures.

In Mapping panel change the Offset value of the X window so you can see only one texture. Hovering your cursor over that window press I to insert a keyframe. Go to another frame, change the Offset value and press I again.

This would be great for one of the problems I have. But the issue I have now is that I don't know how to make the texture move across the surface of the material.
How can I make the image on the object move?
Think of a magical cape, with the design constantly flowing on the cloth.
How could I achieve something like that?

If I got your idea correctly, you want to move the texture pattern from the top of the cape to the bottom of it and repeat it continously, right?

Correct. While the material stays the same shape, I want the pattern to move.

Ok, done. It's actually much simplier to create. Please see my new answer.

this maybe is a bit dumb but easy: you could add an object moving along 1 or more axis, in the environment but out of sight, add a driver node linked to the object location. add keyframes to differnet object locations based on the values you want to obtain (for example if I want my tecture parameter to assume values 1 or 2 I will shift the object position from Z = 1 to Z = 2 at the desired frame). Do the same for the other axes, Y and X. now you have potentially 3 values that are changing every frame of the amount you want and that can affect your texture in 3 different ways.

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


text:
Object falls though other objects even when given the same physics
So, I made a bunch of spheres (they don't bounce yet) that are supposed to fall and hit the plane beneath them, and stop. All of them, big and small, do exactly that... except one. This one keeps falling right through the plane. First I changed all the physics in the physics tab to make it work, and when nothing changed, I deleted that one, copied directly off of another ball, and placed it where it was supposed to go.
And it fell through.
Its an exact copy of the other one. Does Shift-D only copy the physical properties of something, and I was just unaware of this?

A blendfile will probably help find the issue. Upload to: http://blend-exchange.giantcowfilms.com/

As in send you the blender file that has the issue?

You can host it online through the link specified above, then attach it to a comment here, or edit your question to include this link. That way anyone who wants to help will be able to download and examine the file.

The blend-exchange keeps giving a "fatal error". I have no clue what to do to send the file. :/

Have you tried applying the scale on the faulty ball?

Hope this helps http://blender.stackexchange.com/questions/1811/tips-for-making-mesh-rigid-body-collision-shapes-more-stable

I've been having the same problem with objects falling through a cube surface even with a box collider. This post - Why is this passive rigid body allowing objects to pass through it? - has a really helpful comment from @satishgoda. If you go into the Scene tab in the Properties window, and increase the Steps per Second (I needed 300 steps) that should help prevent some of your smaller objects from falling through.

increasing steps worked great, thanks

thank you! that solved it! It further helped to increase the sensitivity margin under physics properties of the object. This needs to be changed in every object. (Default is only at 0.04 m)

I encountered this in blender 3.2.2. The settings have moved to Properties > Scene tab > Rigid Body World > "Substeps per frame" and "Solver Iterations". For my usecase I had to increase them to 15 and 150 respectively to get clipping down to an acceptable level.

I've had issues with physics objects falling through a plane before when the Scale hadn't been applied to it, so make sure you have done that — CTRL+A > Scale

There are a few things that could go wrong. Here are some common problems:

Plane isn't "solid" try using a cube or the Solidify modifier
Bounding volume isn't "box" for the floor
Bounding volume isn't "sphere" for the spheres

Here is a short YouTube video I made where it worked in 2.76. I hope it helps.
https://www.youtube.com/watch?v=uzF24ianiwY&feature=youtu.be

Well all the spheres hit the plane except one. And that one just falls through.

As I demonstrate in the video make the Plane solid.

Yeah but my plane interacts with all the rest fine! I even made the new one a copy of one of the ones that hits and it still falls though!
I want to understand it, not just make a quick fix.

It's because the "Box" modifier around a plane doesn't properly describe how that object can pass through it. If you crank up the iterations or modify the time-stepping it may stop falling through, but the reason it's falling through is because the simulation can't tell if it was falling from above or below the plane if there is too much error in the simulation. Error increases as more objects have to push each other off one another. By making the Plane a box or setting "Margin" on the plane for the box bound you reduce this error by how thick the floor box is.

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


text:
Scale Interior While Retaining Objects Scale
I was wondering if there was a way to take the object in the first picture and increase its interior radius, without scaling the actual rectangles scales.
1x1x2 Blocks

1x1x6 Blocks

Well not without modifiers at least. If those blocks were made using the solidify modifier you could scale them at will in edit mode. Otherwise use the top view and move the vertex 2 units in X or Y direction

If you specifically want to use the scale command you can only do it using modifiers to add thickness, otherwise the scale command will also affect the thickness of the blocks.

Otherwise use the move command instead and move the vertex 2 units in X or Y.

Perfect! Exactly what I needed. Thank you for the quick reply


text:
Glass Shader for PNG Export
I am trying to model a tub with clear material. The output will be PNGs as these assets will be used as static images and videos (PNG sequence to Adobe)
My issue is the clear material is not perfect, the thickness of the materials generates dark areas.

As you can see when exported as PNGs they have dark thick edges/sides.

hello, it's reflecting your World so maybe change the World?

Hi, Moonboots.
Yeah, the world is the default gray. I played around with it and changed it to FFFFFF(White) still the strength is at default. And now it is white.

I also tried setting the world strength to 0 and now it is dark.

don't you want to use an HDRI image? It would make it more natural

I did and it game me the same results. The material is also noisy.

noisy? i thought your problem is that the reflection was black, if you use an HDRI image it should reflect the image, maybe pack your image and share your file?

Do you have denoise on in your render settings?


text:
Any idea why the lighting is bugging out on the left, i found this out when i was rendering my scene to see how it looked
I was rendering my scene early to see how it looks and i ran into the lighting or something getting bugged out when i was rendering. Im using cycles and any idea on how to fix this would be appreciated. Thanks a bunch!

You're going to have to clarify this.. it look reasonable from the evidence, on the left. Do you mean the triangles on the right?

there may be multiple objects in the same area. try clicking on the bugged out area and deleting some things.


text:
Change collision bounds of an object with character physics based on its child mesh in UPBGE
I am using character physics on an invisible cube object to control the main character in a game I'm trying to create for my project, but I wanted the character physics objects collision bounds to match my actual character mesh and change according to the current animation.
I tried using compound option but it lead to blender crashes due to exeption access violation or the object would just fall down without colliding with the land mesh
reinstancephysicsmesh() only works with triangulated phy mesh but character physics only support convex hull.
Can someone with a better insight on this please suggest a method to get over this using python or logic bricks(python prefered cause my project requirement asks for python to be used).

Try asking in the UPBGE forums where you're more likely to get an answer. - The game engine was removed from Blender a couple of years ago and this Q&A site deals mainly with native Blender nowadays, albeit still having a game-engine tag available. The docs for it appear to be here.

I did ask in blenderartist.com and I am waiting for a reply i asked in this forum too just in case someone who has the knowledge about this appears to pass by the post


text:
Texture paint - lags
I'm using blender v2.76 in cycles render.
I'm trying to texture paint on my model(21k verticels). But blender lags, on small brush, big bush, etc.
My texture is 2048x2048 in resolution. I have nVidia 960M,8 GB RAM, i7 4720HQ processor so that should not be a problem. I try to disable use nodes. I have no active modifiers on model.
I tried to active region overlap option in system preferences, and window draw method to Triple Buffering.
Image texture is generated from blender and is 16 bit(not 32). Occlude, Cull, Normal options disabled or enabled. Still no change and disabled smooth option for brush.
I thought my last pc was no so good, so I buy new one for blender and get same issues. (That drives me mad) .
Can somebody help me ?
Thanks

Have you tried to find out which factor (texture size or mesh density) affects most your issue?

@m.ardito Both the same way but mesh density maybe a little bit more I think. If i zoom to model and paint a small area, it lags for 2 seconds. if i zoom out with same brush and paint edge of the model. it is better but if I outzoom a lot and paint half of the model or full model. it lags and i had to restart blender.

What are the active modifiers on the model? Have you tried to paint not on model directly in 3D View, rather than on texture in UV/Image Editor? Have you experienced such problems with other files? Probably you should import this model into another .blend? Does your OS respond fast in other programs? And also: maybe there is something to change with your OS, not with Blender.

As I said, there are no modifiers on object. I tried it on different pc with same result. I also try to just start up cube and get same lags. I'm painting on 3D model not to UV/Image Editor. Now I download older version and try if the problem persist. @MrZak

From your question: "..I have active modifiers on model... " From your comment: "As I said, there are no modifiers on object...." Please edit either one of them so they to fit each other. As to lags - I haven't ever had and still don't have such problems on computer with much less powerful configuration, so it seems to me this is not Blender related problem. But you're right, check everything, including downgrading to older version.

Fixed. Sorry for missdirect. Are you using windows 10 ? Older version does not help to me :/. @MrZak

I'm using Win7 32 bit. Does your PC work properly while in other programs? If yes, then taking into account your PC system configs and that Blender should be (and it seems to be that really is) compatible with Win10 - take a look at one thread, second - then you are facing some OS problems as it seems to work for other people.

Okay version v2.72b works for me fine.


text:
UV Texture Error

I downloaded this model from Mario Kart and the UV came out like this in multiples. I don't really know how to deal with a UV that comes out like this. The concept is to only have that one pupil in the eye, but how do I subtract the others without making that one disappear too. I tried using blend types to but nothing work. Anyone know what options to press to fix this?
Model Download Link: https://www.models-resource.com/wii_u/mariokart8/model/9758/

Any chance you can link us where you downloaded it from? Assuming of course it is free and open-source

Looks like a face around left eye on the UV map is overlapping with another one. Unfortunately there's no way to lnow exactly without model or at least screenshots of the UV map overlayed on texture and mesh in Edit mode.

It's in the question now.


text:
'bpy_prop_collection' object has no attribute 'link'?
I'm using Blender 2.8+ and I found a web page containing a nice python script to generate a labyrinth. I copied the script in Blenders text editor and an error occurred at line 88:
bpy.context.scene.objects.link (object)

AttributeError: 'bpy_prop_collection' object has no attribute 'link'
  Error: Python script failed, check the message in the system console

Unfortunately, I have no idea what a 'bpy_prop_collection' is and I don't know where to start fixing this issue. What I need to do in order to make the script work for Blender 2.8x?

Need waaay more information. "The error" is not a basis for debugging. At least paste error output and tell us what version you're using.

Related https://blender.stackexchange.com/questions/95408/how-do-i-create-a-new-object-using-python-in-blender-2-80  Found via  googling ""site:blender.stackexchange.com bpy_prop_collection' object has no attribute 'link'"   For scripts like above, recommend adding  a comment to the blog re the error, or now by adding a link to upgraded to 2.8x code supplied by @brockmann

If you are interested: As of Blender 2.8x SceneObjects.link(object) is gone due to the new collection system. You can use CollectionObjects.link(my_object) instead so you just need to replace a single line to "update the script" for Blender 2.8x:
- bpy.context.scene.objects.link(object)
+ bpy.context.collection.objects.link(object)

Blender 2.80: Python API Changes

blender labyrinth generator 2.8x:
from random import shuffle
from array import *
import bpy

N=1
S=2
E=4
W=8

odir = {}
odir[N] = S
odir[S] = N
odir[W] = E
odir[E] = W

WIDTH=40
HEIGHT=40

coords = []
faces = []

d = [[0 for col in range(WIDTH)] for row in range(HEIGHT)]

for i in range(0,WIDTH):
    for j in range(0, HEIGHT):
        d[i][j] = 0

def carve( x, y ):
    dirs = [N,S,W,E]
    shuffle(dirs)

    for i in dirs:
        print(i)
        nx = x
        if i == E:
            nx =  nx + 1
        if i == W:
            nx = nx - 1
        ny = y
        if i == S:
            ny = ny +1
        if i == N:
            ny = ny - 1
        if nx >= 0 and nx < WIDTH and ny >=0 and ny < HEIGHT and d[nx][ny] == 0:
                d[x][y] = d[x][y] | i
                d[nx][ny] = d[nx][ny]  | odir[i]
                carve(nx, ny)

carve(0,0)

idx=0
step = 0.1

for x in range(0,WIDTH):
    for y in range( 0, HEIGHT ):
        if ( d[x][y] & N ) == 0:
            coords.append((x * step , y * step, 0 ))
            coords.append(((x+1) * step, y * step, 0 ))
            coords.append(((x+1) * step, y * step, step ))
            coords.append((x * step, y * step, step ))
            faces.append(( idx, idx+1, idx+2, idx+3))
            idx+=4
        if ( d[x][y] & S ) == 0:
            coords.append((x * step , (y+1) * step, 0 ))
            coords.append(((x+1) * step, (y+1) * step, 0 ))
            coords.append(((x+1) * step, (y+1) * step, step ))
            coords.append((x * step, (y+1) * step, step ))
            faces.append(( idx, idx+1, idx+2, idx+3))
            idx+=4
        if ( d[x][y] & E ) == 0:
            coords.append(((x+1) * step, y * step, 0 ))
            coords.append(((x+1) * step, (y+1) * step, 0 ))
            coords.append(((x+1) * step, (y+1) * step, step ))
            coords.append(((x+1) * step, y * step, step ))
            faces.append(( idx, idx+1, idx+2, idx+3))
            idx+=4
        if ( d[x][y] & W ) == 0:
            coords.append((x * step, y * step, 0 ))
            coords.append((x * step, (y+1) * step, 0 ))
            coords.append((x * step, (y+1) * step, step ))
            coords.append((x * step, y * step, step ))
            faces.append(( idx, idx+1, idx+2, idx+3))
            idx+=4

mesh = bpy.data.meshes.new(name="MyMesh")

object = bpy.data.objects.new( 'MESH', mesh )
bpy.context.scene.collection.objects.link( object )

mesh.from_pydata( coords, [], faces )
mesh.update( calc_edges=True )


text:
Applying opencv distortion parameters to camera or setting custom projection matrix for render
I need to set a camera and render images with that camera. I have rotation and position data as extrinsic parameters and focal length, shift values and radial and tangential distortion coefficients as intrinsic parameters from opencv. I succesfully applied all the parameters except radial and tangential distortion coefficients.
There is an lens distortion value in Blender in Compositor Editor but it is just single value. I need three parameters k1, k2, k3 for radial distortion and two parameters p1, p2 for tangential distortion. How can I achive to use those parameters? I can manually set the projection matrix by myself. However is it possible to use custom projection matrix for each 3d points in the scene for render image?

The tangential distortion can not be modeled in the current version.
The radial distortion with three parameters can be entered in the Movie Clip Editor (Shift F2) in the 'Track' panel under 'Lens'. Then they can be applied with the Movie Distortion node in the Compositor (Shift F3).
The same question was asked by me here and also asked here. Check the answers to those questions for more details.
Regarding the projection matrix: 6 years ago, it was not possible to set a custom projection matrix, but a workaround using orthographic projection was suggested: see here. However, I don't know if this has changed since 2014.

As pointed  out by others already, the distortion parameters can be set in the move clip editor. Blenders. Interface deals only with radial distortion (k1,k2,k3).
In the compositor the node to use is not the lens distortion one, but the movie distortion one and needs to be linked to a move clip, or image, used in the move clip editor.


text:
Blender adds Armature name to Actions name when exporting FBX

When I export an animated FBX with different Actions in it, Blender renames the Actions like this (Armature name 2x before the action name). I tried renaming the Actions directly in the Blender file menu, but whenever I export the fbxs, those "Armatures" are added to the Actions name.
This doesn't cause any issue, it's just driving me mad and I didn't find anything about it on the internet

Typicaly there can be a lot of animations in one file, and nobody knows relationships beetween animations and objects. To sort out you may put on all animations in NLA then in Export setting checkmark export NLA, disabling Export all actions:


text:
Auto-keyframing fails to record when a modal timer op is setting position/rotation?
I have a serious problem in understanding how the Modal Operator works. I created a Python script using the Modal Operator Timer template, which basically translates and rotates the camera of the scene taking data from a sensor. The function called is:
def get_rotation(self):
        data = tracker.get_data()
        print("Received:\n%r" % data)
        try:
            camera.rotation_quaternion[0] = data[3]
            camera.rotation_quaternion[1] = data[4]
            camera.rotation_quaternion[2] = data[5]
            camera.rotation_quaternion[3] = data[6]

            camera.rotation_quaternion.rotate(math_rot_x)
            camera.rotation_quaternion.rotate(math_rot_z)

            camera.location[0] = data[0]
            camera.location[1] = -data[2]
            camera.location[2] = data[1]
        except KeyError:
            raise ExitOK

And this function is called here:
def modal(self, context, event):
        if event.type in {'RIGHTMOUSE', 'ESC'}:
            print("Vive Tracker to Camera FINISH")
            return {'FINISHED'}

        if event.type == 'TIMER':
            self.get_rotation()

        return {'PASS_THROUGH'}

Now, everything works fine, but if I activate the "automatic keyframe insertion" button, it doesn't "record" anything. Why is this?

Is the issue with same object and properties being set by both, or does the auto record not work for all when the timer is running?

the auto record doesn't work for all.


text:
Reconstructing axis of pot with one shard via vertex normals
I`m planning to do a reconstruction of a whole pot from one shard of it.
I've already thought of a way to do it, but I really don`t know how to make it happen in code.
Theory: every shard has a certain bend to it. This bend contains two pieces of information:

the orientation of the shard within the pot
the diameter of the pot.
You can easily see this when turning on vertex normals in edit mode. Technically, from the process of making pottery, there is a center axis in the middle of every pot. The vertex normals cross this axis, so you can see the axis clearly when turning the vertex normals on.

Problem:
how do I reconstruct that axis via script? mathematically it is the intersection of the vertex normals with a thin cylinder.
Step one would be to select the vertex normals from a certain selection only, as I don`t need the one facing outwards...

Test Shard

Related https://blender.stackexchange.com/questions/133870/how-can-i-create-a-mathematically-correct-arc-circular-segment

https://blend-exchange.giantcowfilms.com/b/gJM8bplr/

@batFINGER
The approach you posted may be a lot better! I`ll take a closer look at it, thanks :)

Thankyou for posting  link. Can the pot be considered cylindrical?  Have an inkling could do something with convex hull, which will have longest edges across concavity (arc)  Then look for maximum  distance centre point of edges to shard surface. (closest point on mesh)

@batFINGER really looking forward to seeing your approach, if it goes . . As I see it atm, in large part the problem is not very Blenderish.. more like this

..or, since we don't know the angle of the shard to the axis of rotation, it might be better,(assuming the fragment is approximately one of a cylinder,) to fit to an ellipse, from which the cylinder's axis could be deduced.

@RobinBetts agreed.  Added POC answer re using convex hull to get lines crossing cavities to generate sample data  points to then crunch into links algo.  For demo purpose have used simple 3pt arc formula.

Proof of Concept

Result on single selected edge of convex hull
Further to comment, have added this as going some way to proof of concept,
Fistly here is a script that copies your object and mesh to another, goes into edit mode and converts it to a convex hull.
Select the shard and run
import bpy
bpy.ops.object.mode_set()
bpy.ops.object.duplicate(linked=False)
dupe = bpy.context.object
dupe.display_type = 'WIRE'
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.convex_hull()

after which new wire frame of the convex hull of original in edit mode with all geometry selected.
The next script goes thru the edges of the hull, finds the closest point on the mesh to its middle point, uses these to create a circle from chord as described here How can I create a mathematically correct arc/circular segment?
To visualize have added a vert at circle center and the two joining edges.  As data would save as radius, centre coordinate, and normal (axis of rotation the normalized cross product of two edge vectors)
Test script, creates predicted circle "wedges" for each selected edge.  Run with convex hull mesh in edit mode, edges of interest selected.

Result on all edges of convex hull
import bpy
import bmesh
from math import asin, degrees
context = bpy.context
scene = context.scene
ob = context.object
me = ob.data
bm = bmesh.from_edit_mesh(me)
shard = scene.objects.get("3D_Scherbe_Model_50K")
#edges = bm.edges[:]  # all edges
edges = [e for e in bm.edges if e.select]
#edges = [e for e in bm.select_history if isinstance(e, bmesh.types.BMEdge)]
for edge in edges:

    o = (edge.verts[1].co + edge.verts[0].co) / 2

    hit, loc, _, _ = shard.closest_point_on_mesh(o)

    if hit:
        h = (loc - o).length
        if h < 0.1:
            print("On surface")
            continue
        a = edge.calc_length() / 2
        r = (a * a + h * h) / (2 * h)
        if abs(a / r) > 1:
            # math domain error on arcsin
            print("N/A")
        else:
            angle = 2 * asin(a / r)
            print(f"{r} {degrees(angle)}")
            vc = bm.verts.new(o + r * (o - loc).normalized())
            for v in edge.verts:
                bm.edges.new((v, vc))
bmesh.update_edit_mesh(me)
me.update()

Notes.

Instead of predicting a circle from the closest point to edge centre, could walk the edge and make  sample points to crunch into   https://meshlogic.github.io/posts/jupyter/curve-fitting/fitting-a-circle-to-cluster-of-3d-points/ and https://github.com/ndvanforeest/fit_ellipse as suggested by @RobinBetts.

Similarly could use the generated circle estimate to test against actual mesh surface.

Look at the normal returned from closest point on mesh.

Narrow down the selection, is there historic data that suggests radii or wedge angle within a certain range.

Project (closest point on mesh) equal length "subchords" of edge onto mesh, if each has same radius and angle would be a perfect match.  Minimize for best fit.

Look at the bounding box dimensions. If an edge is shorter than some fraction of minimum bbox dimension it is probably not major pot axis. Consider shaving off some percentage.

Decimating cleaning or smoothing shard mesh in some way.

Brilliant! I don't have so much time right now as I want to have to dig into it, but the first look is very promising! If you believe or not: reconstructing a pot is all done by hand at the moment. So basically every digital process is already an improvement to precision. Selecting edges by the user could track down the relevant "wedges" for reconstructing the axis quite effectively. Decimating and cleaning  would certainly help, but also alters the original data.

I may have to look for the impact by taking a shard of a pot with a known diameter, but I guess as long as the convexity of the arc doesn't change, the result should roughly be the same... or by comparing a high res mesh to a mid sized and a low poly one. If the calulated radius doesn't change much, it would make things easier to handle. I guess that depends also strongly on the size and convexity of the fragment.


text:
Shapekey driver miscalculates during playback and render?
video example, slightly NSFW

I am using corrective shapekeys for my ankles (see video link above).
The driver expression is the angle between two bone vectors.
Blender does notify me that it's "Slow python expression"
For example: poseBones[103].matrix.col[1] * poseBones[12].matrix.col[1]

I have many other drivers likes this in the scene. They all randomly bug out/don't update/delay. Both in render and viewport playback/edit. It's completely random.

Is it because of my slow expression?
Are there better workarounds?
Are there "non-slow python expressions" that can output the angle between two bones?

EDIT:
My computer spec: 2060rtx 5900x 16gb ram SSD
Tried on other computers with the same file. Same problem occurs, and again, the drivers bug out randomly.

Hard to say on info given. https://blender.stackexchange.com/questions/134270/use-self-and-the-slow-python-expression  There is a rotation difference driver variable type  Which takes two target objects (bones) and returns the angle between in radians.

which one is it? Can it give you the absolute angle and not just difference between selected axi?

it gives the angle between.  two bones like  vector.angle(vector2)  eg there  is 90 degrees between z axis and both y and z.  Could you elaborate on how you are using the resulting vector objtained by multiplying the pose bone matrix columns as outlined above?

https://gyazo.com/855e5c4b6101a359c64a69a6642eaa7d like this


text:
Python module installation does not work
For some of my python scrips i need additional modules like pytables. I followed the instructions here, but nothing worked for me:

first I set the PATH and PythonPath system vars to C:\Python34
then I tried to copy the module files from C:\Python34\Lib\site-packages to C:\Program Files\Blender Foundation\Blender\2.74\scripts\modules, but when I try to import a module in the blender python console, it gave me an error (see below)
I deleted the C:\Program Files\Blender Foundation\Blender\2.74\python, but then in the blender system console it says: Warning: bundled python not found and is expected on this platform. <if you build with CMake: 'install' target max have not been build>

this error:
import tables
Traceback (most recent call last):   File "<blender_console>", line 1, in <module>   File "C:\Program Files\Blender
Foundation\Blender\2.74\scripts\modules\tables\__init__.py", line 25, in <module>
import numpy   File "C:\Program Files\Blender Foundation\Blender\2.74\scripts\modules\numpy\__init__.py", line 185, in <module>
from . import add_newdocs   File "C:\Program Files\Blender Foundation\Blender\2.74\scripts\modules\numpy\add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc   File "C:\Program Files\Blender Foundation\Blender\2.74\scripts\modules\numpy\lib\__init__.py", line
8, in <module>
from .type_check import *   File "C:\Program Files\Blender Foundation\Blender\2.74\scripts\modules\numpy\lib\type_check.py", line 11, in <module>
import numpy.core.numeric as _nx   File "C:\Program Files\Blender Foundation\Blender\2.74\scripts\modules\numpy\core\__init__.py", line 6, in <module>
from . import multiarray ImportError: DLL load failed: %1 ist keine zulässige Win32-Anwendung.

I am using Win7 64bit version, python 3.42 and Blender 2.74.
I really don't know what I can still do to import these modules.

If you can start command prompt, and get python34 REPL, and import numpy and tables without errors, there's little reason that Blender's python console can't do the same.
Determine which python executable is used
Run this bit of code in two different locations. First from command prompt python interpreter and then from Blender's python console.
import sys
print(sys.path)
print(sys.executable)

You might notice that Blender isn't finding the same python executable. If they are different, this can explain why imports are failing. If they are the same that's a good thing. Half the battle is won!
Test your Python separately first.
On windows make sure the C:\Python34; is at the start of the PATH line, when you type in python into command prompt you'll want 3.4(.1+) to launch. (At least, I've had success with that and numpy1.8 on windows)
You should also be able to import numpy from command prompt without errors
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) <edited>
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> # also try the other important imports, stuff must work from here too

If you get errors from this python interpreter, forget about blender and fix the errors first. Once fixed, blender too will be able to use the libraries.
If you still have the python directory inside Blender's folder now is a good time to rename it to _python.
The Blender warning when you rename/remove its own python folder

Warning: bundled python not found and is expected on this platform.

is just that, a warning. Telling you that Blender looked in the directory where it keeps Python and couldn't find it, that's OK. It's perfectly fine to use your local Python34 installation, on windows I prefer to use it that way. Pasting around libraries into scripts/modules folder obviously didn't work, I suggest removing the files you added there to prevent them from interfering with imports.
For sverchok we found it was necessary to install Numpy 1.8 and Python3.4.1, and did a small write-up. I won't reproduce here because this is bordering on off-topic.
Forcing Blender to use your local system Python3.4.x
When Blender is forced to use the system's local python 3.4.x it hoists some paths of its own into the global namespace at runtime, to allow for importing bpy and all other blender modules. Apart from that the py3.4 runtime is entirely your system's.
If your imports are failing inside Blender, even though it uses the local python3.4, it is likely because you moved libraries into scripts/modules/.. or one of the other paths listed in sys.path. Python is going to look in the sequence given by sys.path, it iterates over the list, to find an import that matches your import statements. if Python finds anything before it hits 'C:\Python34\lib\site-packages` that will be tried first and only.
You should have a nice directory with all your python3.4 libraries like
C:\Python34\lib\site-packages\numpy
C:\Python34\lib\site-packages\scipy
# etc

i did exactly this. when i start python from cmd and import modules, it does perfectly work. after renaming  the C:\Program Files\Blender Foundation\Blender\2.74\python folder it only shows me the error above and i can't import numpy or tables. if i call sys.path in blender, it shows first this, following with my C:\Python34 paths: ['C:\\Program Files\\Blender Foundation\\Blender\\2.74\\scripts\\addons', 'C:\\Program Files\\Blender Foundation\\Blender\\2.74\\scripts\\startup', 'C:\\Program Files\\Blender Foundation\\Blender\\2.74\\scripts\\modules', ...

what about http://stackoverflow.com/questions/5927633/how-to-get-current-python-interpreter-path-from-inside-a-python-script sys.executable and help(sys).

in Blender's python console: 'C:\\Program Files\\Blender Foundation\\Blender\\blender-app.exe' and in cmd: 'C:\\Python34\\python.exe', the log of help(sys) from blender i posted here: http://pastebin.com/2uQrvzxX

I will update my answer.


text:
How do I add a new panel to the Properties Editor?
First, I want to make sure I'm using the right terms and talking about the proper part of the Blender workspace. From reading a few different answers on SE:Blender, and a few other sources, my understanding is that the area in the blue box below is often called the "Properties area," and that the area in the red box is the "Properties Editor." But I've also read things that make me think the area in the blue box is not called a "Properties area," or anything like that.

So, first, can someone provide me the correct names for these areas? And, since I'm not sure of names, I'll just call them the highly technical terms of "Red Area," and "Blue Area."
A user on SE:Blender sent me an example script that created a tab and panel in the red area, so there was another panel for a specific use. I tried it a couple months ago and it worked. I've been heavily involved elsewhere for awhile and came back to this issue about 2-3 weeks ago. I copied his script in and it didn't work - no panel in the Red Area.
So I went into the Script Editor and picked the "Ui Panel" from the templates and ran that. It looked to me like it was supposed to add a panel to the Red Area, but it didn't. I checked the tabs in the 3D View and nothing was added there at all.
Then I copied the script in the image above from this answer to test it:
import bpy
from bpy.props import FloatVectorProperty, BoolProperty

class CarPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Car Details"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

    @classmethod
    def poll(cls, context):
        return context.object.get("Capot", False)

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

        car = context.object
        layout.prop(car, '["Capot"]')
        #bools don't show well (1 or 0 integer)
        layout.prop(car, "switch")
        layout.prop(car, '["bool"]')
        col = layout.column()
        col.prop(car, '["prop"]')
        # car color property
        row = layout.row()
        row.prop(car, "car_color")
        # object color rgba
        row = layout.row()
        row.prop(car, "color")

def register():
    # define a registered property (available for all Object types size=4 gives rgba)
    bpy.types.Object.car_color = FloatVectorProperty(subtype='COLOR', size=3)
    bpy.types.Object.switch = BoolProperty()
    bpy.utils.register_class(CarPanel)

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

if __name__ == "__main__":
    register()

I did not see a panel added in the Red Area or anywhere else at all.
Last example - I went to Blender documentation and this page has this script:
import bpy

class ObjectSelectPanel(bpy.types.Panel):
    bl_idname = "OBJECT_PT_select"
    bl_label = "Select"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"
    bl_options = {'DEFAULT_CLOSED'}

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

    def draw_header(self, context):
        layout = self.layout
        layout.label(text="My Select Panel")

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

        box = layout.box()
        box.label(text="Selection Tools")
        box.operator("object.select_all").action = 'TOGGLE'
        row = box.row()
        row.operator("object.select_all").action = 'INVERT'
        row.operator("object.select_random")

bpy.utils.register_class(ObjectSelectPanel)

I ran it and it seems to have no effect at all.
So what am I doing wrong? Why don't these scripts seem to do anything and what do I need to do to add a panel to the Red Area? (And what are the proper names for the Red Area and Blue Area?)

If you mean adding a panel on the left of the red area, you can't with Python. You'll have to dive into the source code for that. If you open the object properties (Orange square icon) you'll see your panel there in addition to all the default ones

For the record: Blue is the Outliner, Red is the so called Properties area which is always context dependent, meaning dependent on what you have selected in the Outliner or the 3d viewport.

@brockmann: Thank you for clarifying that for me. I've gone through multiple books and tutorials, but it's a lot of information to absorb. I do better remembering the logic and what does what, but names are easily confused.

Easy, I'd suggest start here: https://blender.stackexchange.com/questions/57306/how-to-create-a-custom-ui/57332#57332

@brockmann Again, thank you!

Texture context
when adding a panel to the properties area we set the context as signified by the icon on LHS. This is set with bl_context.  To get a panel in the questions "Red Area"
bl_context = "texture"

all the examples given in question are in object context. Press the Object tab. (cube)
How to enable or disable panels with the click of a button
Eg for Hello World example.
import bpy

class HelloWorldPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "texture"

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

        obj = context.active_object

        row = layout.row()
        row.label(text="Hello world!", icon='WORLD_DATA')

        row = layout.row()
        row.label(text="Active object is: " + obj.name)
        row = layout.row()
        row.prop(obj, "name")

        row = layout.row()
        row.operator("mesh.primitive_cube_add")

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

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

if __name__ == "__main__":
    register()

A couple points to clarify. The 1st comment on my question states I can't add a new tab and, since you're talking about context, I take it that's correct - you can't add a complete panel? Also, by context, if I switch from texture to object, then this new panel should show up in the object context, right? And will it always show up in the Object tab?

Is one able to add their own context tab somehow?

any chance to add a completely separate section? in the same height as object, texture, render and so on?


text:
How do I only select vertices which are visible from my perspective in 3D View?
I'm trying to retopologize a high poly mesh and create a low poly version out of the existing sculpt. While selecting some vertices of my low poly mesh in order to edit them, other non-visible vertices are always getting selected automatically, which is tedious to work with:

Q: How do I only select the vertices which are visible from my perspective in 3D View?
Higher Resolution video showing the issue: https://i.sstatic.net/DduJe.jpg

Should work by default, make sure x-ray is turned off: https://blender.stackexchange.com/a/43890/31447 However I also noticed some inconsistent behavior while testing it. If that doesn't work, consider to file a bug report. Good luck. (removed my comments btw)

I was afraid so myself from suspicion because I have tested it on other mesh, and yes, in the clip I toggle xray and wireframe but I know it happens in a shorter time span :) Thanks for the help sir it is a shame of this glitch luckily I am trained to hide and unhide mesh with custom hotkeys lol.

Updated: The issue still happens, less often but it still happens.
I was able to solve the issue by changing the "display as" "wire" to "textured" under the view-port display under object properties.


text:
How to snap the 3d cursor to a specific vertex?
I need to snap the 3D cursor to a specific vertex based on it's ID (to create an empty at that location) and I'm having trouble finding a simple way to achieve that.
Anyone got some pointers?

What do you mean by "ID"? Is it a scripting/Python question?

Yes. I need to select a vertex based on it's index, and snap the 3D cursor to it in order to create an empty at the given location (I need to repeat it several times, hence the need for python)

Related https://blender.stackexchange.com/questions/6155/how-to-convert-coordinates-from-vertex-to-world-space

I think you want to move the 3D cursor in order to use bpy.ops to create the empties.
You should avoid using it because it involves updates at each usage and is slow.
In your case you can use directly objects data.
The code is commented below but ask in comments if anything is not clear:
import bpy
import bmesh

def empties_from_indices( context, obj, vertex_indices ):
    #Get the current collection
    collection = context.collection
    #Access to obj vertices
    vertices = obj.data.vertices
    #Get its world matrix
    matrix = obj.matrix_world
    #Loop over indices to get vertex locations
    for location in [vertices[index].co for index in vertex_indices]:
        #Create an empty
        empty = bpy.data.objects.new("empty", None)
        #Set its location converted in world space
        empty.location = matrix @ location
        #Add it to the current collection
        collection.objects.link(empty)

#Get current context and object
context = bpy.context
obj = context.object

vertex_indices = [1, 4, 6]

empties_from_indices( context, obj, vertex_indices )

If you need to access vertex location when the object is deformed by a modifier or has an armature for instance, you can use the following (same principle, only the way vertices are accessed changes):
import bpy
import bmesh

def empties_from_indices_with_deform( context, obj, vertex_indices ):
    #Get the current collection
    collection = context.collection
    #Access to obj vertices
    dg = context.evaluated_depsgraph_get() #Get the dependency graph
    bm = bmesh.new() #Create a bmesh
    bm.from_object(obj, dg) #Get object data
    bm.verts.ensure_lookup_table() #So that can access verts with indices
    vertices = bm.verts
    #Get its world matrix
    matrix = obj.matrix_world
    #Loop over indices to get vertex locations
    for location in [vertices[index].co for index in vertex_indices]:
        #Create an empty
        empty = bpy.data.objects.new("empty", None)
        #Set its location converted in world space
        empty.location = matrix @ location
        #Add it to the current collection
        collection.objects.link(empty)

#Get current context and object
context = bpy.context
obj = context.object

vertex_indices = [1, 4, 6]

empties_from_indices_with_deform( context, obj, vertex_indices )

Thank you, I was hoping I could avoid using the 3D cursor. This is way more elegant! Appreciate it.


text:
How to model an air mattress?
I am planning to design this air mattress. Here is the picture that I want to model:

First thing that I was thinking was creating this individual cell (the puffy cell unit) from the mattress.
This is where I met an obstacle. My thought process tells me to start with a cube and refine it. It didn't quite work out and I used circle but couldn't process it to look like a cell. I am stuck for several hours. Is there a good tips or resources to come up with the cell design?

Some good ideas: Model upholstery with buttons?

You could begin this way:

Create a plane, rotate it 45° on the Z axis, cut 2 obliques:

Bevel, extrude up, delete the bottom, mirror, extrude the joints:

Give it an Array modifier on the X axis, enable its Merge option:

Give it a second Array so that it duplicates the row on the Y axis:

And then a third Array, on the Y axis again, that duplicates the first two rows:

Give it a Subdivision Surface modifier, play with the Array modifiers > Merge > Distance value so that the vertices stick to each others...

Neatly done.. a lot from a little .. I wonder what happens if you cloth and inflate.. I'll try when I get a chance :)

not sure what you mean by "if you cloth and inflate" but I look forwards to seeing what you'll do  ;)  do you mean it is supposed to be animated?

if you want to simulate a cloth physics for the whole thing, give it a Surface Deform modifier and give the surface a cloth physics


text:
how to fix the problem i blender when it cannot assign weights
I have been trying to assign bones to my mesh, and Blender keeps giving an error that it cannot assign weights to my design. Why is this so, and how can I fix it? I am using the option with automatic weights, yet the heat is not showing in any area of the mesh.

U may have more than one armature,ie
Any new finger bones added newly from object mode,also check whether the naming both right and left sides are evenly matched


text:
Rendering a composite: different behavior of a script on command line and in UI
A baffling (to me at least) Blender behavior. Here is a pared down version of my compositing setup (A).

In Compositor, shadow of a sphere from one layer is combined in Alpha Over with cube from another, and piped into a file. The whole thing is scripted. Running the code from the command line (in Blender's batch mode) gives me an image of a cube, without the shadow (B).
If, however, I read the script into Blender GUI, run the script, and then re-render with F12 (Info Editor, Render -> Render Image), I get both the cube and the mixed in shadow (C), which is what I am trying to get. Edit: for this last to work, a Node Editor has to be open, and in compositing mode.
According to the mouseover description, F12, should be the same as the last line in the script:
bpy.ops.render.render(use_viewport=True)
I suspect that GUI is adding something to the setup but I have not been able to figure out what. Any suggestion welcome.
I am using Blender 2.75 and  here is the code, if it helps any:

#!bpy
"""
"""

import bpy
from math import radians
import fnmatch
import os

###################################
def delete_old_stuff():

    # escape edit mode
    if bpy.ops.object.mode_set.poll():
        bpy.ops.object.mode_set(mode='OBJECT')
    # delete all mesh objects
    bpy.ops.object.select_by_type(type='MESH')
    bpy.ops.object.delete()

    # delete all lamps
    bpy.ops.object.select_by_type(type='LAMP')
    bpy.ops.object.delete()

#####################################################################
def set_camera(scene):
    # Set camera rotation in euler angles
    scene.camera.rotation_mode = 'XYZ'
    scene.camera.rotation_euler[0] = radians(20)
    scene.camera.rotation_euler[1] = radians(3)
    scene.camera.rotation_euler[2] = 0.0

    # Set camera translation
    scene.camera.location.x =  0.34
    scene.camera.location.y = -1.2
    scene.camera.location.z =  6.7

#####################################################################
def set_lights(scene):
    # ambient
    scene.world.light_settings.use_ambient_occlusion = True
    scene.world.light_settings.distance = 2
    # spotlight - sun
    bpy.ops.object.lamp_add(type='SUN', location=(-2.0, 0.32, 6.5), rotation=(radians(-21), radians(-5), radians(69)))
    lamp = bpy.context.object
    lamp.data.node_tree.nodes['Emission'].inputs['Strength'].default_value= 5.0
    lamp.data.node_tree.nodes['Emission'].inputs['Color'].default_value= (0.43, 0.78,1.0,1.0)
    lamp.cycles_visibility.shadow = False

#####################################################################
def create_objects():
    # it looks like the thing uses the last layer definition seen, not the default one
    bpy.ops.mesh.primitive_cube_add(location=(0.0, 0.0, 0.0), layers=[l==0 for l in range(20)])
    cube = bpy.context.object
    cube.name = "cube"
    cube.data.materials.append (bpy.data.materials.new('Plain Diffuse'))
    cube.active_material.diffuse_color = (0.0665019, 0.0302079, 0.8)

    bpy.ops.mesh.primitive_uv_sphere_add(location=(0.0, 3.0, 0.0), layers=[l==0 for l in range(20)])
    sphere = bpy.context.object
    sphere.name = "sphere"
    sphere.data.materials.append (bpy.data.materials.new('Plain Diffuse'))
    sphere.active_material.diffuse_color = (0.8, 0.0344425, 0.0344425)

    return [cube, sphere]

#####################################################################
def compositing(scene, outdir, outfile_base_name):

    # let's try to work in some layers
    render_layers = scene.render.layers
    render_layers.active.name = "main"
    render_layers.new("sphere")
    render_layers["main"].layers   = [l==0 for l in range(20)]
    render_layers["sphere"].layers = [l==1 for l in range(20)]
    render_layers["sphere"].use_pass_shadow = True

    scene.layers[0] = True
    scene.layers[1] = True

    # switch on nodes and get tree reference
    scene.use_nodes = True
    tree = scene.node_tree

    # the default nodes are Composite and RenderLayers, that contains our main layer already
    # --> remove them if I am going to run this script repeatedly
    for node in tree.nodes:
         tree.nodes.remove(node)

    links = tree.links

    main_layer_node = tree.nodes.new('CompositorNodeRLayers')
    main_layer_node.layer    = "main"
    main_layer_node.location =  0, -200

    sphere_layer_node = tree.nodes.new('CompositorNodeRLayers')
    sphere_layer_node.layer = "sphere"
    sphere_layer_node.location = -400, 200

    alpha_over_node = tree.nodes.new('CompositorNodeAlphaOver')
    alpha_over_node.location = 200, 0
    links.new(main_layer_node.outputs['Image'], alpha_over_node.inputs[2])
    links.new(sphere_layer_node.outputs['Shadow'], alpha_over_node.inputs[1])

    # create output node
    out_node = tree.nodes.new('CompositorNodeOutputFile')
    out_node.base_path = outdir
    out_node.file_slots[0].path = outfile_base_name
    out_node.location = 400,0
    links.new(alpha_over_node.outputs['Image'], out_node.inputs[0])

###################################
if __name__ == '__main__':

    delete_old_stuff()
    scene = bpy.context.scene
    scene.render.engine="CYCLES"

    set_camera(scene)
    set_lights(scene)

    [cube, sphere] = create_objects()

    #move the sphere to the second layer (index==1)
    sphere.layers = [l==1 for l in range(20)]

    # do some compositing in which we bring the two layers together again:
    compositing(scene, os.getcwd(), "test")

    # rendering
    scene.render.resolution_y = 1024
    scene.render.resolution_x =  512
    scene.cycles.film_transparent = True

    # not working:
    bpy.ops.render.render(use_viewport=True)

Not sure, but could it be the 'know design limitation' discussed here, in  Blender developer forum ...?


text:
Blender's Nearest Equivalent to Cinema 4D's Collision Deformer?
What's Blender's best, simplest, and most direct equivalent to Cinema 4D's (now 3+ years old) Collision Deformer?
I'm looking for a simple and fast way to have objects deforming other objects like they were outside or the inside of them like Cinema 4D's Collision Deformer can do except I'd like to use Blender or an add-on for it instead. I've looked into Blender's soft-body physics, but I'm hoping there's a more direct equivalent to Cinema 4D's Collision Deformer than that.

Blender doesn't have exactly this. You can use a Softbody or Cloth modifier to achieve the same and set a Collision under physics for other objects. It has to be simulated and baked though, doesn't work interactively like Cinema4D's does.

I was afraid of that. I guess maybe I should request it as a feature then. It seems like the kind of thing that could make life a lot easier in the right situations. I just wish I knew the best way to request it.

You might be looking for dynamic painting with displacements.

Care to elaborate, @someonewithpc? :)


text:
Blender operator redo fails because of poll
I'm writing a Blender addon, and there's a certain Operator that I'm having problems with (let's call it SquashOperator).
Now SquashOperator can only be applied to objects once, in the sense that it
is impossible to squash objects that are already squashed (the precise meaning of squash is irrelevant).
In particular, the SquashOperator marks the object as squashed, and SquashOperator.poll returns False if the active object is squashed.
The SquashOperator has an option (implemented as an IntProperty), and I would like to give the user the possibility of adjusting this option using operator redo, the same way that you can adjust the radius of a sphere that was newly inserted. (Let's say that you can squash horizontally or vertically, and that I want the user to be able to change the squash direction.)
However, once SquashOperator is executed, its options can no longer be adjusted, because now poll return False. This effectively renders operator redo impossible (even though it makes perfect sense for the user to squash something, notice that they squased it horizontally, change their mind, and want to select vertical instead).

Can operator redo be implemented for Operators whose poll function returns False for objects that they have already operated on?


text:
How does scaling work in Blender, *exactly*?
Transformation matrices in Blender (skip if you want)
Transformation matrices in Blender are by design limited to a certain type of 4x4-matrix that is less general than just any old invertible matrix. For example, shear operations are not possible.  Blender's transformation matrices are precisely the matrices that satisfy the following conditions, I think:

The first three columns are mutually perpendicular and end in a 0.
The last column is of the form (a,b,c,1) where (a,b,c) represents a translation.

(I'm using the convention that a transformation matrix M is applied to column vectors v as M*v, as is usual in mathematics.)

My question
Suppose that M is the transformation matrix of a Blender object (and therefore satisfied the conditions above). I now apply a scaling of factor 3 along the global x-axis. How is the resulting transformation matrix calculated?
One would naively expect that the first row of M just gets multiplied by 3. (As opposed to scaling by 3 along the local x-axis, in which case the first column of M gets multiplied by 3.) But this is not what happens, as the resulting matrix would not satisfy the first condition above anymore.
Instead, all of the columns of M get rescaled in some way.

How is the transformation matrix of an object changed when I scale along the global x-axis?

An illustration
Start with the default cube. Rotate it by 30 degrees along the y-axis (ry30Enter).
Now rescale by 3 in the x-direction (sx3Enter). The object gets rescaled by 2.646 in its local x-direction and by 1.732 in the local z-direction. Where do these numbers come from? (They seem to equal sqrt(7) and sqrt(3), respectively. So their squares sum to 1+3^2, which is probably relevant.)

Observations (added)
If we rescale along a global axis by a factor x, and this results in rescaling along the local axes by factors (a,b,c), then we always have a^2+b^2+c^2 = x^2+1^2+1^2.
Also, rescaling along global x by 3 twice is not the same thing as rescaling along global x by 9.

Note: I don't need an explanation of the mathematics behind transformations, matrices or quaternions. I'm familiar with those.

I'm personally ignorant to dealing with these transformations at a matrix level, however I did have a thought here. Have you tried applying the scale and rotation 1st, and then looking at the matrix again to see if it was what you would expect? Just curious.

@RickRiggs - Applying the scaling first and then rotating is the same as first rotating and then scaling along the local x-axis (by hitting x twice), as one would expect. But I'm not sure how exactly the numbers 2.646 and 1.732 are calculated.

As another illustration, start from the default cube. Rotate it by 45 degrees about the y-axis. Now scaling along the global x-axis is the same as scaling along the global z-axis (!).

Maybe we are still talking two different things, and I want to make sure we are not. When I say "apply" I mean (with your mesh of focus selected) Ctrl+A >> Rotation & Scale. It sounds like maybe you were thinking "apply" means entering your rotation and scale values to the matrix directly. If this is the case, take my definition of it into account, and check your mesh matrix again to see if you get your expected values.

@RickRiggs - Oh, sorry, I didn't get what you meant. In any case, applying (ctrl+a) the rotation and scale just applies the object's transformation to the mesh data and resets the object's transformation to the identity. This is what I would expect. But it doesn't answer the question, unfortunately.

Darn, at least we ruled that one out.

I suspected the scaling vector (ie world X axis) is divided into the local X, Y, Z components by projecting onto them and each of the object's scale is multiplied by the respective components but I'm yet to try this theory and make it into an answer post. The algebraic formulas themselves are probably too complex for me, I'm not too good with vector math but at least I would like to demonstrate it graphically.

@kheetor - Yes, it might be something like that. I'll play around with it a little to check whether it's true.

An indication seems to be that 1.732^2 + 2.646^2 = 1 + 3^2.

http://blender.stackexchange.com/questions/28778/hexagon-is-distorting-on-x-axis-when-scaling-on-y-globally/28783#28783

@Chebhou - Thanks! That is indeed the same phenomenon. Would you happen to know how it works quantitatively, though?

I wondered the same, and when I saw that there was no answer here, I looked it up in the source. Dealing with signs is complicated, but without considering signs, the method is as follows. The sources work with 3x3 matrices (position doesn't influence scale), so I'll do the same here.
Let $S$ be the original scaling matrix, and $R$ be the original rotation matrix. Now, to scale by a new matrix $N$, calculate $A = S\times R\times N$ and obtain the new sizes on each axis by calculating the Euclidean norm of each row of $A$.
In your case:

Suppose that M is the transformation matrix of a Blender object (and therefore satisfied the conditions above). I now apply a scaling of factor 3 along the global x-axis. How is the resulting transformation matrix calculated?

Take the $3\times 3$ matrix $M' = S\times R$ by discarding the last row and column of $M$, then obtain $A = M'\times\left[\begin{matrix}3 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1\end{matrix}\right]$. Now, the new X scale is $\sqrt{a_{11}^2 + a_{12}^2 + a_{13}^2}$, the new Y scale is $\sqrt{a_{21}^2 + a_{22}^2 + a_{23}^2}$, and the new Z scale is $\sqrt{a_{31}^2 + a_{32}^2 + a_{33}^2}$. Use these as the elements of the diagonal of the new scaling matrix, $S'$. The new $3\times3$ matrix is obtained as $S'\times R$ and the $4\times4$ matrix by adding back the last row and column of the original $4\times4$ matrix.
For your example:

Start with the default cube. Rotate it by 30 degrees along the y-axis (ry30Enter). Now rescale by 3 in the x-direction (sx3Enter).

we have $S = I$ (no scaling on the cube to start with), $R = \left[\begin{matrix}\cos 30°&0&\sin 30°\\0&1&0\\-\sin 30°&0&\cos 30°\end{matrix}\right] = \left[\begin{matrix}\sqrt3/2&0&1/2\\0&1&0\\-1/2&0&\sqrt3/2\end{matrix}\right]$ and $N = \left[\begin{matrix}3 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1\end{matrix}\right]$. Now $A = S\times R\times N = \left[\begin{matrix}3\sqrt3/2&0&1/2\\0&1&0\\-3/2&0&\sqrt3/2\end{matrix}\right]$ so the new scale on X is $\sqrt{(3\sqrt3/2)^2+(1/2)^2} = \sqrt7\approx 2.646$, on Y is 1, and on Z is $\sqrt{(-3/2)^2+(\sqrt3/2)^2} = \sqrt3\approx 1.732$.
The code can be found in source/blender/editors/transform/transform.c in function ElementResize(). Function TransMat3ToSize() extracts the norm of each row and deals with signs.

I hope to see more of your questions and answers in near future.

If you wish to scale along the normals after rotating, simply hit 'x' twice, then enter 3.  This will provide you with the dimensions you are looking for/expecting.
In a simple way, think about how the X values of the rotated box are actually smaller than 1 if you apply the 30 degree rotation first.  Then once you include the fractions for sine and cosine (M) for the rotation around an origin, the value of X will be even smaller than the simple multiplication by 3.  The numbers you are seeing above are correct.  But they are the result of a certain order of operations.  Use the correct order of operations or scale on the normals for the expected results.
If you search for "scale rotate translate", you'll find videos and articles about this for game programmers.
Updated with calculations because my initial answers were vague:
The Z scale is the result of the 30 degree rotation multiplied by 2:
>>> (sqrt(3)/2) * 2
1.7320508075688772

The X scale is the result of 1) the ratio of the scale to 3:
>>> 2.6459962836960553/3
0.8819987612320185

and 2) the ratio multiplied by sqrt(3)/2 to compensate for the ability to calculate the radius of the increase on the X axis, like so:
>>> (2.6459962836960553/3) * (sqrt(3)/2)
0.7638333333333335

Now with the scale ratio included into the 30 degree calculation, you can see the resulting X value of a vertice on the long end of the scaled and rotated cube:
>>> 3 * ((2.6459962836960553/3) * (sqrt(3)/2))
2.2915000000000005

Which from the other side, means that the scaling factor for X can be arrived at this way:
>>> 0.7638333333333335 * 3
2.2915000000000005
>>> (0.7638333333333335 * 3)/(sqrt(3)/2)
2.6459962836960558

Also, if you are curious about calculating the X and Z values, don't forget to calculate the length from the origin point to the corner of the cube before scaling or rotating.
>>> sqrt((1**2)+(1**2))
1.4142135623730951

Yes, I know that hitting x twice will rotate around the local x-axis. This is not what I'm asking about. You write 'use ... for the expected results'. But I didn't expect it to scale along the local x-axis. I just want to know how the numbers 2.646 and 1.732 are calculated.

I attempted to point you in the right direction in paragraphs 2 & 3.

Here's the crux.  once you rotate the cube, prior to scaling, you expose the Z axis to further scaling as well, because your vertices(which are really the numbers you should be referencing rather than scale factor) are what are actually getting modified.  You might think of the changes to Z as sharing a ratio of requested changes to X.  This is why the scale factor for both gets changed, where X is not quite 3 and Z is slightly modified.

I don't think we understand each other. I'm looking for a formula to calculate the numbers 2.646 and 1.732. How is the 'sharing' of the ratio (as you call it) calculated?

Also, the vertex data (the data that is stored inside the mesh) has nothing to do with my question. I'm just talking about transformation matrices. The question applies equally well to empties.

Well, if nothing else 2.646 and 1.732 are simply the distance from the origin to the faces along their respective origins.  If you apply a -30 degree rotation and go into edit mode, you'll see the verts (global under 'n') match up.  Getting the calculation may involve some trig where 15/30/60 degree offsets affect the scales.

Yes, 2.646 and 1.732 are those distances, by definition. You write '... may involve some trig...'. It's the trig I'm looking for.

Please see my amended answer for calculations.

Does that help?  Or have you solved this to your satisfaction?

I follow your calculations, but I don't see how they explain where the numbers come from. Why sqrt(3)/2*2 for the z-scale? For the x-scale: sure, you can calculate the 2.646 from the 0.7638. But where does the 0.7638 come from? (The only answer I see is 'from the 2.646'...)

(Btw, I think you meant sqrt(3) instead of sqrt(2) right at the end. But this is unimportant. I'm not interested in coordinates of vertices.)

sqrt(3)/2 is how Cosine is is calculated for 30°.  You can find a set of common values from the unit-circle: https://en.wikipedia.org/wiki/Unit_circle.  In this case it's how X values are calculated as they rotate around the origin point(X values were focused on as they gave us the most unpredictable value which was ~2.646).  The scale that you are trying to discover is based on the movement of vertices.  So ignoring vertices will ultimately be impossible.

I'll leave the matter alone with this... if you look up matrix math for rotations, you'll find that sine and cosine values are distributed across axis values to perform the rotations.  Scale calculations are more simple, being simply a multiplication across the matrices as you mentioned in your question.

But the reason that this particular scaling wasn't simply multiplication by an axis value in this case, is because the geometry's vertices had multiplication of cosine and sine applied prior to the scale, making the geometry along the axes uneven thus producing a ratio of the scaled axis by 30° (sqrt(3)/2),1/2).

sqrt(2) is so that you find the distance from the origin point to the corner of a 2x2 cube.  That gives you your starting X,Z values prior to rotation, then scaling.  --not a typo

I still don't think you have answered the question. Let's not fill the page with a discussion in the comments, but instead talk in chat: http://chat.stackexchange.com/rooms/39303/how-does-scaling-workin-blender-exactly

From what I can tell (I was able to get one of your stated values 1.732) the numbers being stored in the matrix to the local X is a projection value to it's local mid-point in world space as seen in the screenshot below. As for your scale value I would hope that would be the 2.732 value instead of your stated illustration value of 2.646, so on that one I'm at a loss.

@kheetor - Sorry, I just saw that there were hidden comments to this post, and you had the same idea. I will gladly withdraw my answer if you post it.

Aha, at least we have the value 1.732 showing up somewhere! I'll play around a bit with this idea to see whether I can explain both numbers (the 2.646 is correct).

authors: Анна Осипова


text:
How can I determine the coordinations of the deepest point of a pit located on a 3D object?
I am trying to find the deepest point of a rough pit located on a rough 3d object. The pit is full of irregular vertices.

https://drive.google.com/open?id=1muCjhRDHhwo3AnY194BAvkaCpPIdyWhx
I cannot determine which one of them is the lowest. Could you please help me?
Thanks!

Can you give us a screenshot of the pit? Can't you just go into front view, and wireframe mode and see which vertex is the lowest?

Thank you @Leander
I can go into front view and see vertices as seen in the screenshot below however I am trying to find the exact lowest point of the surface. I am going to make measurements regarding this point for my scientific article so I need to be very precise.
https://drive.google.com/open?id=1muCjhRDHhwo3AnY194BAvkaCpPIdyWhx

Local minima
Calculus is full of finding maxima and minima of equations.  Numerical methods , generally iterative, can be employed to find turning points based from  Newton's Method or Gradient Descent to name a couple.
Turning points occur where the derivative (tangent) is zero.  Inconveniently the mesh isn't defined as an equation.  For every vertex there is a normal, that is perpendicular to the tangent.

Vertex selected in "ding" in icosphere test
As a simple test case, for each vertex:

Create an imaginary plane from coordinate and normal.
For all vertices of neighbouring faces if the distance to plane is greater than or equal to zero then it is "below" all neighbours and considered a local minimum
The test is looking at all neighbouring verts being above, for a really rough mesh this may need to be relaxed slightly.

Simple edit mode test script.
import bpy
import bmesh

from mathutils.geometry import distance_point_to_plane as dp2p
context = bpy.context
context.tool_settings.mesh_select_mode = (True, False, False)
ob = context.edit_object
me = ob.data
bm = bmesh.from_edit_mesh(me)
bm.select_flush(True)

for v in bm.verts:
    # define "vertex" plane
    p_no = v.normal
    p_co = v.co
    # neighbouring verts
    nvs = set(nv for f in v.link_faces for nv in f.verts)
    v.select = all(
            dp2p(nv.co,p_co,p_no) <= 0
            for nv in nvs)

bmesh.update_edit_mesh(me)

Result of reversal of test. dp2p(nv.co,p_co,p_no) <= 0 as a useful way to find concavities
Once a point is selected its local depth (depth from surface) could be calculated (estimated) by selecting out from point until distance from plane stops increasing, and choose the max.
As mentioned this is a very simple test. Once a vicinity is known a more robust method like raycasting could be employed.

Do you tried mesh analysis?
The Sharp analysis:

And Thickness:

Thanks for helping!


text:
Python script help - assign certain materials to some particular objects
First post here. Using Blender 2.8 and learning the basic of scripting. Can someone help me with a assigning certain materials to some particular objects. Any help would be great, many thanks.
import bpy
objects = bpy.data.objects

material_01 = bpy.data.materials['red_material']
material_02 = bpy.data.materials['blue_material']
material_03 = bpy.data.materials['yellow_material']

for obj in objects:
    if 'Object_cube1' in obj.name:
        obj.data.materials[0] = material_01

for obj in objects:
    if 'Object_cube2' in obj.name:
        obj.data.materials[0] = material_02

for obj in objects:
    if 'Object_cube3' in obj.name:
        obj.data.materials[0] = material_03

for obj in objects:
    if 'Object_cube4' in obj.name:
        obj.data.materials[0] = material_01

Using get(name) and startswith(...)
Using the get method of a collection, objects and materials in this case,  if an object doesn't exist with  name it returns None which is boolean false.
Here I've made a helper method, and added a call to add default material "Material" to default cube object "Cube" or any name other starting with it, eg "Cube.001", but not "BigCube"
Taken a punt that you are looking for objects that start with those names, for which startswith is ideal.
import bpy

def assign_mat(ob_name, mat_name):
    mat = bpy.data.materials.get(mat_name)
    obs = [o for o in bpy.data.objects if o.name.startswith(ob_name)]
    for ob in obs:
        if mat:
            ob.data.materials[0] = mat
    return obs and mat

if assign_mat("Cube", "Material"):
    print("assigned Material to Cube[*]")

Recommend something like
pairs = (("Cube", "Material"),
         ("Blob", "BlobMaterial.001"),
         ("Cone", "Material"),
        )

for ob_name, mat_name in pairs:
    assign_mat(ob_name, mat_name)

If nothing is assigned
if not any(assign_mat(ob_name, mat_name) for ob_name, mat_name in pairs):
    print("Assigned Nothing????")

Thank you so much batFINGER, will give this a try.


text:
Addons not appearing when I search for them
I am trying to install a addon that lets me import MMD files but it is not appearing after I press the button "install from file" and select the file.
Here are some pictures of what I do to install it.

As seen above it is nowhere to be found! (sorry for the poor quality pictures)

Have you looked at http://blender.stackexchange.com/questions/39745/addons-only-some-zips-will-install?rq=1  zip addon install will fail if the addon folder is not the root of the zip... which is often the case for github zips.

Voted to close as link above answers this for a generic case.  What you need to do is drop the mmd_tools folder from the zip into one of your addons folders.  It's a toss up when hosting on git to use the root folder as the addon folder as there is the git README.md etc... unfortunately that makes install from zip add a gitrepo_master folder in your addons folder, and the addon folder inside that, which isn't picked up by blender as an addon module.


text:
csv>python>blender>movie ; a little more help to achieve my script
I'd need a little more help to watch and "finish" my script
the aim is to use a csv file (OK)
as coordinates (Done)
use it to create text (OK)
and make an animation (Done)
I'm lost in rendering/exporting the movie (to .avi or .mpeg, nevermind)
Thank you in advance and excuse my poor english !
import bpy
import csv
from math import pi #useful for text and camera rotation_euler
#create material
material_basic = bpy.data.materials.new(name= "Basic")
material_basic.use_nodes = True
principled_node = material_basic.node_tree.nodes.get('Principled BSDF')
principled_node.inputs[17].default_value = (1,1,1,1)

def event_text(event):
    bpy.ops.object.text_add()
    ob = bpy.context.object
    curve = ob.data
    curve.body = "%s"%event
    bpy.context.active_object.location=(float(x),float(y),float(z))
    bpy.context.active_object.rotation_euler=(pi*90/180,0,0)
    bpy.context.active_object.data.materials.append(material_basic)
#define scene
scn = bpy.context.scene
#create the first camera
cam1 = bpy.data.cameras.new("Camera 1")
cam1.lens = 18
#create the first camera object
cam_obj1 = bpy.data.objects.new("Camera 1", cam1)
cam_obj1.rotation_euler = (pi*90/180, 0, 0)
scn.collection.objects.link(cam_obj1)
scn.camera = bpy.context.object

#extract datas from csv file :
file = '\\Users\essai.csv'
#make the loop
with open( file, 'r' ) as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        x, y, z, event = row[0], row[1], row[2], row[3]
        cam_obj1.location = (float(x),float(y)-3,float(z))
        cam_obj1.keyframe_insert(data_path=("location"), frame=((reader.line_num)-1)*120)
        cam_obj1.keyframe_insert(data_path=("location"), frame=((reader.line_num)-1)*120+120)
        print (reader.line_num)
        #creer les blocs textes
        event_text(event)
        #render
bpy.data.scenes.render.filepath = '\\Users\essai\' + str(n_strip)+'.mkv'
bpy.ops.render.render( animation = True, write_still = True )

Did you miss additional ' \ ' inside '\\User\essai\ '? Should be like '\\User\\essai\\'

@HikariTW : worked so far : I managed to export singles pictures ; but not a movie... I will check that

finally got it :

finally got it ; the file type needed to be "AVI_RAW" : code :bpy.context.scene.render.filepath = '\Users\essai'
bpy.context.scene.render.image_settings.file_format = "AVI_RAW"
bpy.ops.render.render(animation = True)


text:
How to set different HDRI for different objects as IBL?
I have multiple objects in the scene and want them to receive different HDRI lighting. To my knowledge, the HDRI environment is a world property. It would affect each object equally. But I would like to ask if there is a solution for objects to receive different HDRI lighting.
My goal is to augment the autonomous driving image data and add objects that do not exist in the original image using blender. This requires me to set different lighting depending on where the object is inserted.
For example, I want to add 2 vehicles to the scene (more than 2 in more cases.). One of them will be in shadow and use a darker HDRI, while another will be out of shadow and use a brighter HDRI. However, currently, I can just use the same HDRI for these two vehicles.

Can someone help me?

HDRI lighting is not a good solution for this case. If you want shadows to affect objects in the scene, you need those shadows in your scene. This means you need to recreate at least rough shapes of the objects and lighting in the environment. It's possible to create lighting with different mesh spheres around different objects and textured emission shaders. You could turn off camera visibility for those spheres, but that will not produce good results and will have a lot of problems. Like what happens at the borders or when objects move between different lighting areas?..

Just add some geometry that will cast that shadow in the place of house visible on hdri.


text:
Material Doesn't catch light shining on it from using a Geometry and Mix Shader node
I created the following node setup to place an image on 1 side of a plane and have the other side white.

The issue is now the material will not catch any light from a lightsource.
The following node setup works but then the image is on both sides of the plane.

Question
How can I use Geometry and a mix shader in my material and have it catch light?

@RobertGützkow I guess I would only want 1 side to be diffused and the side with the image to have specular reflections.

Then you can simply use your first node setup and add a Principled BSDF between the Image Texture node and the Mix Shader. Set the Specular value of the Principled BSDF to control the amount of specular reflection. Does that solve your problem?

@RobertGützkow I have added some render preview images. The 4th image with the stem lights, see how they cast a light onto the image?

The first setup is almost right, you just shouldn't connect the Image Texture directly to the Mix Shader. The green sockets  should be used to connect Shaders. Take the nodes from the second setup (without the Material Output) and connect the output of the Principled BSDF with the Mix Shader.

@RobertGützkow Awesome! Do you want to write that for an answer so I can mark answered?

The first node setup is almost right, except that you're missing a shader between the Image Texture node and the Mix Shader. The green sockets indicate that the input to the Mix Shader should usually be the output of another shader, for instance the Principled BSDF.
Start from the node setup from your first screenshot and add a Principled BSDF. Disconnect the Image Texture node from the Mix Shader.
Connect the:

Color output socket of Image Texture node to the Base Color input socket of the Principled BSDF node
BSDF output socket of the Principled BSDF to the upper Shader input socket of the Mix Shader

Adjust the properties of the Principled BSDF to get the desired look. Specular controls the amount of specular reflections.


text:
How to render an Equirectangular Panoramic image with Eevee
I want to use Eevee to render 360 panoramic images. I do not want to use cycles because of the render time for my project. I tried searching google and this site but the last time this was asked was about 2 years ago: Is it possible to render 180º equirectangular with eevee engine?
My only thought is to create multiple cameras, render each camera and then stitch together in another program. Is there an easier and faster way?

There is this VRRenderer script by EternalTrail that works okay for rendering a stationary camera. However it does not animate and the camera cannot be parented to another empty or object. (Correction - it can render an animated camera or imported camera, please read the update below)
Here's a video explaining how it works.
https://www.youtube.com/watch?v=ND8T5_VCcN0
I have tried installing it as a addon as described in the video but it didn't work for me, what worked is opening the python script directly in the scripting tab in Blender and then running the script. Following that you should be able to see the eeVR tab on the side of the viewport. You have to save the blend file for it to run and also it writes the renders in PNG and into the same folder of the of the blend file. Seams will appear if you turn on AO and bloom in Eevee. Turning on overscan will apparently fix the problem but I have yet to try it.
Guess I'll have to wait for the Blender developers to come out with a dedicated Panoramic renderer for EEVEE. Cycles is good but the render times just take way too long when time is limited.
Update after some experiments.
I have trying to use an imported alembic cache export from Maya and although I can see the camera animated, the VRrender script does not want to render from the camera. As explained earlier, this is a limitation in the script. I tried deleting all the cameras and used a single camera and the script automatically renders to that camera. I tried manually keyframe animating it and the renders correspond to the keyframed animation. Eventually I figured out from other forum posts that I can just duplicate the alembic exported camera, delete its alembic constraint, then apply a transform constraint to follow the alembic constraint camera. Following that I select the duplicated camera, then go to Object => Animation => Bake Action to bake the keyframes into every frame. In the Bake Action options, I turned on only Visual Keying and Clear Parents. My Camera animation had over 2700 frames so it took a while for the keys to be baked. This is the workaround I'll use until the official Panoramic EeVee render is available.