text:
How to avoid grainy renderings in Cycles?
I've read this question and its answers, but they didn't solve my problem, so I am re-asking this question under the context of my setup.

I am rendering some planes under HDRI lighting. These planes' material is a mix of transparent BSDF and diffuse BSDF (with 0 roughness!).
To avoid the grainy renderings (or fireflies, as some other people may call them), I tried the methods mentioned on the internet. Specifically,

Sample number is et to 128
Light paths are set to "full global illumination," where maximum numbers of bounces are all 128 (but this also means caustics are on. Maybe I should try turning them off. Thought they contribute to photorealism, the graininess I current have is unbearable...)
Filter glossy is set to 0.5
world.cycles.sample_as_light set to True, as I read from a article by Andrew Price

Despite all these efforts, the results still look pretty bad. Worse still, I have those weird white dots that seem like missing pixels...

Is this completely hopeless? What else can I attempt?

Sample number is set to 128

Unless you have the "square samples" option enabled (which turns it into 128^2 samples, aka 16384 samples), 128 is not high at all. Set it higher.

Light paths are set to "full global illumination," where maximum numbers of bounces are all 128 (but this also means caustics are on. Maybe I should try turning them off. Thought they contribute to photorealism, the graininess I current have is unbearable...)

I'd advise never using the Full GI setting unless you specifically want to wait around for awhile to get every last lighting detail. The benefit of extra diffuse bounces drops of FAST after 2-4. Glossy and transmission often need more to avoid dark reflections/refractions, but 128 is overkill. Try 4-6 for glossy and 10-16 for transmission.

Filter glossy is set to 0.5

Try 5.0. 0.5 is barely enough to even do anything.

world.cycles.sample_as_light set to True, as I read from a article by Andrew Price

Do you know what that setting actually does? If not, give this a read: What is multiple importance sample option While that option is usually the right call for scenes with HDRIs, you should understand WHY you are enabling options, not just flipping them on because the tutorial said to.

Generally, here's my steps for cutting down render time and noise, in order of increasing desperation:

Turn on filter glossy
Disable refractive caustics
Turn off diffuse visiblity on mesh lights, add a lamp object to cover the missing lamp.
Lower diffuse bounces
Disable reflective caustics (they're generally softer than refraction caustics, so less noise and more contribution)
Turn on clamp indirect. Remember that it clamps sample values and not final pixel colors. Mind what white point you're using if you have enabled exposure options, post-processing, the filmic-blender LUT kit, etc.
Turn on clamp direct (absolute last resort, avoid this setting if you can).

Can you go into more detail about "Turn off diffuse visiblity on mesh lights, add a lamp object to cover the missing lamp."? I never heard about this trick. How do you do it?

I'm not sure whether cegaton's answer comment was meant as an answer to my question, but in the linked answer and comments I see nothing about "Turn off diffuse visiblity on mesh lights, add a lamp object to cover the missing lamp.". My best guess is to uncheck diffuse ray visibility on a mesh with emissive material, and add a lamp which has only diffuse ray visibility.

@WannaKnow He basically meant that mesh lights being area light behave in a way that introduces noise to the scene. So by turning off diffuse visibility exclude it from lighting emission calculation. But which means there is no more light emission but the mesh will still look bright white. Hence to complete the illusion, you will need to create a light object to "fake" those missing emission you just turned off.

In my personal experienced with cycles ...
Because of the law of conservation of energy in the real world, light hitting a surface should never reflect more energy than what was initially available from the source. Some energy should have been diffused in other direction or lost during the interactions with surrounding environment and/or objects.
Fireflies or bright white speckles is a sign that law of conservation of energy has not been accurately observed within the engine's calculation. Hence the white speckles are light sources reflecting a greater amount of energy when compared to the initial input. So imagine 1 Lux of light is now 2 Lux after reflecting off the surface of the object... this is definitely a problem and noise can be introduced easily ... imagine the light source gets to bounce around and it becomes stronger every bounce and create inaccurate solutions.
The really effective solution is to hinder this scenario from happening.

Use Clamp indirect. Make sure that the indirect light can only get up to a certain intensity helps. Starts with 4.0 and Lower the number until the noises disappear. This would usually solve most of the noise issues.
Using light portals to direct light sources into hard to reach area. Engine's are not smart enough to know where to aim all the samples towards a certain critical area of your model. If your model has a lot of surfaces overlapping and light exposure are not direct, it would often help to add some light portals to focus on those areas where samples may have missed them and noise were inevitably introduced. This is often true for an interior scene with a small window opening.


text:
How can I make my hair curves less GPU intensive?

Sort of new to geometry nodes. I made this setup and it works well but the GPU runs high, I'm guessing because I don't have interpolate hair and instead use Duplicate Hair? Can't figure out how to fit it into my node tree.

source: Stack Exchange

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

sort: votes


text:
Copying fur groom to another character?
I made a character and used Quick Fur to add fur, then I used the sculpt window to groom the fur and make some hairs longer than others. Now I want to copy the hair exactly as it is to a new identical character. Copying modifiers worked but I can't find a way to copy the sculpt, is it possible?

you can copy the curves with Geometry Nodes. Just output the geometry of the source curves. Then apply to modifier to the (target) curves object. After that, you need to attach the curves to the surface (Sculpt mode, menu Curves > Snap to Nearest Surface). If the models are very different it will hopefully look similar but it won't look 100% identical.

Thanks! novice here, how do I output the geometry of the source curve? are there any video tutorials for this?

Oh, I forgot one step. You have to deal with the modifiers or they will be copied as applied. I will post an example...

You can copy the curves with a Geometry Nodes modifier. Here is an example:

the cube got a Curves > Fur added. It's same as Quick Effects > Fur
while Suzanne the monkey head has an Curves > Empty Hair object.
both models require a UV map with no overlapping UV islands

To copy the hair curves:

select the source curves object
and disable all modifiers in the viewport so we can copy the unmodified original curves

select the target curves object

add a new Geometry Nodes modifier to Suzsanne's Curves (target)

the Geometry Nodes modifier just outputs the geometry of the source curves with an Object Info node. You can drag and drop the Cube's Curves from the outliner into the node editor. Blender then creates the node for you.

note that the Geometry Nodes modifier Surface Deform now displays an error message. We'll fix this soon.

apply the Geometry Nodes modifier to make the copy permanent by using the modifier's dropdown menu > Apply, or by pressing Ctrl+A while the mouse pointer hovers the modifier.

now we need to attach the curves to the surface. This is done in Sculpt mode
select the menu item Curves > Snap to Nearest Surface to attach the curves to the model
the error of the Surface Deform GN modifier should be gone now

finally, enable the modifiers of the Cube's Curves again, copy them (Ctrl+L in Object mode) and make sure the settings in the target curves object are correct (Surface object and UV Map).

The hair style will not look 100% identical, but similar, depending on how similar the models are. For comparision, I've added a cylinder.

Thank you so much!

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


text:
Dilating baked (BW) texture
I have an object with black/white (binary) baked textures, and I want to dilate the white regions by some amount. The islands on the uv map are offset by a margin. I have tried a few things, without any success.
A simple example would be a black cube with a white dot in the middle of one face. I want the dot to spreas in all directions and eventually expand over the edges to other faces. In my actual case, there can be multiple white irregular regions.
I have understood from previous questions that it is difficult to do this in shader nodes, especially since I dont want to modify my geometry or subdivide.
Doing this in 2d using the baked texture and morphological dilation is one option, but its not trivial because of disconnected UV Islands. I would somehow need to dilate over UV boundaries, using information about joint edges. I feel there should exist a  algorithm for this, but I cannot find anything online. In a way this option is preferable as it would offer the most control.
Another option would be to use the spread feature in dynamic paint. This would achieve the desired outcome, but the problem is that I dont really have a brush. It does not seem to be possible to assign my baked texture as an initial (wet) paint and let it be affected by the spread effect available under the canvas options.
I have also seen people achive spreading or dripping effects with geometry nodes, but I dont know how to use my texture as initial condition.


text:
How to get warning details when importing FBX with a script?
I'm trying to get the warnings details of an import FBX (like missing textures...)
I'm using this method :
bpy.ops.import_scene.fbx(filepath=input_fbx_path)
I can see the results I want in the info pannel of Blender, but I can't make a script that copy those infos and put them in a file. Is that even possible ?
I successfully got the screen area and space, but then, what can I do to automatically copy this ?
Or am I going the wrong way and is there a much simpler method to get those warnings log into a file ?

You should have a look at the fbx importer's code. That's what makes the the warnings, so that will probably answer your question. It's a lot of code there... I am not sure you will find many people here who will be happy to do that job for you... But maybe I am wrong...


text:
VR Rendering Issues
I am trying to Render a VR Video to use with a VR-Headset, but I always have a kind of Border in my video (picture at the very Buttom).
For Rendering, I render each Frame as a PNG-File seperately and I am using following Settings for the Camera:

For the Image Output Settings i use following Settings:

For Rendering Settings i use Cycles and GPU computation.
I Render all Frames as PNG Images side-by-side and after this I use the image sequencer to create the video as an  MPEG-4 with H.264 codec.
I tried everything but I still have this annoying border in my Video...
Can you please help me?
Render Settings for Video Output:

Hello and welcome. Please use a title that matches the content of the post. It should read like a question, be descriptive but succinct, unique and identifying, summarizing the problem so that anyone searching for similar issues is likely to find this. Remove anything superfluous, avoid using words like "this", "help with", "issue" or "question about", instead describe what "it" is. Remember, your title is the first thing visitors see, answers you get depend heavily on it. See What is the problem of asking “How do I do this?"


text:
Projection of point on plane
I have a point in 3d view (found out with region_2d_to_origin_3d of mouse position). I want to find its projection on a plane defined by a normal (x1, y1, z1) in orthographic view. How to do this?

Edit: Attaching a sample blend file with the script I am trying to run. If you run the modal operator from the perspective view and move the mouse pointer, the Bezier line always lies on the plane (which is the desired functionality). But the same operator from orthographic view does not produce any movement.

Elements to do that here https://blender.stackexchange.com/questions/150267/how-to-move-object-while-tracking-to-mouse-cursor-with-a-modal-operator/150314#150314

@lemon Thank you! I don't have a plane object, just the points on plane, so I am using geometry.intersect_ray_tri and giving it three points on the plane. The problem is finding the start and end of the ray. Using view_matrix gives correct results in perspective view but not in orthographic view. So I thought of exploring the mathematical route.

region_2d_to_origin_3d is the origin of the view. region_2d_to_location_3d gives the mouse 3D pos from mouse pos. So you have things in order to ray cast. Both are available in ortho. But maybe I've not understood the issue?

@lemon Yes, I am just looking for what you have given in the example. And the script given by you works for both perspective & orthographic views. The only change needed is I don't have the 'Plane' object (and creating a temp object is not desirable). I just have 3 non-linear points defining the plane and I want to orient the cube along the normal of this plane in orthographic view.

Well, intersect_ray_tri should work. Or you need something around that?

@lemon It does not work in orthographic view. Maybe I am missing something.

Could you upload you file so that we could have a better understanding of what is happening? Please use this link to do it https://blend-exchange.giantcowfilms.com/

@lemon Thanks for your interest. I have attached a blend file with the script. The structure is the same as in the blend file from the thread: https://blender.stackexchange.com/questions/150267/how-to-move-object-while-tracking-to-mouse-cursor-with-a-modal-operator/150314#150314

You can do it this way

@lemon Thank you so much. That was perfect! This single solution works for both the views :) Maybe you want to put this as the answer, so others who are looking for something similar would also know the solution. Thanks a ton once again!!

Done, a bit simplified

The code can be the following.
We principally need the view vector (axis from the camera) and the view point (cam/eye position) which are given by view3d_utils.region_2d_to_vector_3d and view3d_utils.region_2d_to_origin_3d.
Then we cast on the plane coordinates in two parts as the plane is two tris.
    # Get mouse position
    mouse_pos = event.mouse_region_x, event.mouse_region_y

    # Get object and region 3D
    object = context.object
    region = context.region
    region3D = context.space_data.region_3d

    # The target plane in order to have coordinates
    plane = bpy.data.objects.get('Plane')

    # All Transforms applied, so global space coordinates
    # (Plane is used just to get the points, in actual situation only
    # points will be available)
    p1 = plane.data.vertices[0].co
    p2 = plane.data.vertices[1].co
    p3 = plane.data.vertices[2].co
    p4 = plane.data.vertices[3].co

    # View vector (view axis) from the mouse pos
    view_vector = view3d_utils.region_2d_to_vector_3d(region, region3D, mouse_pos)
    # View point (eye position) in 3D
    view_point = view3d_utils.region_2d_to_origin_3d(region, region3D, mouse_pos)

    # Cast on plane defined by points above (2 counterclockwise tris)
    loc = geometry.intersect_ray_tri(p1, p2, p3, view_vector, view_point, True)
    if not loc:
        loc = geometry.intersect_ray_tri(p2, p4, p3, view_vector, view_point, True)

Note: have left the plane coordinates part as it was, but can also use the plane world matrix to translate coordinates to world.


text:
Cycles causing visible triangulated wireframe over mesh?
I can't seem to solve this issue (see render)

As you can see, there's a faint wireframe being rendered on top of my mesh. Occurs in cycles viewport and render. Any tips on how to solve other than starting fresh? There are no wireframe modifiers present anywhere in my scene. even adding a fresh Suzanne Monkey to the project seems to reflect the same issue:

Maybe try the solution in the comments here: https://blender.stackexchange.com/questions/252912/wireframe-artifact-shows-up-when-rendering-close-up-detail-in-blender-3-0 (Switch Subsurface Scattering to "Random Walk" and keep it below .4)

Hmm.. There's no subsurface scattering anywhere in my scene.

You might wanna share your file so people can take a look then. Just the Suzanne, for ex. You can use https://blend-exchange.com/

copy that, just added the file. The artifacts seem to be very lighting dependent - for me they're very visible under the "moonlit golf" preset hdri

It seems to be caused by your model's distance to the origin. Too much disparity between your model's smallest and biggest dimensions can engender all kinds of rendering issues, from clipping, to Z-fighting, to... this:

aha! thanks for the info.

I have a similar problem, wireframe appearing on cycles render in random places, especially in lit places. I tried all the tricks that did not work.
https://blender.stackexchange.com/questions/320465/cycles-produces-unwanted-wireframe-pattern


text:
Merge many planes into one smooth surface?
I have many small planes, which I want to merge into one smooth surface. I did some search and found "dissolve" is probably the way to go? Here is my simple .blend file.

Use the Join tool.
Object mode , select All.
Ctrl + J to join all the parts.
Edit mode, with all selected. open Tools panel.
Tools tab > Remove > Remove Doubles.
Shading tab > Normals > Recalculate Normals.

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


text:
Why are resolution, pixel aspect ratio, and sensor size not linked in Blender?
Background
So I wrote this lil' python script to obtain the camera matrix (intrinsics times extrinsics) from my scene and its active camera. It's been working great, under the following settings.

Render resolution: x = 1000; y = 1000
Sensor size: width = 50; height = 50
Pixel aspect ratio (PAR): x / y = 1

Today, I used my script under a new setting,

Render resolution: x = 1920; y = 1080
Sensor size: width = 50; height = 18
PAR: x / y = 1

and my camera matrix projects a point (which appears inside the camera as per the viewport, i.e., the "numpad0 view") to a negative y pixel value -- outside the frame!
I thought about it, and it makes sense. The (imaginary) physical sensor is shorter in height (18) than in width (50), and I am (unreasonably) demanding unproportional resolutions and a PAR of 1. Inevitably, some of the 1080 pixels in the y direction fall outside of the physical sensor!
Questions

Is my analysis above correct?
If so, why does Blender still show me the complete rendering (instead of the partial photo truncated in the y direction), even if I'm being unreasonable?
An even higher-level question: why aren't these three quantities---resolution, pixel aspect ratio, and sensor size---coupled in Blender? If a ridiculous user like myself is demanding

Render resolution: x = 1920; y = 1080
PAR: x / y = 1

shouldn't the sensor size be constrained to a fixed, computable value already?

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


text:
Assign a custom orientation to each instance of a dupli-object
I would like to duplicate an object along a path, and also have the ability to manipulate the orientation of each instance individually.
Expected result:

Like in the picture above, where each object's orientation is determined by some unit vector defined somewhere, and possibly each object is just an instance of a duplication.
What have I tried #1: mesh & dupliverts
Parenting the object to a mesh, and selecting "Duplication > Verts" on that mesh, results in all the objects having the same orientation:

I'm not sure what happens exactly when I enable "Rotation" under "Duplication":

I know it should be possible to make the "vertex normals" count, but I don't know how to do that, and how to control these normals.
What have I tried #2: curve & dupliframes
Parenting the object to a curve, enabling "Duplication > Frames" on the object ("Speed" un-checked), then changing the "Frame number" in the Curve setting to match the number of Bezier handles.
This would be a worse solution, as the duplication would happen at each 1/n-th of the curve length, not at each Bezier handle. However, it doesn't work as the duplicated object don't seem to orientate according to the Bezier handles:

What I'm looking for
A solution that uses duplication, modifiers, standard mesh editing tools, or even python¹ would be appreciated. Consistent results are crucial!
Using particle systems wouldn't be great, as it's complicated to have fine control over each single particle/hair.
Please no animation nodes, as I can't seem to fully comprehend the pipeline. It'd be fine only as long as the solution is guaranteed to be the same, and already evaluated, every time I open the file, and static at every frame.
If I can't obtain this, I'll have to just manually (or via script) duplicate and adjust the objects, which is nonoptimal as the file size and memory usage would increase.
¹ I'm thinking of something like my attempt #1, where the orientation is linked (how?) to the vertex normals and python assigns these normals, if there's no GUI way to accomplish this.

Edit: @Lemon's suggestion (particle system)
One way to introduce some control on the orientations is to create a mesh with N vertices, assign a particle system to this mesh with

"Render>Object"

Emission: Number = N, Emit from: Verts, "Random" un-checked, Velocity = 0, Physics = No, Rotation enabled.

One can then play with the "Rotation" settings.
However, having control over "Rotation", in a way not limited to "Phase" and "Random", is what I need. I can start from one of these settings, but then I need to be able to control and adjust some of the particles.

The file
Attached:

Updated with @Lemon's suggestion:

Particles system works. Draw a line (mesh) with n vertices. Set your shape as dupli object (render panel of the PS). Set the PS emit from verts with no random and set the particle amount to n. Now you can play with the rotation panel of the PS (either velocity or phase or random + the initial orientation that can be chosen).

@lemon this might actually solve part of my problem, i.e. giving different orientations (thanks for the tip!) but it doesn't allow me to have control over each single instance, or does it? I can't seem to be able to "comb" these particles

So another suggestion: a curve plus a plane with array modifier and curve modifier. Then make your mesh dupliface of the plane and adjust the rotation using the twist of the curve (edit mode for the curve, select a vertex and ctrl+T to twist). There is no random here but you can control "all" by adding as curve vertices as you want.

@lemon nice! Unfortunatly I'd be bound to having constant distance between each instance. (I know I'm too demanding!)

Another technique here using vertex groups: https://blenderartists.org/forum/showthread.php?318143-How-can-I-randomly-rotate-objects

Related https://blender.stackexchange.com/a/163958/15543 see bottom example. Can set vert normals. (Hassle IIRC the normals are lost if vert mesh is edited. Haven't looked at new point cloud object in 2.9)

even though it is evolving quickly, geo nodes look to be a viable solution to this problem if it was never solved...

You can do it with Geometry Nodes in Version 3.0+ :
We can use this rather simple setup to instance objects at each control point of the curve :

Note you can get the value of $2 * π$ (or $6.283...$) by writing tau in a float field.
Result :

If you want to input specific values for each element, at the moment it's not possible to use vertex groups on curves so we'll have to hack our way somehow. There are multiple ways but since we're not using the control points handles I figured we could use the $X, Y, Z$ fields of the left control point to store our $X, Y, Z$ rotations.
Here's a script you can tweak to setup specific values on control points :
import bpy

from random import randint

curve = bpy.data.objects.get("Curve").data
for spline in curve.splines:
    for point in spline.bezier_points:
        point.handle_left_type = 'FREE'  # Enable custom position
        point.handle_left = (randint(0, 360), randint(0, 360), randint(0, 360))  # You can import external data (eg from a csv file) here

We'll just use a Vector Math node to transform our degrees to radians. You can delete it if your input values are in radians.

Result :

Yep, geometry nodes was the answer to this question (it just didn't exist at the time of asking :D)

Yeah I bookmarked this specifically so I could get closure on this Question once 3.0 is officially released ^^


text:
Snake Defensive Display animation
How one would approach this specific snake motion in Blender as shown in reference:
 Reference source
 Reference source
The position of the snake visibly remains almost static while the body parts quickly change their position. Using Curve and Armature Modifiers doesn't seem to help much and Soft Body Physics are difficult to control.
Edit (by vklidu):
In general - current solutions are not really solutions:

Modifier - are too spiky (+ in mesh version deforms texture)
Hooks and ShapeKeys - are correct in curvature, but this solution is not a real loop

Here a bit closer locomotion ...

it looks like it's contracting itself? so maybe curve modifier and scale on one axis?

Thanks for the suggestion. If observed closely - body contraction could be ignored. It is obvious that the body of the snake is moving on a curved path, but that path is always changing in very smooth and organic manner. That is the hardest part to figure out.

oh ok the inner shape is increasing its length actually, would it be too complicated with a curve and hooking its vertices to empties or bones?

Hi Rumen. Although i have the right to vote for closing your question - i didn't do it. But...don't be angry or frustrated. Believe me - i was often frustrated myself here because i often had the feeling that it is not fair here and i felt that some people are really unpolite here. But most of the people here are helpful and nice and have an amazing knowledge(e.g. Moonboots or Robin Betts). Maybe point out why the answer you hope to get isn't the answer they linked to be the duplicate. Sometimes they change their mind.

There are definitely complexities beyond just sticking bones to a curved path here. In particular pinning the head still and animating the path for the right movement of the body.

Have a seven foot eastern brown living up the back.  It's idea of defensive is getting on its tail chasing you and biting you in the crutch. Agree this isn't a dupe  (my answer there is more for trains) however IMO if intention is animating,  rigging the snake  is a good place to start.

Hi Chris, thank you for your support. I am not angry, but a little disappointed it was closed so quickly. I was hoping to attract more attention as I really find this problem very challenging.
Thank you for being observant Sazerac, I was fooled initially that this motion is very easy to animate until I noticed the head is almost always staying in one place. while the body keeps going. I love this movement!
@batFINGER - I am sure your answer is part of the solution, basically the deforming  Curve needs to be animated in some clever way, sadly Shape Keys don't give very smooth result.

I have no solution but I will share my observations. This seems to be a regular "forward" motion of a snake warped around into a circle. Snakes can generate waves but they cannot move forward in the absence of friction. These waves appear to be similar to peristaltic waves, muscular contractions passing down the length of its body. If friction is added the resulting force is towards the center. The pattern created is similar to those of ancient labyrinths, some interpret these labyrinths as representing an inner journey. Curious!

I would try to figure out what the problem is, before looking for a solution. With an image-sequence reference.. 1.  Manually rotoscope the changing curve to shape-keys. 2. Try to identify fixed points in the reference, (tail-tip, etc) and animate empties along the changing curve following those points. It may not be the final method, but it would give a clue about what the final method has to do. (After all, this motion has evolved, because, presumably, it confers an advantage by confusing / alarming predators)

@RobinBetts This defensive movement causes the  scales to produce sound like a poisonous snake due to the friction between them. Observation is very helpful in this case and I recommend slowing the video down or viewing it frame by frame to understand what is happening. Doing a curve 2D animation with Grease Pencil is quite a fun challenge too.

Can't you cheat a bit and animate the skin texture while actually moving just a small part of the snake near to its head?

Hi @Lukasz-40sth, everything we do to simulate this motion is mostly cheating. Obviously realistic simulation is to hard to do at this time. Any representation - 2D or 3D of this motion is welcome. So if you have an idea just post an answer. It will be much appreciated.

It depend how advanced rig or complex animation it should be.
For given reference it could work with ...

one Curve  controlled by few Hooks

and Snake controlled by Curve modifier

Just downloaded. The motion is so much simpler than it looks! Well worked out. :)

I like the way it is executed - using Hook Modifiers on the deforming Bezier Curve.
However, it is showing only the first phase of the motion.  The formed bulge on the right side of the head keeps expanding. If you try to complete a full loop (cycle) of the motion as on the videos you may run out of control points to keep up with the new shape.
I would love to see a full cycle using this approach.
By the way you don't have to animate the snake body if you switch the Curve direction and invert the snake model - the head will "stick" to the beginning of the curve.

Here is the the file with the switched direction and removed Snake object animation.
https://blend-exchange.com/b/Gv2Zz2Jd/

Wow! Well done!!!

@RumenBelev -right :) I just mimic the gif you attached, later I saw video with loop cycle, sorry. Anyway I don't think you will run out of control points since they just deform curve left&right, but it has to be animated all since inner curve runs slowly to outer. I will check that later. I have also another concept that I want to proof (tomorrow or Monday). Ad to animated snake - right thanks :) I tried to switch dir, but it didnt changed result for some reason, so I left it and focused on basic movement. If I wouldn't find loop version, I will delete answer to don't waste Jachym's bounty :)

@vklidu Hi! I am not sure how these gifs were generated. I only posted links to the video references. It is still a challenge to try and create a longer animation and you will see the issue with this approach. I am preparing an answer on my own, which is not 100% satisfactory to me. But that is what I like when discussing problems with others - a new solutions may arise. And who said that there is only one answer? ;)

Great you found solution :) BTW the gifs are done thanks to Jachym, I see ... BSE doesn't accept external links (they are not permanent) and placing reference directly to Q make it more clear a quicker for others to follow without other clicking.

@vklidu Thanks for the clarification. I will have this in mind when posting questions in the future. I hope that this is one of many solutions. Mine is not perfect. That is why I posted the question here.

Here is another way ... curve object with two modifiers used for Snake object with Curve modifier ...

Wave
Simple Deform > Bend

Not perfect yet ... I have difficulties to set shape of wave I like to (still too spiky). For now just a concept to play with :)
 ... change Simple Deform > Bend > Angle

Later I want to try Lattice or something similar that allows me adjust tips of waves to get more roundness, but ... busy days so if someone wants to move it forward ...go ahead :)

This one looks easier for a longer animation.

This is very good procedural solution! A friend of mine proposed this approach last night, but we ended to a conclusion that we cant stop the neck (head) area from moving and to control it separately. I'm quite surprised that you got the same idea independently and executed it perfectly! Good job!

Dropped the bounty here, like the clever way this answer is dealing with infinite looping :)

@JachymMichal Thanks ... Seems like I 'm occupying this thread ... hm ... I expected bigger waves with such bounty ... like no one with Animation nodes skill or some rigger ... none of the answers here really gave satisfied solution here. Lets go for second round :)

Well played sir :))

I would like to bring two new variants to the Curve deforming approach that avoid the "pinching issue" at the points where the snake is extremely bent. I would like to thank to Quentin Clemence for pointing in that direction and bringing more variety of the solutions of this problem.

I'll try to be as brief as possible due to the solutions being fairly simple and understandable.
Variant A - Rotating Torus
The animation curve is initially a "zig-zag" shaped cylinder (closed curve). One could play with the width of various parts of the "waves".

A Hook modifier rotates the curve along the cylinder's axis.
Then a Simple deform shapes it into a Torus. Animated it looks like this:
 and
The model snake is NURBS path curve but it could be also a mesh object with Curve modifier.
To keep the snake in place a linear transformation is animated to counteract the rotation of the torus. The result looks like this:

The shape of the animated curve can be deformed additionally using Lattice modifier.
The position of the snake can be adjusted in such way that the head is going up in the center of the torus where some sort of distortion happen.
A possible solution is given at the end of this text.
Here is how the modifier setup looks like:

Variant B: Translating Spiral
I am not sure what is the name of this curve, let's say it is some sort of a spiral.
Again it is a pre-modeled open curve shape that looks like this:

Again a Hook modifier is added to the curve but for translation only.
A lattice modifier is added second to flatten the curve. The resulting animated curve is shown below:
 and
The lattice is shown in final state. It was deformed to flat shape in Edit mode in two steps:

The snake (NURBS curve) object uses that curve as deformation modifier and was animated similarly to the first variant so it stays in place. Here is the result that can be modified further by adding more curve loops and resolution to the lattice:

Modifier set-up:

The body animation seems nice but the problem with the head part is the same as in the variant A. The head is fixed, looking up and wobbling.
Here is a solution: We are using a curve for the body deformation. This curve can be a basis for a Spline IK constraint of an Armature. The armature rig is split in two - body and head. The body bones are part of the Spline IK constraint, while the head bone is targeting an Empty.

Blend files for your own study:
Variant A:

Variant B:

Pros: Solves the "pinching" of the body. Very lightweight. No texture distortion ("worm effect"). Adjustable shapes.
Cons: The curve tilt may cause some body rotation which is visible with more complex textures. It also affects the bone rotations in the Spline IK chain.

Absolutely fantastic stuff.IMO, because this kind of cross-domain, 3D > 2D  idea could generalize to other problems, not just in animation. Is there a particular link for your reference?

@Robin Betts Unfortunately there is no reference. It was a private discussion and we were just throwing out ideas. Quentin is working on shadow projections and he found the 3D objects that could possibly generate these 2D shapes in motion. It is in fact  a fascinating area to explore and Blender has the capabilities to assist. I have big  hopes for the Geometry Node that could give us more access and control over the Curve object. For example control on Tilt orientation of a Curve can help in resolving the above mentioned issue.

Reminiscent of 4D > 2D, to loop/tile procedural noise.

despite the disadvantages I like the concept :) Thanks

I wanted to come up with Lattice version, because there is not a way to adjust wave shape inside modifier in a shape I would like to.
With Lattice deformer it is possible in some limited way, also with lattice you can completely fix snake's head position ... the biggest issue here is material.

Instead of curve objects you can go with mesh object, because with mesh you can set a vertex group to be affected by Wave modifier.

Add Lattice like resolution U 12 / V 6 / W 1 and transform basic shape in object mode to cover wavy strip
To make final bended waves less spiky go to edit mode select middle controls points and with proportional editing enabled scale on X axis t move grid closer to sides.
Add Simple Deform > Bend modifier to Lattice object

As final step - create mesh Snake object and with all modifiers of wavy strip disabled add Surface Deform modifier > Target – wavy strip and Bind it.

Notes:

use Subdivision modifiers as many you need
you can also move lattice vertices in snake tail part closer to head - like that bended tail became closer to fat part of snake body (same in your reference)

The biggest issue is shader that calculates texture coordinates before lattice ...

Another great solution @vklidu! One thing I like about it is that you have excluded the Curve object as helper. It seems this solution gives very stable result.
One thing I don't like about the Wave modifier is that it doesn't produce very symmetric waves and I am thinking about using Displacement Modifier with Wood Sine Texture. I will post a solution here as soon as I polish it. You have my up-vote on this one :)

Here is my take using curve Shape Keys for the animation.
This requires some good animation skills and patience.
I prefer using NURBS curve for this specific shape - Figure 1
Initially I start with a Curve Path object and subdivide it twice
Then subdivide some more only the first segment where the head will be and then snap these generated points to the first control point.
I'll call them "spawn points". Currently the segments they create will not contribute to the curve shape as they have zero length.

Now I start pushing the body points to form the initial snake body shape - Figure 2. That is not necessary but saves some animation time as my intent is for looping animation.

On the next step we add the snake object and use the NURBS curve as Curve Modifier. It is important to be able to see the body of the snake to prevent intersecting body parts during the animation - Figure 3

The last step is harder to describe in few words but basically the animation is a sequence of Shape Keys of the NURBS path. I prefer using Absolute shape keys (the Relative option is turned off) as it is easier to control the speed using the Evaluation Time property. Figure - 4

On each sequential Shape a new "spawn" point is introduced, leaving the location of the first "head" point. It will now contribute to the body shape, providing more resolution (point density) where it is most needed (close to the head and neck). To select a subsequent "spawn" point just select a previous one then [CTRL]+[+] to include it in the selection. You can see how the shape changes in the attached blend file and on the animation below (apologies for my poor FFMPEG conversion skills)
Blend file:

Pros: It is easy to animate using fewer modifiers and objects.
Cons: Due to the nature of shape keys the transition form one shape to another is in linear fashion and this doesn't produce very smooth result unless you use more and more shape keys. That makes this animation hard to reproduce and modify.

Another nice answer to IMO a nice Q. Thanks to @Jachym again for pointing it up. Downloaded.. the movement is easier to see with a bands texture at a frequency chosen to try to avoid the strobe?... but I guess the conversion to gif would screw it, anyway.

@RobinBetts I had to lower the frame rate to 8 fps to satisfy the 2 MB GIF restriction. In the blend file you can set a longer animation time to see better the pattern direction.
There are just two key frames in total. The longer the animation time the better you see the poor transition between shapes.
As I mentioned this approach requires good animation skills and patience, which I am lacking. You have to play with the animation curve to correct the speeds between the shape keys or add more in-between shapes to smoothen the movement.
It is indeed faster than the original movement.

i use many animated curves to join 2 big curves, then use sverchok to combine those 2 curves into final animated curve.

I am happy to see Sverchok in action and I love the mechanical feel of this animation. I don't understand the node set-up very well but it will be a nice challenge to reverse engineer what you did in the blend file. There is obvious curve manipulation and mathematical parts in the node tree. I believe that this motion can be described mathematically I already have some ideas. Also the snake model rocks! Do you give permission for using it by other users?

The model is not my works, here is the link. https://www.blendswap.com/blend/7985

Here is a modified and optimized version of the vklidu's approach.
It differs by replacing the Wave modifier with Displacement modifier.

For the Surface Deform object I start with a straight line of connected vertices alnog Y axis and making sure there is bigger vertex density at the "tail" section.
I add all vertices to a vertex group which will control the displacement effect. Also added an Empty object at the "head" section to be used for the vertex group modification using the Vertex Weight Proximity Modifier.

I add Wave_Animation_Control Empty which will control the displacement texture and its animation. Rotating the Empty 45 degrees along Y axis gives good alignment of the texture with the Surface_Deform object
The Texture is parametric Wood Sine texture which gives nice symmetric sine waves. The Color Ramp is enabled to take advantage of the Ease interpolation for more round/flat crests of the waves. That helps with the pointiness of the snake's body bending points.

Lastly I add the Simple Deform modifier and a Screw modifier to generate a polygonal surface to be used in the surface deformation (see below).
At this point you can test the animation by moving the Wave_Animation_Control along the Y axis.

Here is a set up of the Snake object using only modifiers.
One could try with a realistic snake model. The important part is to Y-scale (squish) the snakes body to the length of the Surface_Deform object or less.
The most important modifier in the snake's model is the Surface Deform modifier. Before binding both meshes, make sure to disable the deforming modifiers as shown below.

After the binding you can enable the remaining of the SurfaceDeform object modifiers. The result:

and you can download the blend file here:

I also did a Lattice Deform version which gives additional control over the waves spacing:

the blend file is here:

Both set-up give better real-time responsiveness than the previous solutions.
The cons of these solutions is that the Snake's body is too squishy when moving, which can be seen with the texture enabled. It is more worm-like than a rigid snake body. Having a Curve to keep the snake's body unchanged in length is preferable in my opinion.

I didnt check your file closer for now, but result is issued by the same things like wave-lattice version ... too small radius in turns and uneven texture that is stretched/squized https://imgur.com/eR9q2u8 ... sorry

Path follow it, the effect is mainly that the texture of the snake is small in size, so the movement over the path causes the effect, you might even animate the path a bit
another way to do it would be through a mesh deform modifier
with a mesh of the curvature ( partly (using empty bindings)).
the problem here would be to overcome stretching, so you get chain alike constructs (empties with distance restrictions)..
I think there are a few solutions possible this way, though they take some time to configure, (currently dont have that time to create a demo file).

Thank you for your answer. Following a path - like moving on a rails won't help much, but using a curve to control the shape of the snake is a good approach.
I would love to see what you came up with using the Mesh Deform Modifier. I haven't thought about using it as part of the solution.
A screenshots or example blend file could be very helpful.

Sorry not having the time for that, though its pretty simple, you model it all traight (as a long line alike cube, you put a straightned snake in , and then deform that cube to a circle (snake will deform as well), pushing the snake forward, will move it through the mesh deformer (following it)


text:
Script Outdated - Shape keys and applying subdivision surface modifier
I've spent a lot of time with creating Shape Keys for my model and now I see I have forgot to Apply the Subdivision Surface modifier.
How can I Apply modifier and keep all my Shape Keys?
Thank you for help.

where do you want to use your (well known) dragon ? In UE ? I dont know if there is a way to export a mesh with shape keys in a good format for UE ? Have you checked all that ?

Have a try with a very simple mesh with some shape keys and a subsurf.

I truly think I have posted way too many things about my dragon project indeed.. :D
UE4 seems to support this indeed. Shape keys there are called morph targets. However, I haven' t tried that earlier..
With very simple mesh, like cube, it's relatively easy to push or drag the geometry when subsurf is applied, but I have an eyelid which can' t be dragged as easily, even with proportional editing it's quite hard to get the shape I look for because there's too much geometry to handle...

FYI. I dont have UE, but I did some tests exporting and reimporting a simple object with both shape keys and subsurf. I did it in obj, and dae. Each time the result was bad : the reimported object was not good. I dont know if it is to considerer as "bad news" for you... but to be totally sure, you should import some simple mesh to UE and test it.

There is a workaround here http://blender.stackexchange.com/questions/9007/cannot-apply-array-modifier. This is the same principle for subsurf and array. It works, I have tested it.

This answer comes from a previous one here Cannot Apply Array Modifier. I simply add some more details in the explanation and a way to do it for all shape keys at once.
Here is a simple shape, which has a subsurface modifier and shape keys :

Make one copy of your initial object for each shape key and set for each the shape key to "1" :

Select these copies and pull down the Object menu and select Convert > Mesh, (for 2.79 and earlier press Alt + C Convert > Mesh from Curve).

The modifiers are applied and the shape keys too (these objects now have no shape keys or subsurf modifiers).
Make another copy of your original object, remove the shape keys from it, and apply the Subsurf modifier :

Now select the "shape keyed" objects, and the last copy we just made (in this order), and in the shape key panel use "join as shapes" :

We now have the final object, with the subsurface modifier applied and the shape keys available :

Thanks alot for this wonderful explanation. I don' t know what I would've done without your help (probably created all those 10 shape keys again...). Thanks.. man once again :)

you are welcome. I hope to see some pic of your dragon live : )

but anyway.. have a check about how will UE accept shape keys (after an export from Blender)

Yep. I'll let you know when I finally finish it... which seemingly won' t happen in near future if I keep doing those mistakes that I'm doing (but it's really good to go through all those mistakes by myself so I could understand how much pain they can cause :) ).
Yup. I'm trying to get to know it better. I have quite many problems already with UE4 by understanding what can be done or what can't.. For example, today I spent the whole day trying to understand whether I should use one multi-texture for my dragon using UDIM technology or use 3 separated objects instead.

Anyways. I'll let you know when the model is ready :D

That's some really great answer, it helped me a lot! THANKS!!!

This seems like something that could be scripted instead of done manually. Has anyone seen a script that does this?

This is very good advice, however sometimes it's very difficult to apply shape keys to high poly models whose subdivision surface modifier has been applied. If you decide to set your shape keys before applying the modifiers on several models, it will take a very long time to follow the process described above.

Here is an updated script which is tested and working for me on 2.91.2. The script from the existing answers still wasn't working for me in 2.9, so I took into account the fixes mentioned the comment by @paddyg (also had to remove apply_as='DATA' from modifier_apply since that is deprecated). It still creates a duplicate Basis.001 shape key (which you can just delete) but otherwise I think it works properly.
To use it, just paste this code into the Blender text editor, select your object, then click the Run Script button (little play button in the text editor header).
(I added the call to super_apply_modifiers() at the end so you could just run it from the text editor. This seemed easier to me than running it from the console, but you can remove the last line if you want to do it the other way.)
import bpy

def reset_shape_keys ():
    for name, shape_key in get_active_block().items():
        shape_key.value = 0

def get_active_block ():
    block_id = bpy.context.object.active_shape_key.id_data.name
    return bpy.data.shape_keys[block_id].key_blocks

def select (selection):
    bpy.ops.object.select_all(action='DESELECT')
    selection.select_set(True)
    bpy.context.view_layer.objects.active = selection

def select_last_shape_key ():
    shape_key_count = len(get_active_block().items())
    bpy.context.object.active_shape_key_index = shape_key_count - 1

def remove_shape_keys (object):
    selection = bpy.context.object
    object.shape_key_clear()
    select(selection)

def apply_modifiers (object):
    selection = bpy.context.object
    select(object)

    for key, modifier in object.modifiers.items():
        if key != 'Armature':
            bpy.ops.object.modifier_apply(modifier=key)

    select(selection)

def super_apply_modifiers ():
    original = bpy.context.object
    bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={
        "linked":False, "mode":'TRANSLATION'},
        TRANSFORM_OT_translate={
            "value":(0, 0, 0),
            "constraint_axis":(False, False, False),
            "orient_matrix":[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
            "orient_matrix_type":'GLOBAL',
            "mirror":False,
            "use_proportional_edit":False,
            "proportional_edit_falloff":'SMOOTH',
            "proportional_size":1,
            "snap":False, "snap_target":'CLOSEST',
            "snap_point":(0, 0, 0),
            "snap_align":False,
            "snap_normal":(0, 0, 0),
            "gpencil_strokes":False,
            "texture_space":False,
            "remove_on_cancel":False,
            "release_confirm":False,
            "use_accurate":False
        })
    backup = bpy.context.object
    backup.name = original.name + '_backup'
    remove_shape_keys(original)
    apply_modifiers(original)

    for key, shape_key in get_active_block().items():
        select(backup)
        bpy.ops.object.duplicate_move(
            OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'},
            TRANSFORM_OT_translate={
                "value":(0, 0, 0),
                "constraint_axis":(False, False, False),
                "orient_matrix":[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                "orient_matrix_type":'GLOBAL',
                "mirror":False,
                "use_proportional_edit":False,
                "proportional_edit_falloff":'SMOOTH',
                "proportional_size":1,
                "snap":False,
                "snap_target":'CLOSEST',
                "snap_point":(0, 0, 0),
                "snap_align":False,
                "snap_normal":(0, 0, 0),
                "gpencil_strokes":False,
                "texture_space":False,
                "remove_on_cancel":False,
                "release_confirm":False,
                "use_accurate":False
            })

        meshed_shape_key = bpy.context.object
        select(meshed_shape_key)
        reset_shape_keys()
        get_active_block()[key].value = 1
        bpy.ops.object.convert(target='MESH')

        select(original)
        meshed_shape_key.select_set(True)
        bpy.ops.object.join_shapes()
        select_last_shape_key()
        bpy.context.object.active_shape_key.name = key

        select(meshed_shape_key)
        bpy.ops.object.delete(use_global=False)

super_apply_modifiers()

Thank you everyone for the other answers, I had done a bunch of modeling using multiple shape keys with a subsurf modifier on the whole time, without realizing this isn't the "proper" workflow, and then got slapped with the "modifier cannot be applied to a mesh with shape keys" error.
EDIT: When I first posted this, I'd only tested in 2.90.1. It broke again in 2.91.2, but after updating remove_shape_keys() to use  object.shape_key_clear() instead of iterating, as suggested by @paddyg, it works again.
EDIT by vklidu: I thought @Ned script is outdated, but the script works even in 3.3.
If there is set just a one Shape Key it works fine ... if there is more Shape Keys, than "Key 1" has to be selected (under Data Properties > Shape Keys) to prevent error.

Thank you! I was trying to get the ShapeKeys Helper plugin working for this and it wouldn't work with 2.80+, but this worked great!

Does this un-intuitive behaviour of "needed selection" can be avoided by some script update? Thank you

Any update on this for 3.3? -- It fails with the following error: ERROR (bke.mesh_convert): C:\Users\blender\git\blender-v330\blender.git\source\blender\blenkernel\intern\mesh_convert.cc:1574 BKE_mesh_nomain_to_mesh: YEEK! this should be recoded! Shape key loss!: ID 'MECube.003'.

Oh -- figured it out -- two issues: 1.) I had to delete the shape key's driver. (The script isn't smart enough to preserve those -- so you will still have to recreate them all -- any chance for a fix?) -- and 2.) contrary to the instructions, don't create a key named "Key 1", just select the first non-"Basis" key.

I scripted @Lemon 's answer!
the code is kinda long, but I think it is (I hope it to be) self-explanatory. Just copy the code into a new file on blender's text editor, call the text file apply_with_shape_keys.py, and then, select the object with the modifiers and shape keys, (make a backup, just in case). Now from the console execute it like this:
>>> import apply_with_shape_keys
>>> apply_with_shape_keys.super_apply_modifiers()

the script will apply all the modifiers conserving the shape keys! and will create a new object called "backup" without the modifiers applied (just in case you wanna add new shape keys in the future).
If the object has an armature, the script will explicitly not apply that modifier. Also you have to make sure that the skeleton is in the original pose, otherwise strange things will happen.
here is the code!
import bpy

def reset_shape_keys ():
    for name, shape_key in get_active_block().items():
        shape_key.value = 0

def get_active_block ():
    block_id = bpy.context.object.active_shape_key.id_data.name
    return bpy.data.shape_keys[block_id].key_blocks

def select (selection):
    bpy.ops.object.select_all(action='DESELECT')
    selection.select = True
    bpy.context.scene.objects.active = selection

def select_last_shape_key ():
    shape_key_count = len(get_active_block().items())
    bpy.context.object.active_shape_key_index = shape_key_count - 1

def remove_shape_keys (object):
    selection = bpy.context.object
    select(object)
    shape_key_count = len(get_active_block().items())
    select_last_shape_key()
    for i in range(0, shape_key_count):
        bpy.ops.object.shape_key_remove(all=False)
    select(selection)

def apply_modifiers (object):
    selection = bpy.context.object
    select(object)

    for key, modifier in object.modifiers.items():
        if key != 'Armature':
            bpy.ops.object.modifier_apply(apply_as='DATA', modifier=key)

    select(selection)

def super_apply_modifiers ():
    original = bpy.context.object
    bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(0, 0, 0), "constraint_axis":(False, False, False), "constraint_orientation":'GLOBAL', "mirror":False, "proportional":'DISABLED', "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False})
    backup = bpy.context.object
    backup.name = 'backup'
    remove_shape_keys(original)
    apply_modifiers(original)

    for key, shape_key in get_active_block().items():
        select(backup)
        bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(0, 0, 0), "constraint_axis":(False, False, False), "constraint_orientation":'GLOBAL', "mirror":False, "proportional":'DISABLED', "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False})

        meshed_shape_key = bpy.context.object
        select(meshed_shape_key)
        reset_shape_keys()
        get_active_block()[key].value = 1
        bpy.ops.object.convert(target='MESH')

        select(original)
        meshed_shape_key.select = True
        bpy.ops.object.join_shapes()
        select_last_shape_key()
        bpy.context.object.active_shape_key.name = key

        select(meshed_shape_key)
        bpy.ops.object.delete(use_global=False)

I've made a simple change to your code, to give the backup object a more comprehensive name instead of just "backup" by adding "_backup" to the original file name.>>>backup.name = original.name +'_backup'

Throws error: keyword "constraint_orientation" unrecognized. :(

what version of blender are you using? I made it a long time ago lol... are you with blender 2.8+?

I just updated the @Bengalaa 's script with @Lemon 's answer to work in blender 2.90
# File: apply_with_shape_keys.py
# usage:
#   - select an object to apply modifiers on
#   >>> import apply_with_shape_keys
#   >>> apply_with_shape_keys.super_apply_modifiers()

import bpy

def reset_shape_keys ():
    for name, shape_key in get_active_block().items():
        shape_key.value = 0

def get_active_block ():
    block_id = bpy.context.object.active_shape_key.id_data.name
    return bpy.data.shape_keys[block_id].key_blocks

def select (selection):
    bpy.ops.object.select_all(action='DESELECT')
    selection.select = True
    context.view_layer.objects.active = selection

def select_last_shape_key ():
    shape_key_count = len(get_active_block().items())
    bpy.context.object.active_shape_key_index = shape_key_count - 1

def remove_shape_keys (object):
    selection = bpy.context.object
    select(object)
    shape_key_count = len(get_active_block().items())
    select_last_shape_key()
    for i in range(0, shape_key_count):
        bpy.ops.object.shape_key_remove(all=False)
    select(selection)

def apply_modifiers (object):
    selection = bpy.context.object
    select(object)

    for key, modifier in object.modifiers.items():
        if key != 'Armature':
            bpy.ops.object.modifier_apply(apply_as='DATA', modifier=key)

    select(selection)

def super_apply_modifiers ():
    original = bpy.context.object
    bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={
        "linked":False, "mode":'TRANSLATION'},
        TRANSFORM_OT_translate={
            "value":(0, 0, 0),
            "constraint_axis":(False, False, False),
            "orient_matrix":[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
            "orient_matrix_type":'GLOBAL',
            "mirror":False,
            "use_proportional_edit":False,
            "proportional_edit_falloff":'SMOOTH',
            "proportional_size":1,
            "snap":False, "snap_target":'CLOSEST',
            "snap_point":(0, 0, 0),
            "snap_align":False,
            "snap_normal":(0, 0, 0),
            "gpencil_strokes":False,
            "texture_space":False,
            "remove_on_cancel":False,
            "release_confirm":False,
            "use_accurate":False
        })
    backup = bpy.context.object
    backup.name = 'backup'
    remove_shape_keys(original)
    apply_modifiers(original)

    for key, shape_key in get_active_block().items():
        select(backup)
        bpy.ops.object.duplicate_move(
            OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'},
            TRANSFORM_OT_translate={
                "value":(0, 0, 0),
                "constraint_axis":(False, False, False),
                "orient_matrix":[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                "orient_matrix_type":'GLOBAL',
                "mirror":False,
                "use_proportional_edit":False,
                "proportional_edit_falloff":'SMOOTH',
                "proportional_size":1,
                "snap":False,
                "snap_target":'CLOSEST',
                "snap_point":(0, 0, 0),
                "snap_align":False,
                "snap_normal":(0, 0, 0),
                "gpencil_strokes":False,
                "texture_space":False,
                "remove_on_cancel":False,
                "release_confirm":False,
                "use_accurate":False
            })

        meshed_shape_key = bpy.context.object
        select(meshed_shape_key)
        reset_shape_keys()
        get_active_block()[key].value = 1
        bpy.ops.object.convert(target='MESH')

        select(original)
        meshed_shape_key.select = True
        bpy.ops.object.join_shapes()
        select_last_shape_key()
        bpy.context.object.active_shape_key.name = key

        select(meshed_shape_key)
        bpy.ops.object.delete(use_global=False)

Thanks to all above for helpful answers. I still got errors running with Blender 2.90.1-linux64 essentially due to object.select = True which had to be object.select_set(True) and the bpy.context.object.active_shape_key.id_data.name caused errors for some reason running in the Text editor. The armature modifier also got deleted but easy enough to put back (and an additional shape_key Basis was added) Finally I used object.shape_key_clear() to delete all the shape_keys rather than iterating.

Here is fixed version.
Tested with Blender 3.3.1
Edit: copy pasted code from my gist
# https://blender.stackexchange.com/questions/56795/script-outdated-shape-keys-and-applying-subdivision-surface-modifier
import bpy

def reset_shape_keys ():
    for name, shape_key in get_active_block().items():
        shape_key.value = 0

def get_active_block ():
    if bpy.context.object.active_shape_key is None or bpy.context.object.active_shape_key.id_data is None:
        bpy.context.object.active_shape_key_index = 0
    block_id = bpy.context.object.active_shape_key.id_data.name
    return bpy.data.shape_keys[block_id].key_blocks

def select (selection):
    bpy.ops.object.select_all(action='DESELECT')
    selection.select_set(True)
    bpy.context.view_layer.objects.active = selection

def select_last_shape_key ():
    shape_key_count = len(get_active_block().items())
    bpy.context.object.active_shape_key_index = shape_key_count - 1

def remove_shape_keys (object):
    selection = bpy.context.object
    object.shape_key_clear()
    select(selection)

def apply_modifiers (object):
    selection = bpy.context.object
    select(object)

    for key, modifier in object.modifiers.items():
        if key != 'Armature':
            bpy.ops.object.modifier_apply(modifier=key)

    select(selection)

def super_apply_modifiers ():
    original = bpy.context.object
    bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={
        "linked":False, "mode":'TRANSLATION'},
        TRANSFORM_OT_translate={
            "value":(0, 0, 0),
            "constraint_axis":(False, False, False),
            "orient_matrix":[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
            "orient_matrix_type":'GLOBAL',
            "mirror":False,
            "use_proportional_edit":False,
            "proportional_edit_falloff":'SMOOTH',
            "proportional_size":1,
            "snap":False, "snap_target":'CLOSEST',
            "snap_point":(0, 0, 0),
            "snap_align":False,
            "snap_normal":(0, 0, 0),
            "gpencil_strokes":False,
            "texture_space":False,
            "remove_on_cancel":False,
            "release_confirm":False,
            "use_accurate":False
        })

    backup = bpy.context.object
    backup.name = original.name + '_backup'
    remove_shape_keys(original)
    apply_modifiers(original)

    try:
        for key, shape_key in get_active_block().items():
            select(backup)
            if(key == "Basis"):
                continue
            bpy.ops.object.duplicate_move(
                OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'},
                TRANSFORM_OT_translate={
                    "value":(0, 0, 0),
                    "constraint_axis":(False, False, False),
                    "orient_matrix":[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                    "orient_matrix_type":'GLOBAL',
                    "mirror":False,
                    "use_proportional_edit":False,
                    "proportional_edit_falloff":'SMOOTH',
                    "proportional_size":1,
                    "snap":False,
                    "snap_target":'CLOSEST',
                    "snap_point":(0, 0, 0),
                    "snap_align":False,
                    "snap_normal":(0, 0, 0),
                    "gpencil_strokes":False,
                    "texture_space":False,
                    "remove_on_cancel":False,
                    "release_confirm":False,
                    "use_accurate":False
                })

            print("key: " + key);
            meshed_shape_key = bpy.context.object
            meshed_shape_key.name = backup.name + '_' + key
            select(meshed_shape_key)
            reset_shape_keys()
            get_active_block()[key].value = 1
            bpy.ops.object.convert(target='MESH')

            select(original)
            meshed_shape_key.select_set(True)
            bpy.ops.object.join_shapes()
            select_last_shape_key()
            bpy.context.object.active_shape_key.name = key
            select(meshed_shape_key)
            bpy.ops.object.delete(use_global=False)

        backup.hide_set(True)

    except Exception as err:
        original_name = original.name
        original.name = original.name + "_broken"
        backup.name = original_name
        select(original)

super_apply_modifiers()

gist version might have other fixes too:
https://gist.github.com/terokorp/c2e0bdadf4cffcc856098b93b84d38a9/

Understandable to post a link to github, but typically we ask that the answer contain all of the necessary information and links are supplementary.  Cheers and thanks for the work.

Thanks for your contribution! However, it would be great if you could reword the answer so that all the necessary information can be found in it and it doesn't just consist of a reference to an external link.

Thank you, that is an improvement, I undelete the post again! In the future, please always make sure to give the most comprehensive answer possible, because content to external links can be lost, which would make your post here useless.


text:
Creating a full, complete and an autonomous duplicate
I have an Area Light with some nodes enabled and some of these nodes have Drivers on them that are tethered to a parented object’s properties and vice versa. How can I duplicate this light an the parented object completely, and have all the data block names updated to the copied ones, so they are not tethered to the original?

When you duplicate only a child object, it is automatically parented to the same parent as the object from which it was duplicated. When you select both child and parent object and duplicate them, the new child will automatically be parented to the new parent object. Also a driver on the child object referencing the parented object will be updated as well. Have you tried this?

I've tried it and both child and parent are indeed being duplicated, but the Drivers aren't being updated and still are being driven by the original. I should mention that inside of the parent (Area Light), there's a bunch of node groups that obviously haven't been even made Single User. Most of the Drivers are on some nodes inside of these node groups. The child has a Geometry Nodes setup on it and some of the stuff there is also driven by things like Area Light size, and the copied Geometry Node setup isn't single user as well.

Well, that's a much more complex setup as the question suggested... you talk about object properties there, Geometry Nodes are mentioned nowhere. Geometry Nodes nodegroups are in a way like materials, not directly bound to the object holding them, their internal structure does not change when you put them on different objects. Only variables connected to the Group Input can be changed per object which uses the nodegroup, by default this is the base mesh coming from the input for example, or values connected to input sockets which can then be given individual values in the modifiers tab.

Yeah, this is quite the pain. For some reason I expected this functionality to exist already in Blender. Basically, what I want is to be able to copy any object and everything that may or may not be parented to it and have the option of making everything fully autonomous, every shader and geometry node made single user, every driver updated to work within these new duplicates.


text:
How do i get the exact surface area of a complex model
I have a complex bridge model made of around 3000 objects but a lot of them are inside eachother adding to the surface area so i want them away.
i tried using bool tool but some faces disappear.

Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.

May I know why you need the aurface area? Do you just need to get an estimate? You could join all objects together and then Remesh (Voxel) it and use this method to calculate surface area.

There is no functionality for that. You have to join them somehow. Booleans are a viable option, they just don't always work, so you could try combining few parts at a time until that works, making sure to move the parts slightly(fractions that do not interfere with your purpose, maybe millimeters if you are working in tens of meters) if you run into problems. You can also try different Boolean algorithms (fast/exact). Booleans generally might not work well if you have vertices that are very close together or overlapping geometry, n-gons, non-manifold geometry or sometimes no apparent reason at all. Boolean algorithms are not perfect in pretty much any surface modelling software.


text:
The shape squashes sharply but I want it to be curved, what can I do to fix this?
I am trying to create a mannequin model where the abdomen box bends and twists when I move the thorax or pelvis. The stretched side (left from viewer) looks good but the squashed side looks weird.

I want it to be curved like the stretched side but its sharp. What can I do to fix this?

i would recommend searching for "blender armature shape keys". There are dozens of tutorials on yt and answer here.

Hello please share your file: https://blend-exchange.com/


text:
Mirror on Hook modifier
I'm a beginner at blender so I'm sorry if I'm not explaining this perfectly.

This is my model and I'm trying to animate it.
The idea is to have the two armes stretching and squashing the cube in the middle.
I can move the top arm while moving the bottom one using mirror modifier.
I added an Empty named FullBodyHook to control it.
I managed to have the top on working using the hook modifier on the to face of the cube linked to FullBodyHook.

Now I want the bottom face of the cube to move in a mirror manner to the top while it still being perfectly symetrical. (I don't want to have to animate the bottom manualy)
I created an Empty hooked to the bottom but no matter what I was trying I couln't have it mirror the action of FullBodyHook.
Is there a way to do that in Blender.
Thank you for your help

Hello please share your file: https://blend-exchange.com/

Wanting the actions of one object to control of another? Think drivers.

Right click the value you want to use to "drive" the value of another. Lets go with the Z-axis location for this example.

Then paste the value into whatever value you want to be controlled with right click as well.

By itself this driver will just copy the values from one to the other, but if you change it to "Scripted Expression" and set the driver to be "location * -1" it will invert that value.

End result:

I set the X-axis location to be copied 1:1 and the Z-axis to be the inversion of the controller object.

Thank you for your help !

Did this answer solve your problem @AntoineBedry?

It did thank you

Cool, then can you accept the answer so that it removes the Q from the unanswered questions queue?


text:
Can't animate location of characters in text individually
Here's the blend file: http://pasteall.org/blend/index.php?id=44670. If you keyframe the location of the letter "I" at a different location and then move the greenbar the rest of the letters will follow its origin. I've been looking for answers on the internet and can't find a solution.

P.S. here at stack exchange we pefer if you use Blend-Exchange, http://blend-exchange.giantcowfilms.com/ ,  for the files will never will never expire. Just for future reference ;)

All the letters have strips in the NLA Editor which share the same action:

But this action contains nothing so it looks like the letters aren't animated. For this same reason you can use Remove Emtpy Animation Data option to remove all the empty strips:


text:
cloth tent problem
I have a big problem with a tent, the tent almost never remains in place and falls into the floor. I created a simple cylinder to use as a stick and I added the collision, same thing for the floor. How could I solve this?

http://s000.tinyupload.com/index.php?file_id=06659551165230967310 File Source

Go to Edit mode and select top vertices.
In Object Data tab create new Vertex Group and click Assign.

Go to Physics tab and check Pinning and select Vertex Group.


text:
Moving Back and Forth - Animation Node(PYTHON) vs Unity (C-SHARP) Boolean Switch Logic
public class ChangeDirection : MonoBehaviour {
public bool movePositive = true;

// Update is called once per frame
void Update () {
    // CHECK IF MAX REACHED AND MOVING POSITIVE DIRECTION
    if (this.transform.position.y <= 4f && movePositive) {
        // MOVES IN POSITIVE DIRECTION
        this.transform.position += Vector3.up * Time.deltaTime * 5f;
    }
    else {
        movePositive = false;
    }
    // CHECK IF MIN REACHED AND MOVING NEGATIVE DIRECTION

    if (this.transform.position.y >= -4f && !movePositive) {

        // MOVES IN NEGATIVE DIRECTION
        this.transform.position += Vector3.down * Time.deltaTime * 5f;
    }
    else {
        movePositive = true;
    }
 }
}

NOT C-SHARP QUESTION EXACTLY - I NEED TO IMPLEMENT A BOOL LOGIC IN PYTHON
The code above moves an object back and forth within specified limit making one bool switching True and False,
Hits the max and moves in negative direction and hits the min and moves in positive direction.
But as you can see in the image, I can't do the same thing with the same logic. How can it be implemented in Python script with Animaton Node - Blender?

Adding the code extra if you have problem with image
move_pos = True

if input_x < 20 and move_pos:
    input_x += 1
else:
    move_pos = False

if input_x > -20 and not move_pos:
    input_x -= 1
else:
    move_pos = True

output_x = input_x

It took me a while but I could come up with a solution creating a class.
Including class method makes it static-like and increases the performance compared to calling the function on class object.
The interesting part; I had to use "time info" as an input in a "for loop" otherwise it just moves to the end point.

I see no good reason to discretize such simple animation. A parametric approach might be better. To move an object between 0 and 1 in 20 frames, you can use such node tree:

To see why it works, plot the function. Another approach would be to use the animation nodes in Animation Nodes:

I can't see the images. They are not opening. It is for learning purposes to compare stuff between two different platforms. Trying to understand the approach in general with scripting.

@vGuMuS They are working fine for me, they are gifs. If your question is how to convert C# into python, then I think it is better asked in stackoverflow.

Okay I can see them now. I like your approach but I would like to see the process which can be done using script in AN. It is not a C sharp question. I need a logic with bool switching.

By the way I checked the first node tree. Do we really need division node? It works just fine without it.

@vGuMuS Divide is just to make the interval into 0 1, but if you want it as is, then you can remove it.


text:
Clip depth field of view in nodes
I am a beginner in Blender. This is what I do to save the depth:

I can get the real Z in meter from the camera to the object. But how to simulate the field of view of the depth sensor?
Concretely, this is what I would like to do but using some mathematical nodes:
if (depth(i,j) < z_max) {
  if (depth(i,j) > z_min) {
    depth_clean(i,j) = depth(i,j);
  } else {
    depth_clean(i,j) = 0;
  }
} else {
  depth_clean(i,j) = 0;
}

This is how to do it using the Python API, see this answer for a reference:

add a viewer node and connect the Z ouput of the Render Layers to the Viewer node
get the pixel data of the viewer
perform the depth "clipping" in Python
copy back to a bpy.ops.image
save the image in OpenEXR format

Script:
import bpy
import numpy as np

# https://blender.stackexchange.com/questions/35191/how-to-get-color-and-z-depth-from-viewer-node/71264#71264
bpy.context.scene.render.use_compositing = True
bpy.context.scene.use_nodes = True
tree = bpy.context.scene.node_tree
links = tree.links

for n in tree.nodes:
    tree.nodes.remove(n)
rl = tree.nodes.new('CompositorNodeRLayers')

vl = tree.nodes.new('CompositorNodeViewer')
vl.use_alpha = True
links.new(rl.outputs[0], vl.inputs[0])  # link Render Image to Viewer Image
links.new(rl.outputs[2], vl.inputs[1])  # link Render Z to Viewer Alpha

#render
bpy.context.scene.render.resolution_percentage = 100 #make sure scene height and width are ok (edit)

step_count = 251
scene = bpy.context.scene
for step in range(1, step_count):
    # Set render frame
    scene.frame_set(step)

    # Render
    bpy.ops.render.render()

    #get the pixels and put them into a numpy array
    pixels = np.array(bpy.data.images['Viewer Node'].pixels)

    width = bpy.context.scene.render.resolution_x
    height = bpy.context.scene.render.resolution_y

    #reshaping into image array 4 channel (rgbz)
    image = pixels.reshape(height,width,4)

    #get only depth
    z = image[:,:,3]

    #simulate depth sensor fov / depth range
    def clip_depth(z, z_near, z_far, default_value=0):
        if z > z_far:
            return default_value
        elif z < z_near:
            return default_value
        else:
            return z

    clip_func = np.vectorize(clip_depth, otypes=[np.float])
    z_near = 1
    z_far = 8
    z_clip = clip_func(z, z_near, z_far)

    #save depth to OpenEXR format
    image_settings = bpy.context.scene.render.image_settings
    image_settings.file_format = "OPEN_EXR"
    image_settings.color_depth = '32'

    #create an HDR image with name 'img_z'
    image_name = 'img_z'
    bpy.ops.image.new(name=image_name, width=z_clip.shape[1], height=z_clip.shape[0], alpha=True, float=True)
    img_z_clip = bpy.data.images[image_name]

    z_clip_rgba = np.dstack((z_clip, z_clip, z_clip, z_clip))
    img_z_clip.pixels = z_clip_rgba.ravel()
    img_z_clip.save_render('/tmp/blender_z_depth_clip_%04d.exr' % step)


text:
Cannot find camera after deleting and appending a new one with python
I run a background script that:

deletes everything:

override = {'selected_bases': list(bpy.context.scene.object_bases)}
    bpy.ops.object.delete(override)

appends a camera, a mesh and a light as object to the scene from a blend file:
with bpy.data.libraries.load(filepath) as (data_from, data_to):
    data_to.objects = data_from.objects
    print ("Objects added for map "+selectedmap+": " +str(data_to.objects))
sets the appended camera for the scene:

bpy.context.scene.camera = bpy.data.objects['Camera']

adds a bunch of cylinders
does a render of the objects in the blend file
saves the file:

bpy.ops.wm.save_mainfile(filepath=basepath + 'FPSPath.blend', check_existing=False)

then repeats again from, delete all
append another camera, mesh and light from a different blend file
render all again, but at this point the new camera does not seem to be selected as active, I do a bpy.context.scene.camera = bpy.data.objects['Camera'] after appending but, the render keeps coming back empty.

My print debug shows that the camera is changing name, (as camera.001 and so on) could that be the reason I am not getting anything on the render, is there a way to get any camera and then make it the active one?
Also the last blend file saved does not contain the camera, light or mesh objects I appended, should I add something else to the appending method? does it need anything else, the mesh object is never on the render, and only the first camera works.
Thanks.

Please provide more context, or it may be impossible to answer this question.

Sounds like you forgot saving the file after removing all objects as Sazerac mentioned, related: http://blender.stackexchange.com/a/27235/3710

I am using this to save: bpy.ops.wm.save_mainfile(filepath=basepath + 'map.blend', check_existing=False)

Another way would be to rename each of data_to.objects before "delete all again", If you don't want to save on each iteration.

the camera works now, I switched the method I was using to looping through all objects to find a camera and then set it as the camera for the scene: for obj in bpy.data.objects:
if ( obj.type =='CAMERA'):
bpy.data.scenes["Scene"].camera = obj

If the new camera is getting named Camera.001 then it is likely that the old camera is not being deleted, as blender appends .XXX (where XXX is some number) when the requested name is already in use. I'm not to familiar with all the python delete functions, but this could be because that data isn't actually deleted until the scene is saved and re-opened, due to how blender manages garbage collection/scene data.
You probably need to update your script to get the name of the new camera from ti after creation or assign a unique name to it when you create it, and the use that to set the active camera

to make the camera work I used:
for obj in bpy.data.objects:
if ( obj.type =='CAMERA'):
bpy.data.scenes["Scene"].camera = obj


text:
Correct way of using bpy.ops.import_mesh.stl bpy function?
First time here! So, I'm trying to create a python script that uses bpy (This script is not being used from within blender, but rather bpy is being called from python as a module), and in this script I am trying to import a mesh into the scene. However, I cannot figure out the correct usage of "bpy.ops.import_mesh.stl". I have the following block of code:
print("Importing mesh...")
bpy.ops.import_mesh.stl(filepath="Meshes/cm.stl")
print("Mesh imported!")

But when I try to run this code, this is what I see in the terminal:
Importing mesh...
Traceback (most recent call last):
  File "C:\Users\Browser\Desktop\blendTest\blend_mesh_test.py", line 220, in <module>
    import_stl()
  File "C:\Users\Browser\Desktop\blendTest\blend_mesh_test.py", line 11, in import_stl
    bpy.ops.import_mesh.stl(filepath="Meshes/mesh.stl")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Browser\Desktop\blendTest\myEnv\Lib\site-packages\bpy\4.3\scripts\modules\bpy\ops.py", line 109, in __call__
    ret = _op_call(self.idname_py(), kw)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: Calling operator "bpy.ops.import_mesh.stl" error, could not be found

In case it was because I was entering the filepath incorrectly, I also tried with the absolute file path:
print("Importing mesh...")
bpy.ops.import_mesh.stl(filepath="c:/Users/Browser/Desktop/blendTest/Meshes/cm.stl")
print("Mesh imported!")

But that just comes up with the same error:
Importing mesh...
Traceback (most recent call last):
  File "C:\Users\Browser\Desktop\blendTest\blend_mesh_test.py", line 220, in <module>
    import_stl()
  File "C:\Users\Browser\Desktop\blendTest\blend_mesh_test.py", line 11, in import_stl
    bpy.ops.import_mesh.stl(filepath="c:/Users/Browser/Desktop/blendTest/Meshes/cm.stl")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Browser\Desktop\blendTest\myEnv\Lib\site-packages\bpy\4.3\scripts\modules\bpy\ops.py", line 109, in __call__
    ret = _op_call(self.idname_py(), kw)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: Calling operator "bpy.ops.import_mesh.stl" error, could not be found

It doesn't seem like I'm calling the function correctly, and I have no idea what the problem could be. Would anyone happen to have an idea as to what I might be doing wrong? Thank you so much in advance!

Hello I'm not sure what you mean by This script is not being used from within blender, but rather bpy is being called from python as a module. How do you call the script then if not from within the Text Editor of Blender? Do you execute from command line like this? blender myblendfile --python myscript.py like this? Where the code is inside myscript.py or how do you execute your script then if not within Blender? Or is it called when you run an operator, perhaps from the File > Import menu?

It looks like the STL addon is not enabled in your session. If you have one of the more recent versions I suggest you rather use the (now builtin) operator bpy.ops.wm.stl_import : https://docs.blender.org/api/current/bpy.ops.wm.html#bpy.ops.wm.stl_import

@HarryMcKenzie , I complied Blender myself using the instructions on this page: https://docs.blender.org/api/3.4/info_advanced_blender_as_bpy.html
This allows me to use bpy from a python script I'm creating in visual studio and running from the terminal, without having Blender open or running from the text editor of Blender.

@Gorgious this works perfectly, thank you! I'll create an answer with your solution.

Happy to help. Cheers for posting the answer

Gorgious provided me with the solution in a comment beneath my question. The answer was to replace my function with a different operator, bpy.ops.wm.stl_import from this part of the docs: https://docs.blender.org/api/current/bpy.ops.wm.html#bpy.ops.wm.stl_import. My code now looks like the following:
print("Importing mesh...")
bpy.ops.wm.stl_import(filepath="c:/Users/Browser/Desktop/blendTest/Meshes/cm.stl")
print("Mesh imported!")

Which gives me the following output in the terminal:
Importing mesh...
Timer 'STL Import' took 11.92 ms
Mesh imported!

And I can confirm does in fact import my STL. Thank you, Gorgious!


text:
How to make a transition between 2 objects (between their materials, as in the picture)
I have 2 identical models of tractor, the first has a lot of materials. the 2nd has only one half-transparent material. how do I make the same transition (animation) as in the attached picture?

Hello and welcome. Please verbally describe what your issue is, be specific and and use relevant keywords. Avoid referencing images or links as alternative to words, try to stay away from vague references like "this happens", "issue with", "like so", which make the post impossible to find for someone using search. Instead describe what "it" is, be descriptive, succinct and detailed. It may not be immediately obvious to users trying to help what you mean. See What is the problem of asking “How do I do this?"

At first blush this is easiest to accomplish with two different complete renders and fade between the two videos in your video editor.  That way you don't have to render again for small changes.

Yup this looks like a simple usecase for view layers : render with material 1, render with material 2, use a gradient with an alpha over node to composite the two

You can use a Separate XYZ plugged into a ColorRamp as factor between your 2 shaders (transparent and opaque or whatever). Use the Mapping location value if you want to move the separation:


text:
Compositor scale node in 4.2
it seems as if this node has changed functionality between 4.1 and 4.2. For my purposes, I need to take an image and undistort it (lens distortion). This causes the image to run off the bounds of the canvas. In 4.1 I could just use the scale node to essentially "grow the bounds" of the canvas and get the whole image in view. In 4.2 I'm not sure how to achieve this. I can scale and then mix onto a larger image, but I'm still losing the parts of the image that are outside the bounds of the canvas.


text:
Most of object baking black? (2.8)
I have this model that I'm trying to bake to a texture:

But when I bake it, I get mostly black except for one diagonal brown square, like this:

I'm not quite sure what the issue is here. I'm using diffuse shader, when I'm using the glossy shader nothing shows up. Is there some reason why it's missing most of the model?
Here's the blender file:

Could you attach your .blend please by uploading it to https://blend-exchange.giantcowfilms.com/ and adding the link to your question?

Just attached the file


text:
Cycles: How to apply procedurally made material to a single face properly?
I have a procedurally made material that displays single digit "1" using Generated Texture Coordinate as input to Mapping.
Now I want to apply this material to a single Face.
With Generated it's not working (obviously because Generated coordinates represent the whole object).
So I tried to pick the necessary Face, Unwrap it to separate UV map, added UV Map Node to the Node Editor, picked that map and used it as input to Mapping. Material is shown incorrectly (partially). I've tried various scaling of the UV map, but still somehow I can't get all the parts of the material to appear on the Face. I've tried to play with Mapping Node by changing X and Z Locations - still no effect (however it does still shift X correctly). How may I solve it?
In short: I want my procedural digit to be shown on a single Face exactly like on a whole single plane. Thank you!
Update: here is how it looks. Left side = solid cube with material applied (Generated input). Right side = rectangle of few faces with material applied to single one).
Update2: All right, looks like I solved the problem. So the thing is when you switch from Generated mapping coordinates to UV Map former Z axis (in my case) becomes Y axis (presumably due to UV map being in XY plane), so I just had to substitute Y from SeparateXYZ Node as Z input to my "drawing" Node.
Thanks all who attended!

Share your blend file it seems, though, you need to rescale texture.

Have you tried assigning the material to a single face?

I did exactly that, I made up a vertex group for that face and applied material to it leaving the rest of the object with another material. Plus added that UV map representing face proportions (it's rectangular anyway).

Have you tried using a mapping node to adjust x,y,z?


text:
Cycles Nodes: problem combining two procedural masks for bump (fake displacement)
Struggling some problem here. I've made up a procedural node group representing a single area with gradient that can be placed anywhere on a cylinder's side. It works ok. When I combine (via Math Add Node) two-three-four etc. such node groups side by side it still works ok (I've tested it on any angles from 0 to 360 all the way around cylinder).
However, when I'm trying to combine (still via Math Add Node) two node groups with few of those areas each - to use for displacement (Displacement input of Material Output node) - the bump totally disappears.

1st Node Group connected to Displacement

2nd Node Group connected to Displacement

Their sum connected to Displacement
I wonder why that happens and how do I fix that?
When I use the same sum output as a Mix Shader Factor - it sums up as expected, see the last picture:

The Sum fed to Mix Shader Fac.
Looks like this happens when total angular difference between the very first element and that newly added reaches 90 degrees, but why? Thanks in advance!
Update: I separated large node groups into simpler ones and did some tweaks which allowed me to combine through all the range from 0 to 130 degrees so far. However, when I'm trying to add next area (centered, say, at 140 or 150 degrees) - all still disappears. Yet in Material Preview window it shows bump (!), but not in View itself or on render (see the picture below). All transformations to the cylinder are applied of course.
Any suggestions, why there is such a discrepancy?

Update2: I've checked the math, to me it looks ok (and it looks ok on any separate pyramid I test), there's something with combining them. Ok, all the chain before final add looks ok. Now step by step with our beloved Node Wrangler.
Final add (scalar, grayscale output):

- to me looks as expected.
Now we have to convert it to vector (since Blender 2.8) using Displacement Node:

- again, looks fair enough.
And now we connect the Shaders:

- and all disappears. It's still there in the material preview (see it on the right), but not on a real shape. It's happening in 2nd Quadrant (X<0, Y>0) but not when I enter it, nor when I'm exiting it, somewhere in between. I guess I'll try a whole other approach then, to go completely to cylindrical space (math will be a challenge, heh), but maybe it will be more general and will require less combining. And hopefully it will finally work.

May be totally dependent on your node setting... and it is not really described here.

Let us see the nodes or put the blend here to look at

Could be related to this https://blender.stackexchange.com/questions/112843/how-can-i-make-my-procedural-brick-texture-map-correctly-to-both-a-cube-and-cyli

Yep, thanks for the suggestions, problem is that that gradient calculation setup is quite more complicated than those on screenshots, I doubt anybody would like to dive that deep. However, I'll probably try to distill a simplest possible test case where the issue still exists (anyway I have to debug it somehow), so chances are I find out what I have missed. The very rough scheme looks like this: Generated -> Mapping (-0.5 for each axis to center the origin) -> Separate XYZ -> Math to get mask -> that math out supplied to Displacement/Fac. I never recombine vector back.


text:
Can't turn off x-ray mode
for some reason I can't get out of the x-ray or wireframe mode. I know to find the overlays button, but whatever I do, I can't get to see my object in solid mode.

Check Object Properties > Viewport Display > Display As  dialog. The Display As mode should be switch to Solid.


text:
How can I select a clip/slip/strip under the cursor(=timeline-indicator) via the keyboard?
I want to be able to do the simplest of editing (scroll through timeline, make cut, select clip, remove clip, go on) while not needing to grab the mouse, therefore only using the keyboard as input.
So far I have:
Alt+A play forwards
Alt+Shift+A play backwards (very slow for me)
←/→ move, 1 frame at a time
Shift+↑/↓ move, 10 frames at a time (configurable)
K split clip in two at the current location
??? select clip at the current location
X delete selected clip(s)
One can select a clip with RMB, which is bound to the "clip.select" function the shortcut editor. Adding a new keyboard-shortcut for "clip.select" did not work for me.
I found multiple candidates for what I want to do, but unfortunately none of them worked out:
"Strips to the right / left" seems to select all clips in the same row, and its not clear how it works (to the left/right of what? For some reason, not the timeline-indicator)
"Select more/less" (Ctrl++/-) seems to always start at the right, therefore I cannot select a clip which is between two other clips.
PS: It is possible to (re-)bind any item available in menus to a keyboard-shortcut by RMB on the respective item, but I have not found a matching one.
Info:
Blender 2.79b
Windows


text:
Rendering from at batch file fails on Windows
It's my first time trying to use a batch file so I can render lots of files over night but cant get it to work. Looked up several tutorials and none seem to work. Could you tell me what I'm doing wrong please?
Also, the file location is on the One-Drive cloud folder, should this make a difference?
cd "C:\Program Files\Blender Foundation\Blender\blender.exe"
blender -b "C:\Users\Andy\Documents\Buildings\Malvern\Sienna\Pavilion\8x8\layout_A" -a

Thanks for any help.

You are missing the file extension. The full name of the file is "layout_A.blend". So your command should be:
cd "C:\Program Files\Blender Foundation\Blender\blender.exe"
blender -b "C:\Users\Andy\Documents\Buildings\Malvern\Sienna\Pavilion\8x8\layout_A.blend" -a

many thanks! this fixed it