text:
Why does vertex merging cause non manifold geometry?
I am having issues with some non-manifold geometry.. I understand there are a few types or a few sources of non-manifold geometry, but I can't find the exact issue with my model..
I noticed most of it, if not all, was located where I merged vertices together. Why would this cause non-manifold geometry? I thought the goal of the merging process was precisely to make sure I had a unified mesh?
Here is the file in question, maybe I missed something:

Hello :). Merging vertices can still leave interior faces, or double edges. Please add some images (and perhaps your.blend) if you want more specific answers :).

Thanks for the response! There don't seem to be any interior faces and I have already tried to merge by distance to fix double edges but there doesn't seem to be any... How do I add my .blend to the post?

Hey :). You can try gdrive/dropbox or our local blend-exchange.

@JachymMichal Awesome, went ahead and did that

Your mesh contains flipped faces, which is considered non-manifold geometry.
It's probably not caused by merging vertices, and it's easy to repair

Select all faces
Go Mesh > Normals > Recalculate Outside
Done.

After this, there are still some non-manifold vertices on the outer rim, because the mesh isn't 'closed'.

Amazing. I thought I had already fixed those... Apparently I hadn't! Thank you for the help, cheers

Glad to be of help :). Good luck with your project.


text:
Using array modifier to array an object between 2 curves
I want to array the object I outlined with yellow between 2 red lines I've drawn here. I tried some of the array options to no avail. How can I do that?
It would be great even if you could just forward me to previous solutions for this one. I'm trying to make stadiums for FIFA and these objects are crowd meshes. Creating crowd meshes one-by-one is wasting a lot of time.
Thanks in advance, stay safe.

Edit: Actually this is what I want to do; Change scale of objects in array without affecting distance
but dupliframes are not included with latest Blender version.

You can use Array Modifier's Fit Length or Fit Curve options

Fit Length - specify a maximum length of arrayed objects (use the length slider)
Fit Curve - use a curve to determine the length (adjust the curve to control length)

Thanks for help, using fit length worked for arraying, but I also want them to be scaled around the red lines. How can I do that?

Actually this is what I want to do; https://blender.stackexchange.com/questions/40807/change-scale-of-objects-in-array-without-affecting-distance but dupliframes are not included with latest Blender version

Add en empty at the same position as your arrayed object, set the empty as the object offset in the array modifier, and scale the empty. Every iteration will be scaled by the same amount. You can scale either on x, y, or z, or any combination of axes

It seems like I have to research on adding empties. Are there any videos for that?

source: Stack Exchange

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

sort: votes


text:
Cast 2d image shadow on to my 3d object
Is it even posible? Hello everyone! I have placed a background image to my project and also a plane with an image as its material.

As you may see in the picture I attached (it is not in camera view), that the tree that you see next to a path I modeled has a the shadow I need to project (somehow) to my object.
Thank you so much for your time.

This could be done by duplicating the path, switching the original invisible while you trace the shadow's shape with the duplicate path. This will then be used as a shadow object (plane) to lay over the path but a whisker higher.  Switch the path back to visible and make the shadow plane semi-transparent. Colour it to match the shadow or even texture it with the original shadow section of the image.  Clear as mud?  If so, leave a comment and I'll have a go at this myself, am tied up at the mo.  There are other methods also. One being to organise a texture to apply to the path itself.

Hello, Thank you for your reply. I am going to try the duplicate object then trace shadow method you mentioned.

Good luck with that - I'll watch this space in case you're stuck at some point.

Hello Edgel, if I am using different layers on my compositor and (for example) I only have one camera that appears in the first layer, will that be the camera rendering at my other layers? Because I will always have to add a new camera at whatever layer I want to render from? right?

I ask because I don't see a camera in the layer I am working and when I press cero I can see my background image and the objects where I want them to appear on the render perfectly, but once I render the background image it appears in some other random side.

The rendering can only use one camera at a time. i.e. you have to switch between cameras.  When I commented, my mind was running along the lines of doing all that in the 3D window, and with just one layer and one camera and one single render.  I was thinking about this last night and feel the only way to explain it is to do it, show you here.  See if that suits you... (see below)

A footpath (pink) plane is laid over the background image to hide and replace the original path at the left side of the water.

Two shadow-shaped masks are then laid over that which cut through it to reveal the background image's shadows once more.

The masks are not fully transparent so they can be tinted pink.  The shadows then appear to be on the added pathway when in fact, they're on grey concrete.

Because the masks are to be selective, in that they cut through the added path-plane but don't affect the background image-plane, we render in OpenGL.  (See footnote)
If the masks do cut through the background, parent both to the background plane, then unparent them immediately. (use "keep transform" option in both cases)
See here - for more about this form of masking
-=============-
Footnotes -
An alternative would be to texture the masks with the background image and use the UV editor to scale and align the respective shadows.
-==============-
Another, is to use Blender's internal masking which will cut a hole through everything and require post processing.
Render the holed image (or lossless video) in .png format with an alpha layer. (the RGBA button at extreme right in the rendering properties' output tab)
Note that the output still includes the background image-plane.
Save the project and exit. Fire up Blender again and use the 'Video Sequence Editor' this time.
Lay the holed image/video over a COPY of the background image which is tinted pink to match the overlaid path.
The holed image will only allow the tinted shadows through.
-===========-
The post processing could also be performed using the Compositor.
All up, the easiest by far was to render in OpenGL and use it's masking, do it all in one go.
enter code here

Thank you. Did you read this question: .. if I am using different layers on my compositor and (for example) I only have one camera that appears in the first layer, will that be the camera rendering at my other layers? Because I will always have to add a new camera at whatever layer I want to render from? right?
I ask because I don't see a camera in the layer I am working and when I press cero I can see my background image and the objects where I want them to appear on the render perfectly, but once I render the background image it appears in some other random side.

I did actually answer that in a comment you may not have seen. (you have to click on "Show 1 more comment" to view it)  In that I mentioned that you can only have one camera active.  That's the viewpoint that will be rendered from.  Can I ask why you're using the compositor? Your question is only asking if the original shadow can be laid across the added path, the short answer being - yes, it can.

Your welcome - hope you managed the result you were after :)

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


text:
How to make a torus stay in a piercing hole while it moves aggressively
Can someone help me figure out how to animate a cube with a piercing hole and an inserted torus stay in place while the cube wiggles, scales and moves?
The image is showing the cube (shaped as a nose) the torus as a pendant (the pendant is comprised of two moving parts). each nostril has a set of separate parented bones. The pendant has three bones, a tiny one inside the piercing hole, the next two I have directly extruded from here. I want the nose to look as one that breaths and wiggles like jello. every time I use the wiggle bone fun it goes nuts. haven't figures it out. I want the droplet(the actual pendant) to use the wiggle bone too so it has the physical back and forth of the gravitating pull, I've applied it to the single bone affecting the droplet and it goes nuts. Also I want to rotate the entire cube so the torus and attached droplet moves with it.
Thank you!

How about a render

each nostril has a set of separate parented bones. The pendant has three bones, a tiny one inside the piercing hole, the next two I have directly extruded from here. I want the nose to look as one that breaths and wiggles like jello. every time I use the wiggle bone fun it goes nuts. haven't figures it out. I want the droplet(the actual pendant) to use the wiggle bone too so it has the physical back and forth of the gravitating pull, I've applied it to the single bone affecting the droplet and it goes nuts. Also I want to rotate the entire cube so the torus and attached droplet moves with it.

I am trying the Limit location bone constraint, it kinda works but the wiggle bone disconnects and sends the droplet everywhere. I have given the middle bone of the pendant an inverse kinematic constraint targeting the armature and selecting the droplet pendant, chain length 2,  this works fine but I haven't figured parameters . should I give bones to the piercing hole?


text:
Custom heatmap 3D texture
I have a 3D model constructed from photogrammetry. I would like to colorize this based on custom values on some vertices, and interpolate a heatmap for the rest of the mesh based on these values. I would like to either assign a max/min value to the vertices from which a color ramp is generated or do this outside of Blender and give the vertices RGB values from which the rest of the texture is interpolated.
Does anyone have a workflow or ideas on how this may be achieved?
Edit: I managed to acomplish this using the pyvista interpolate tool https://docs.pyvista.org/examples/01-filter/interpolate.html

You may be able to do this with vertex groups and then plugging them into a colour ramp from the shader editor. Let me test this for you, will give complete answer below soon.

Hmmm, it seems like you can't currently import the weights from vertex groups into the shader editor natively, but there is an addon to do it. https://blender.community/c/rightclickselect/Mkfbbc/

I quite didn't understand the meaning of your Heat map so I created a not-so-complex procedural material, which would consist of 3-4 nodes based on your heat map.

1] Depth Map : This map is based on height, if u want this kind of material then use the top three nodes
nodes

2] Fake Heat Map : This is a fake heat map based on distance from the
camera, a very common filter.

Ahh! I nearly forgot, you can also use the layer weight node to get
the faces facing the camera. Like This :

Feel free to play with the values


text:
Why are portal area lamps slowing down my renders?
I was confused when I added portals to my scene, and it actually increased (slowed down) the render quite considerably!
Here is the demo scene I used to confirm this: portal-demo.zip

portals disabled: 0:47
portals enabled: 1:36

Additional edits after original post
In the scene I'm working on, I created two renders to compare portal lamps enabled/disabled — the sample amount is adjusted to achieve the same render time — and I find that the scene with portals enabled looks considerably worse!

stage-render-portals.zip

This indicates to me, that in my scene, the portals cause the render to slow down, and ultimately produces a worse result.
Could this be, because my room has two rather large windows, and with a certain amount of "openness" to your indoor scene, perhaps the benefits of portals are outweighed by the costs?
(my previous little suzanne portal-demo.zip room seems more reasonable, perhaps because it has a much smaller window?)

I've found that when portals are enabled, the render is slower — however there is considerably less sampling noise.. to achieve the same level of noise with portals disabled, one must increase the sampling so much that the render time overtakes the portals-enabled scene — that is, portals slow down your render, but manages to "wring" out more bang for your buck for the same number of samples, and is thus worthwhile — TLDR portals let you lower the number of samples and achieve a faster render that way

While my above comment appears to be true for the portal-demo.zip scene I provided, it appears to me that there is a limitation on the usefulness of portals — they seem to have diminishing returns when the "openness" of your interior scene reaches a certain threshold — that is, in my scene with very large windows, portals appear to actually slow down the render and degrade the quality of the image (adding more apparent noise)

Yes, but all of the above has been stated before and is partially included in the manual. Use portals sparingly and only when the window is rather small.

@Leander — thanks for including a link to the relevant area in the manual. It says portals aren't good for "outdoor" scenes, but that's fairly vague and I consider my scene rather indoors — for those who may be curious, my scene where portals are detracting from quality is a roughly cube-shaped roomm where one whole wall is simply open to the outdoors, and there is also an open doorway in an adjacent wall — this amount of "openness" seems to be about the crux point where portals are no longer worthwhile

Portals have limitations — it depends on how "open" your scene is
As mentioned by @Leander, the blender manual says that portals are not good for "outdoor" scenes.

portals lamps provide diminishing returns as your indoor scene becomes too "open"
in other words, if your indoor scene has several very large windows, you may be better off without using the portals (because the cost of portals starts to outweigh the benefits)
in my experience, I found portals to be unfit (by a narrow margin) for an indoor scene where I have a room with a whole wall basically missing (huge floor-to-ceiling window), and also an open doorway in one of the intact walls (think of a garage with the big door open, and also a side-door open too)

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


text:
How to change edit material assignments after joining meshes
How can material assignments to a joined mesh be changed after the meshes are joined?

Example:
Create a scene with a cube and sphere.
Assign material #1 to the cube and material #2 to the sphere.
Select the cube and the sphere, using crtl-J join the meshes.
The result is shown below.

The material panel for this joined object shows both materials.

If edit mode is entered, the there is an assign, select, and deselect option, but its not clear how to use this to change the mesh material assignments.

What is the procedure to change the material mesh assignment? For example, how is the red material assigned to one face of the cube?

Example blender file:

When you are in edit mode, select the faces you want with the red material, then in the material tab select the red material and click the assign button, the faces which you had selected should have the material assigned now.

Ah! Using the faces in edit mode does it. Thanks.

Ah I expected more complications! Im going to paste that comment into an answer so you can properly close this question.

When you are in edit mode, select the faces you want with the red material, then in the material tab select the red material and click the assign button, the faces which you had selected should have the material assigned now.

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


text:
How can edge loops move independently and stay connected?
I have two edge loops that are moving in an animation. The edge loops are different in shape and number of vertices. The animation below shows an example of the edge loop shapes and their movement.

Using 'bridge edge loop', I can generate a geometry that blends between the two shapes, but it is not obvious how to animate it so the edge loops can be animated.

How can this geometry be animated so the edge loops can move independently and stay connected?

Which of the following have been attempted? Armatures, Proportional Edit, Shape Keys, Manual or Distance Weight Painting, Separating Loops in Edit Mode as copies.  I may not understand the question.  Perhaps others do. Perhaps another picture of your attempt would clarify.

A suggestion is to change the title of your question to something like the last sentence of your current writing .... How can this geometry be animated so the edge loops can move independently and stay connected?

Animate the bones of an Armature in Pose Mode.

Above is quick armature which you can greatly improve.
An armature modifier was created.
The master bone has deform disabled.  The other two bones deform the mesh.
A vertex group is selected to show weights.

Bendy bones should be worth the try in this case.


text:
Convert animation node result into editable object
Is there a way to convert an animation nodes result into an object?
For example, animations nodes are used to generate the face of a clock. I want to convert that result into an object that can edited. Is there a setting or procedure that will do this conversion?

Most of the time you can simply copy the output of Animation Nodes in the viewport and continue to work on that copy. The node tree that created the object can be deactivated.


text:
How to create a mesh from metaballs which will always work with a Boolean modifier?
My goal is to simulate a particle system in an animation, convert the particles to a mesh, then apply Boolean modifiers to the result mesh. This usually works. However, the mesh generation occasionally results in non-manifold elements which cause the Boolean modifiers to fail. The question is if there is a way to ensure that meshes generated from meta-elements will be a manifold and not contain non-manifold vertices. An idea solution solves the problems by

explaining how to generate the mesh without non-manifold elements;
explaining how to remove the non-manifold elements using a feature in blender; or
explaining how to use scripts to remove the non-manifold elements.

Manual editing of the mesh is not an option since thousands of meshes will be generated.
Details
Using Blender 2.76, the particle system consists of several thousand particles.
The particles are converted to a mesh by a script which runs on each render event. The script creates a metaball for each particle, then converts the metaballs to a mesh. This works fine. However, the resulting mesh occasionally contains non-manifold vertices. The non-manifold vertices can cause Boolean modifiers to fail.
Is there a way to either generate the mesh or modify the mesh to ensure that the all vertices are on the manifold. Manual editing is not an option since thousands of these meshes will be automatically generated in an animation.
Example:
This image shows the particle system during an animation:

This image shows a rendering of the meshed particle system:

This image shows the meshed generated from the particle system with non-manifold vertices identified. From the top of the image, 2-vertices are identified as non-manifold.

To see the issue with the mesh, this a zoomed version to the problem area is highlighted.

An example of a successful Boolean modifier applied to the mesh:

Update based on comments.
From testing with cubesurfer 0.95cubesurf 0.95 and Blender 2.76, the meshes generated are not always manifold.
Example:
For the same problem, here is the resulting cubesurfer surface.

This is the resulting mesh.

When selecting for non-manifold vertices, these are the non-manifold vertices and surrounding geometry.

Zooming in, these are the non-manifold vertices up close

perhaps a crazy solution (but might work) is to write a script to convert the particle locations per frame into a .pdb, and then send the pdb to PyMOL (a program that creates manifold surfaces by passing a solvent radius (ball radius) and surface quality (triangle density) . then import the resulting surface. PyMOL is pretty fast. https://github.com/MonZop/BioBlender/blob/master/BioBlender2.py#L1589-L1607

There is CubeSurfer addon for meshing sph particles. Metaballs in Blender were very slow, but they were optimized recently. It is worth testing which is faster.
I don't know if CubeSurfer guarantees manifold mesh. But I am 99.999% sure that it doesn't. Now 100% sure after your test.
I dealt with similar thing many times (booleaning fluid mesh to have smooth surface where it collides with glass - so it renders nicely).
The solution is to export the fluid mesh in frames where the boolean failes as .obj files, then manually edit those meshes so they are manifold, and substitute them in frames where the boolean failed.
The detection and exporting can be done automatically. Also the substitution if the files are named to indicate which frame they belong.
I don't know any algorithm for blender that can automatically fix a non-manifold mesh to be manifold. It would be quite complex, as it is not an easy task.
There is this paper about it, uses Cutting and Stitching.
The boolean modifier will not fail on every non-manifold mesh, only when the non-manifold piece intersects or is inside the booleaned mesh.
Also putting a smooth modifier before the boolean might cause the boolean to fail less. But it won't fix all the non-manifold problems.
So to solve it you would have to write your own particle mesher that guarantees manifold mesh. Or to hire someone to do it for you, or find a very good soul to do it for free. It's quite a job to do.
Or use a program that can do booleans on non-manifold geometry (which is totally possible, blender just uses open-source library for booleans that is not able to handle non-manifolds) or which can repair non-manifolds. Some programs that could do this are listed here.

Geometric Modeling Based on Polygonal Meshes
...this package provides source code implementing useful repairing algorithms such as Gueziec et al's cut-and-stitch for conversion to manifold (IEEE TVCG 2001)...

Also MeshLab is a nice package worth trying. It can be scripted for automation. With others I have no experience but they might be even better candidates. You just wan't them to be able to process a series of obj's.

Another approach you could take is not to boolean at all, but rather use a volumetric material with very high density with clipping. You just need to figure out the math that clips, depending on the shape you want to clip with. From your pictures looks like you need to cull with 2 planes, the planes face the camera with the local Z axis:

This though produces some wood-like artifacts:

Re "Metaballs in Blender are very slow." - They had an optimizations recently https://www.mail-archive.com/bf-blender-cvs@blender.org/msg61841.html

@ideasman42 True, forgot about it. Didn't test the new speeds against the cubesurfer, will edit it. Thanks


text:
Fastest UV unwrapping techique for very large mesh
I have a mesh which is generated by another program with 100's of thousands of faces. I'd like to UV unwrap this mesh. All of the unwrap options take a very long time. So long that I'm quitting Blender before they complete. Which unwrapping method should finish the fastest?
The surface is created from an airflow simulation and is an iso-surface from a 3D flow like this:

It could be that it would depend upon the mesh and the desired UV layout.

Can we get more info here? Such as what is the subject that you are trying to unwrap (a large scan data dump from something like meshlab), can it be simplified 1st (can you live with less info), etc... I personally do not know how to benchmark the methods of UV unwrapping, however some her on BSE may get you to your ultimate desired end result.

The UV mapping is for baking colors to vertices, then using the colors to decimate the mesh. The UV mapping can be relatively poor as long as all vertices are mapped. Because of the mesh size, I need the fastest method that can be used on the mesh.

The mesh is an iso-surface from an airflow simulation.

@EdTate,  Check this link, and see if the Z-Pass method would seem to help you.

The Z-Pass method looks interesting. However, its not clear how to use it with a non-planar object. The mesh is like a very lumpy tear drop.

One thing I omitted to mention in my earlier comment is that the answer may be influenced by your hardware. What processor, and how much memory you have installed.

I can't help thinking there's probably a better-suited method than UV texturing for getting color onto your model. Also, will this be animated? If so, is this thing changing shape with each frame? Will the viewing angle change in the animation? These are considerations when deciding how to color a model.

The built in automatic method that takes the least time to complete is almost always "Unwrap." For a simple mesh of 300,000+ polys, it took about 10 seconds. "Light map pack" took about 20 seconds, and "Smart UV Project" took longer than 1 minute.
For your mesh, I don't doubt that it will take longer, but it shouldn't be hours (I'd think). It may actually help speed up the process to mark some arbitrary seams. If you can, select two points, then choose Select -> Shortest Path. That will give you a contiguous line of edges that you can then mark as a seam. Mark a couple of seams lengthwise to split it into dorsal and ventral halves, then maybe even into quarters. Splitting things up this way, usually helps "Unwrap" work faster, but doesn't have any effect on any of the other methods.
Hope that helps!

The only thing I've found to actually work for me is to use a package called SimplyGon to remesh the stuff in an intelligent way.  Everything else has failed me.  There is a free license


text:
How to use Geometry Nodes (GeoNodes) to rotate an object so parenting and constraints work
I'm starting with a rigged engine model and would like to use geometry nodes to drive this model. The model works by rotating the crank shaft and using a combination of parenting and constraints everything else follows.

I'd like to use GeoNodes to do some calculations, then set the rotation of the the crank object.
I tried using the following GeoNodes setup, but it does not rotate the object. It just moves the mesh.

How can I set the desired rotation using GeoNodes and have it drive a rigged model?
The model is located here -
Note original rigged engine model obtained from BlendSwap - https://blendswap.com/blend/14129

Thats not what Sample Index is meant for. Its meant for getting a value from a specific geometry element index, like a specific vert or face etc. You want the rotation of the input geometry to be driven by the x rotation of the object in the Object Info node?

The left half of the geonodes is based on spreadsheet importer pluging (see https://github.com/simonbroggi/blender_spreadsheet_import). The index is how the CSV values are referenced in that plugin.

GN works in the "realm" of Edit Mode, not in the realm of Object Mode. This means that you can change the mesh (number of vertices, edges, faces ; position of vertices ; materials ; ...) but you can not change the origin position in world coordinates, neither rotate the object local axis. You can only move the vertices such that they are at the position/orientation you are expecting from the origin and axis of the object to which the GN modifier is attached.

(Using Blender 4.2.1)

This proposal is an adaptation of the post Passing GeoNodes attribute to Shader frame offset.

Approach
One way to proceed is to set up 3 parts:

The original object (named "@Crank") with no GeometryNodes modifier, but instead with a Driver controlling its property Transform - Rotation X.
A single vertex mesh (named "@Crank Coder") whose X position is set by the GeometryNodes modifier originally attached to the "@Crank" object.
An Empty (named "@Crank Driver") making the communication between the two previous objects

by copying the "@Crank Coder" position (read/pull/receive),
by providing the value of the rotation angle to the "@Crank" Driver (write/push/send).

Crank Coder set up

1. In Object Mode, add an object made of one vertex using the menu entry Add>Mesh>Single Vert>Add Single Vert. Its position is irrelevant. Because only one value is coded, one vertex is enough.
2. Add a GeometryNodes modifier to this object. Then copy & paste the nodes of the original "Move crank" graph.
3. Replace the Transform Geometry node with a Set Position node.
4. At this stage, the X coordinate of this vertex is equal to the targeted angle of the crank shaft animated with the Frame number. However, it is to notice that only the position of the vertex is updated. The object's origin remains at its creation location defined at step 1. To use this vertex as a moving point in the definition of a constraint, the documentation explains that "(...) the constraint will target the median point of this vertex group instead of the object’s origin".
5. Consequently in Edit Mode, in the Object Data Properties panel, add a Vertex Group (named "Crank Coder") and Assign after selecting it the single vertex to this group. With only one point, the group median point is this point.
Crank Driver set up

6. Add an empty object using the menu entry Add>Empty>Sphere. Its position is irrelevant.
7. Add a Copy Location constraint to this object. Set the Target to the "@Crank Coder" object created at step 1, then the Vertex Group to the "Crank Coder" group created at step 5.
8. At this stage, the animation shows the empty sliding along the X axis, colocated with the moving vertex.
Crank set up

9. In the Object Properties panel, press RMB over the Rotation X property then select the menu entry Add Driver.
10. In the Drivers Editor, rename the variable to "angle" for example. Set the empty as driving Object (i.e. "@Crank Driver" here).
11. Check that Type is set to "X Location" (the coordinate chosen to encode the crank shaft angle in the GeometryNodes modifier at step 3), and that Space is set to "World Space".
12. Play the animation.
Resources
(Blender 4.2.1+)


text:
How do I open .blend files AND activate scripts via code?
I want to make a program, in Python or C++ likely, to carry out batch script functions across multiple .blend files. So how do I open a .blend file and have it auto-run a script (the script is already in the .blend file), without having to do anything manually?
Edit: I am using this command line: Marie.blend --python test.py
I am using this script (test.py):
import bpy

scn = bpy.data.scenes["Scene"]

scn.frame_end = 10

The script works when run 'normally', but when using the command line, the file just opens and the script is ignored. (Auto.run has already been enabled)

Take a look at command line arguments in the manual.  The python options sections shows how to invoke a python command at run time.  You can also register scripts to run at start time.  See this question for details.
Two important notes, uncovered from our discussion:

On systems like windows, where you can invoke Blender from the command line by naming the blend file (ie > Marie.blend) the --python argument will be ignored.  On such systems you must invoke Blender by name and the --python argument must go before the blend file name.

Scripts invoked at startup are run before everything is initialized.  You need to wait for initialization before your script will work.  I'll update the answer later with a technique for that.

I never used command line arguments in coding. How would you send a certain command line to Blender from another program, say, a C++ program?

That would depend on the OS.  In Unix-like systems you might call system. The system man page would explain the arguments.  There's something similar for Windows.

ARGH How do I do this?? I got this, it opens the file but does not run the script:
import os
cwd = os.getcwd()
filepath = '"Marie.blend" --python Text'
os.system(filepath)

Sorry, the comments will not let me do line breaks...

Is the script an external file or is it a text block inside the blender file?  For an external file you need to pass system the equivalent of blender --python filename.py but for a text block use blender --python-text textname  I suggest getting the command to work properly from the command line first; and then when you're sure it works write the C++ code to invoke system.  Also, remember that you have to have 'autorun' enabled in preferences to be able to run scripts.

Marie.blend --python test.py will not work for me. It opens the Marie.blend file but does not run the script. I tried an internal script, too, with Marie.blend --python-text Text but still nothing happened. The script does not run. Auto-run is enabled in settings.

Do you have the python in a separate file or is it in a text in the blend file?

Let us continue this discussion in chat.


text:
Rigging - Copy Constraints in Version 2.80 and above
Many changes have been made since 2.80 came out.  How do I copy constraints from one bone to another in versions 2.80 and above. using a keyboard shortcut as in 2.79 and below?

Does this answer your question? How to copy constraints from one bone to another? Pose > Constraints > Copy Constraints to Selected Bones

I think the OP is looking for a replacement for the CTRL-C shortcut for copying bone constraints.  (It's used by a lot of tutorials.) They just need to enable the add-on.

Since the accepted answer is not in the question listed as a duplicate, I'm voting to reopen.

In 2.8x and 2.9x you need to first enable a built-in addon, Interface: Copy Attributes Menus in preferences:

Once that's done, to copy constraints:

Enter pose mode
Select all of the bones you want to copy the constraint to
Add the bone you want to copy the constraint from to the selection
Type Ctrl+C to bring up this menus:

Select Copy Selected Constraints  When you do a menu will pop up showing all of the constrains on the source bone:

Select the constraints you want to copy and click OK


text:
How do I measure the length of a selected edge with Python?
Which operation would I use to acquire the length of the edge I have selected so that I could store that in a variable for later use?

It's the distance between its two verts. If you're using bmesh, there's a calc_length member.

In the simplest form, if you don't want to use bmesh, or any vector operations you can use
import bpy

object = bpy.context.active_object
mesh = object.data
for edge in mesh.edges:
    if edge.select:
        v0 = mesh.vertices[edge.vertices[0]]
        v1 = mesh.vertices[edge.vertices[1]]
        x2 = (v0.co[0] - v1.co[0]) ** 2
        y2 = (v0.co[1] - v1.co[1]) ** 2
        z2 = (v0.co[2] - v1.co[2]) ** 2
        length = (x2+y2+z2)**.5
        print(length)

replacing the print statement with whatever sort of storage you want.
This assumes that you have an active object and it is a mesh object.  It will print the length of every edge that is selected.
See the manual entry for Mesh for details, but simplified, this searches all of the edges in the mesh and for each selected edge find the distance between its two vertices.  That distance, of course is the length.
Note: as pointed out in the comment you can simplify the length calculation.  I wrote it out in full just to show the relationship between edges, vertices and coordinates.  The simplified version of the for loop is
for edge in mesh.edges:
    if edge.select:
        v0 = mesh.vertices[edge.vertices[0]]
        v1 = mesh.vertices[edge.vertices[1]]
        print(f"length of edge {edge.index} = {(v0.co-v1.co).length}")

No transforms are applied.  As mentioned in another comment, to apply transforms to get real world coordinates, replace the print statement with something like
co0_t = object.matrix_world @ v0.co
co1_t = object.matrix_world @ v1.co
print(f"length of edge {edge.index} = {(co0_t-co1_tt).length}")

where @ is the Python matrix multiply operator
Using bmesh is a bit simpler:
import bpy
import bmesh

object = bpy.context.active_object
if object.mode == 'OBJECT':
    bm = bmesh.new()
    bm.from_mesh(object.data)
else:
    bm = bmesh.from_edit_mesh(object.data)

bm.edges.ensure_lookup_table()

for edge in bm.edges:
    if edge.select:
        print(edge.calc_length())

The same caveats about there being an active object that is a mesh holds.

Can get Mesh edge with (v0.co - v1.co).length.

Yeah.  I decided to write out the brute force version just to show how vertices and edges relate.

You might want to use obj.matrix_world @ v.co to get real world coordinates if your object has unapplied scale or is parented to an object with unapplied scale

Thanks a bunch!


text:
Array Modifier that creates Instances instead of duplicates
Let me know if I'm incorrect here.
When I press Alt–D I create an instance of an object. My triangle count don't change though.
When I press Shift–D I create a duplicate of an object. Triangle count goes up.
When I create an array modifier, are the cloned objects instances, or duplicates?
If so, how do I use the array modifier to produce duplicates without producing additional geometry?

When I press alt + D, I create an instance of an object. My triangle count don't change though.

Incorrect! You don't create an instance, though you have the right to mean something different by the word instance - still, AltD is an operator that creates a new object wrapper for the mesh (in your case). It is a linked copy, everything is linked to the same data as the original object, including its mesh (so it makes some sense to call it an instance of the mesh, but not the object). The triangle count of all your meshes doesn't increase, because you didn't create a new mesh, but the displayed triangle count of course does increase.

When I press shift + D, I create a duplicate of an object. Triangle count goes up.

Correct! You Duplicate the object, which also duplicates a mesh associated with this object.

When I create an array modifier, are the cloned objects instances, or duplicates?

Neither. The Array Modifier doesn't duplicate your object as if you pressed AltD or ShiftD in Object Mode. Instead, it duplicates it as if you pressed ShiftD in Edit Mode. You don't produce new meshes or objects this way, you also don't modify the Mesh data until you apply the modifier.

If so, how do I use the array modifier to produce duplicates without producing additional geometry?

You can't. You can use Geometry Nodes instead, or Instancing (first link) - basically, instead of using an array on your object, use it on a single vertex or a plane, and then set that vertex/plane object to be an instancer, and parent your object to that instancer. If you don't want to actually use instances, you can then (even without applying the Array modifier) select the instancer, F3 Make Instances Real. This will produces deep-linked objects using a single mesh (as if you used AltD)

When you create the modifier, but have not applied it, there is only one object.  That object contains multiple duplicate copies of the original mesh, and you can only edit that mesh.
When you then apply the modifier, there is still only one object but the individual meshes are no longer duplicates, they are each individual meshes that can be edited separately.
When you then separate the object by loose parts, you have N individual objects, each with its own mesh.  They are not duplicates of each other.  Note: If the original mesh had separate islands, like Suzanne's eyes, mentioned in a comment, then each island becomes a new object, so you lose that grouping as well.
You can make the new objects all have duplicate meshes of the original by selecting all of the objects, choosing the original last, and they typing Ctrl–L and selecting link object data from the popup menu, but this will move all of the duplicates to the same coordinate as the original and you will have to move them apart again.
There isn't a method to relink the meshes without moving the copies.

relink the meshes without moving the copies - the missing step is to press F3 and type set origin to geometry, but this only really works if the original geometry had its origin in the center of mass... Also, Separating by lose geometry won't work for Suzanne, as  has unconnected eyes. You could use a trick with geonodes like so https://i.imgur.com/aMzxfXf.png to then separate by material, but obviously it's problematic if you want to use some materials...But then again if you Ctrl+L to link the data back to the original, it doesn't matter...

Yes, I oversimplified, ignoring objects that were originally multiple meshes.  Updated to note that


text:
Is it possible to make an afterimage (multiple exposure) like effect in EEVEE 2.9?
I'm trying to make an afterimage like effect, don't know if that's actually what its called, but can't figure it out nor can I find anyone talking about it, at least for EEVEE. I've tried particle system and an add-on called magic trails, but it's not working. It needs to work with armature.
Blender 2.92 and EEVEE

Looks for me like you could make it with just copies of your object with the same animation (with some time difference) and different color/saturation/alpha values

I'll save that as a last resort. I'm trying to find a more effective, procedural and time effective way.


text:
Why do my lamps require an insane "strength" value of 1 million?

recently, I was using mesh planes to emit some light, and they had a strength of 8.0.. this worked well
now, I want to swap these out for area lamps (to improve performance)
i've positioned these area lamps in the place of my emitter polygons
i've scaled them such they have 1.0 transform scale, and in the lamp settings, I set the size to 1m across (to size-match the previous emitters)
the problem is, the lamps require a crazy "strength" of at least 1 000 000 (one million!) to produce any reasonable amount of light... this seems bonkers!
point lamps, area lamps, and the others, are all effected
my scene is scaled using the Centimeters preset.. the foreground is only a meter a way, and the more distant background is more like 5 meters back
i've paid special attention to the sizing and scaling of this scene, I can't figure out why the mesh emitters are working with a sane Strength of 8, and the lamps require something out of this world? something must not be right...

Edit: Remastered scene corrects scales, problem persists

stage-crazy-lamps-2.blend

i've remastered the scene so that all of the objects have a proper scale factor of 1.0
this should correct any sizing discrepancy/confusion
my scene must be in centimeters preset, all my other work is in centimeters
the area lamp size is now definitely 1m, as highlighted in the above screenshot (and it is not affected by the 1.0 transform scaling factor, also highlighted (I also verified the delta scale is also 1.0))
despite correcting the scaling of my scene, strength 1 000 000 is still required
is blender simply not accounting for my scene's Unit Scale setting?

Your scene is very large, it like trying to light a football stadium with a torch. For large scenes you must use a sun lamp. I found that at 1 metre with strength at 10 it lit the scene so that every object was visible. If you use an area lamp you will be forced to use values for both size and intensity. I can upload my results in the answer section if you like.

@NickBosse — thank you for pointing out the scaling issue in my scene — I have now remastered the scene to correct the sizing altogether, however the issue still persists — please see my edits on the original question, as now the scene is correctly sized in the eyes of blender's ruler tool and other measurement systems — I am beginning to suspect this is a simple blender bug where the scale/strength of lamps is not correctly factoring the scene's Unit Scale setting, which is vitally important for my purposes

Cycles lamps do not respect the scene's "Unit Scale" at this time
Bug report filed here (Blender 2.79)
Workarounds

Use mesh emitters instead of lamps

mesh emission 'strength' correctly factors the scene's unit scale
you can position and size a polygon to match exactly an area lamp, and even set up some nodes to have it express light in only one direction (to better emulate the area lamp)
for point lights, you could use a small sphere to achieve a similar workaround

Use "meters" unit scale for your scene

cycles lamp strength assumes you are using the "meters" unit scale, so if you are using that unit scale, the problem doesn't affect you

Just roll with one million strength (correct for unit scale yourself)

create a node group which corrects the strength scaling for you, allowing you to input 10, and have it multiply that by 100 000 — if you have to change your scene's unit scaling (not common), you'd only have to manipulate the 100 000 coefficient in your node-group

@cegaton — you're right, that's workaround #3 — the issue with the bug isn't that I can't get the results I want — it's that the results aren't consistent between scenes with different unit scales (despite the sizes being identical according to the measuring tool) — looking into this bug further, it appears blender has several features which don't account for unit scale properly, probably because the scene unit scale concept is one of the newer additions to blender — blender probably needs an internal audit for its own support of 'unit scale', for example, linked objects should be adjusted for

Your area lamp is not 1m across, it is 100m in size, hence the strength required.
Your Blend file seems to have pretty messed up scaling factors, for starters your viewport has a clipping distance of 50µm which is causing all sorts of display precision issues and Z-Fighting.
Your whole scene is huge in reality, most objects are several meters high, have very high scaling factors, and your room is more than one kilometer long.
Most problems probably stem from the fact that your whole scene has a Units Scale factor of 0.01, which is giving you a false sense of scale, and falsely reported units value
Go to the Properties Window > Scene > Units > Units Scale and set the value to 1

Taking your suggestion, I've remastered my scene such that all of the object scaling is corrected. Unfortunately, this doesn't fix the problem. I must use a unit scale of 0.01 which is the blender preset for Centimeters, because all of my work is modeled in centimeters (it's rather small stuff). This shouldn't be an issue, as blender accounts for the scene's unit scale regarding measurements expressed in meters, etc — I have now edited my question, adding a screenshot highlighting the corrected scaling, demonstrating that the problem still exists

I've also just now measured my corrected scene with blender's Ruler tool, verifying that blender reports the size of the area lamp to be 1m across (or 100 cm) — however the problem still persists as 1 million strength is needed

Cycles Shaders don't take Unit Scaling into account, nor does scaling an object change the shader values, so if you use anything other than 1m and don't scale your scene properly so 1 Blender Unit = 1 m you will face this issue

scale your scene properly so 1 Blender Unit = 1 m — you are passive-aggressively suggesting that it is wrong to correctly use Blender's Unit Scale feature at all — this situation where "strength 1-million is required for a 1m lamp" should be rightly considered a bug in cycles shaders — cycles should be accounting for the blender-configured scale — if you really think this isn't a bug, and that I must redo my scene to the Meters unit scale preset, then you're arguing that any usage of Unit Scale is a mistake, and that the blender feature itself is not implemented correctly

most importantly, every other blender feature respects Unit Scale, for example, the ruler tool — my scene is about 6 meters across and is lit by a 1 meter light —  the strength should surely be consistent with these measurements, and have no bearing on the level of precision I am working with — a scene that measures consistently should render consistently — this is clearly a bug in cycles

ultimately, my mesh emitter, a square polygon of 1m, requires only a strength of 10 — this is the same size as the area lamp, but the area lamp requires 1 000 000 — this simple inconsistency illustrates how this isn't just Cycles ignoring unit scale, it is specifically a bug in cycles lamps — since the mesh emitter works correctly, accounting for unit scale

This is so wrong. While size does increase the area of which light can affect, it divides the amount of Emission value and spreads it across the lamp, so that each area will give an even amount of light. For example, Size 1 with Emission 1 will give the same amount of light as Size 100 and Emission 100, it will only affect a larger area. Therefore having the emission value higher than the size will make it  give more light.
It is not a bug, it is just the lamp.

what should be the correct lamp strength to reasonably light a 6-meter wide scene, with a 1m area lamp? — I argue it certainly shouldn't be one million, and even more adamantly, I argue we must not consider my correct usage of blender's unit scale feature to be a mistake — blender should respect its own scale configuration in all cases, as it does with the ruler feature and every other feature — cylces should not be the sole exception to the blender scale configured for a scene, it's purely inconsistent

if cycles is the only blender feature which ignores Unit Scale, then it's impossible for me to work with consistent Strength values in scenes where I'm working at different levels of precision — it surely cannot be right for a 10m scene to require a million times more strength than the exact same scene scaled at the exact same metric values — blender reports an identical measurement, and given the same strength value should render an identical scene

i've found that a mesh emitter of identical size needs only a strength of 10 — this illustrates the bug only affects lamps within cycles


text:
How to make an object move on a Mobius strip?
I have Mobius strip and a sphere. I want the sphere to move on the strips surface, like on a path. How can I do this?
I've tried drawing curves, but I can't create the whole path at once and I've tried joining drawed pieces but the sphere moves just on the first drawed curve. I've tried joining two circles but also the sphere goes just on one of them. There is a way to create a mobius nod directly but it doesn't match the shape and I can't make it match. Can I somehow draw the path by code?
I'm very new to this so if there's an easier way I would appreciate it.
Tryed making edges the path, didn't work.

Create a Bezier Curve. Open it (it shouldn't be closed). Tilt one end 180°. ⎈ CtrlT
The Curve should resemble the twist of the moebius strip.

Add a Follow Path Constraint to the object. Check Fixed Position and set a key with the offset at 0 and 1.

Select the created keyframes and make them linear. T > L
Then make the graph cyclic. ⇧ ShiftE > Make Cyclic
Set a key on the first frame of the rotation. I
Set a key after the second keyframe of the offset on the rotation with the object rotated 180°, making it ready for the second circulation.
Set the new keys to constant interpolation. T > C

Wheeee!

My main problem is to draw the curve to the shape, so that the object would go on the center of the strip. Maybe I can use segments from your answer. Thank you anyway. : )

@K.D. or rebuild the strip using a curve combined with a mesh with the curve modifier.

I don't know what curve modifier is (newbie), but I can maybe make it thinner if that is what you meant?

@K.D. Not quite, but if your problem persists, edit your question to add more detail, describing what you mean by the object would go on the center of the strip or ask a new question and mark this one as solved.


text:
How do I clear the normal map seams even though I painted over the texture?
UPD: The answer was that I had to set the normal map as Non-color.
I have an altar model that I want to texture. I have visible seams, but I paint over them. It appears correct when a map is in the Color node (diff/normal). I save the painted over image, but when I reload as Normal Map Color node, the seams are there, and they are pretty obvious. I've done the same with the normal map (just smudging the seams but it does appear seamless when the map is in Color). Any clues?

Seams in the normal map are caused by usage of UV map when calculating tangent space, see https://blender.stackexchange.com/questions/16354/why-normal-map-baking-break-at-uv-seams. In general they shouldn't be painted over.

The seams are being caused by some problem in the implementation of the normal map, or by some problem in the baking.  There aren't any details for either of those in this question that would allow us to diagnose which.  I realize this is now 5 years old and that the problem is long resolved or abandoned, but I'm voting to delete this question because of a lack of details necessary to resolve the problem.

Open it in GIMP.
Filters > Map > Make Seamless
File > Export As > Whatever_you_want_to_call_it.png
Export > uncheck everything > Compression level 9 > Export
Load this normal map w/ node editor, in place of the original.

It may soften the details.  If that happens, load original as a new layer > select all > feather a decent amount > then delete, so it has crisp details inside, and a seamless outer edge.

The feather amount will depend on your normal-map size.  30 or 50 pixels may do.

My map is not a seamless one, it's one exported for a unique prop. It uses unwrapped UVs that do not go past the edge of the image.

I know it's not seamless.  Gimp can fix that.  It blends the edges so they line up when it wraps.

It creates an interesting solution, where it doesn't actually add up (the edges do not line up) but it is really soft, so there's no visible seam. It'll have to do, thanks!

Oh yeah I didn't imagine circular UV bounds for cylinders when I read that.  Didn't get what you were saying there.  Using a different projection, cube for instance, could fix it, but that might take some tweaking to line it up again.


text:
Weird lines over a eevee render
I have been rendering an image using eevee due to time constraints. Whenever I render an scene from the animation that is above the base plane, i get strange scanlines. These look really bad when the whole animation is played.
Im using blender 2.82.
This is the issue i am getting.

Many thanks


text:
Help me make a waterfall
It has been 3 days now, countless YT tutorials, new and old, searchign on Blender Stackexchange and I just can't make it work.
Additional info: I understand the basic concpets and the objects needed for a fluid simulation to be successful.
I have carved out the environment with sculpting on a Plane where the water should be, and my next step would have been adding the water. As I am a beginner I think I tried everything with the Fluid simulation, it works fine when I start from scratch on a clean Blender, but for the life of me I cannot figure out how to make it work in the this case. Please give me pointers on how to make this happen, cuz I'm starting to lose my mind :D
Thank you!
PS in the meantim I am tryign to figure out how to add the .blend file :D
https://drive.google.com/file/d/1eX-lgrwlHWk5Zotr76cX3adGtFFshJdq/view?usp=sharing

is it supposed to be realistic?

Well it is not important, but if you want to advise that I make the water out of Planes, with noise and shading and so on, I would like to avoid that, and actually learn how to use the fluid animation in any scenario :)

it looks like a guy called Olav likes water simulations: https://www.youtube.com/watch?v=xIxUZpRk4Ac   https://www.youtube.com/watch?v=IOtZdysaJEA

Thanks moonboots, as I said in the very first row, I have been through these tutorials, step by step, I understand what does what, I followed the steps the same way here and apparently I am still doing something wrong.
btw the blender file is attached (blender exchange doesnt seem to work)

You can upload .blend files at blend-exchange.giantcowfilms.com . If you want to know more about why this is the preferred method here, please read this

Thank you! I will look into it. Cheers

For a fluid simulator like the one you want to create you need:

emitter: the mesh where water comes from (choose flow > liquid & inflow)
effector > collision: the mesh that will act as the collision terrain
domain: it's the area where the simulation should run. Emitter and Effector should be inside the domain

The core steps to create the simulation are:

Put all the stuff in place
select the Domain and press the CACHE button
play the animation and check if everything is ok
select the domain, goto Mesh, select it and CACHE MESH
check result and goto 1 to fix settings if you are not happy with the result
apply shader and similar...

here's what I have to share:

here's the source file of my simulation (you need to cache):
https://pasteall.org/blend/5ff62299dac24ba7adec6d04e350173c

Thank you, but it won't work sadly :(
The steps I have taken are exactly the same:

I have the Plane which had the Effector (collision) mode
I add the Cube that contains the whole of the plain and acts as the Domain
I add a UV Sphere to be the Emitter (Flow mode)
I bake the data and nothing happens

I understand the basic concept how the fluid system works and what elements you need for it to work.
I have been playing around with the Fluid concept on a blank canvas and it worked with everything else (big cube as domain, multiple small cubes or planes for collision)

check shared .blend file (it seems that in your blend file the problem is the terrain mesh, try to simplify and start from a cube - not a plane).

I will remake the environment from a cube tomorrow and let you know how it works.
I didn't think it was an issue with the plane, as when I played around with the fluid animation, I used planes as levels (so that it would act liek the one you jsut sent) and it worked fine.
I'll let you know how it goes ASAP
thanks

Good news, the preminilary testing proves that it should work, I made a quick environment out of a cube, carved it up a bit with sculpting and it seems to be working great :D all in all thanks for the advice, really not sure why I had this issue with the Plane to be honest, but regardless, thanks!

there are some specific settings for having a plane as a collision mesh (my tests also failed..)

Other than the accidental penis shape, it finally works... https://pasteall.org/pic/247c644027ec4cea9ca59757f0bb5b0e

https://www.youtube.com/watch?v=2O0QcLpAxV4
How to fix the Planes and Circles fluid and some other things


text:
Is it possible to recreate this in blender geometry nodes and how if yes?
I want to recreate this in blender geometry nodes. I suppose it is possible but it is more math than i hoped it is.
Can someone help please?

yes its more math. it looks similar to the shape i recreated, see my answer in https://blender.stackexchange.com/questions/270409/how-can-i-plot-this-cartesian-equation-in-geometry-nodes

To me, it looked like the inside of a doughnut. (With which we are only too familiar). On closer inspection of the Houdini nodes.. it is the inside of a doughnut.. :D

hey you're right! should be easy to plot using the torus equation blender already has in the xyz math surface templates! and then limit the u and v domain :D

If your question was solved, please be so kind and mark the answer that contributed to the solution as "Accepted Answer". This will make it easier for others to see which way leads to the solution, and the question will no longer appear as unsolved. Thank you! Here you can find more information: What should I do when someone answers my question?. If you still didn't get a solution to your question, please be kind enough to address it.

'Same difference' :) Always slower than @quellenform .. slightly different approach:

but I think his explanation will suffice ..

Good answers need to be well thought out, speed is not everything! +1 ...your answer has at least a Houdini-like gradient as background ;-)

I had to wash up, that's my excuse... and I'm gettin' old :)

Same as above, almost exactly right, only if horizontal lines would slowly move upward so we have emerging effect in full. I don't know is it visible in my video?

@MarkoBogunovic  That effect is slightly visible in my version .. a delay in filling the rings, bottom to top.  Set by the 'Addend' in the 'Anim Rings' cluster. I'm restricted by .gif size.  I think yours also has a fade, that's another question. I think the easiest way to taht is via the compositor, for pure wireframe.

I meant actual movement of the rings up the arc. i updated original post with a new gif. see if it clears it out

@MarkoBogunovic Ahh, OK, quellenform's method would work better than mine, for that. He/you could just animate the tilt of the main circle, or the start-angle of the arc sent around it.

You could solve this as follows:

Here I create a mesh with an arc as a profile and a circle.
Then I separate the horizontal edges from the vertical edges.
I split these and convert them back into curves.
With Trim Curve I extend the curves depending on the current frame.

(Blender 3.2)

With the same technique you can determine not only the end of the curves, but of course also the beginning:

I don't know why i always thought of profile curve needing to be something closed. I didn't realize you could use an arc as the profile curve which is really cool effect!

This is almost exactly what i need but i need horizontal lines, circles to slowly move upward also, so i have emerging effect in full

@MarkoBogunovic I'm afraid I don't quite understand that, they do move slowly upwards, don't they? Can you explain or show this in more detail?

i just updated original post, added your model with manually added rotation on z axis for everything, and moving the slider on your arc node to create this growing/emerging effect. But the thing is, beginning and the end of the arc should stay on same positions and horizontal circles should disappear/emerge when they reach the end. Hope i made it clearer!

watch closely latest gif i uploaded

@MarkoBogunovic If I understand this correctly, you would otherwise simply have to animate the values for Start Angle and Sweep Angle additionally.


text:
How to get an object to display its actual position after transform using parenting with empty using python
Currently this code creates an empty at a defined position and have used parent to get an object, in this case a cube to be in that position. However the newly created cube states its position as the origin rather than its actual position. How would I get the cube to display its actual position which would be the same as the empty?
import bpy
from mathutils import Matrix, Vector

context = bpy.context
scale = 0.01

x, y, z, l, m, n, p, q, r = -500, 200, 1000, 1, 0, 0, 0, 0, -1

y_axis = Vector((l, m, n))
z_axis = Vector((p, q, r))

x_axis = y_axis.cross(z_axis).normalized()

M = Matrix((x_axis, y_axis, z_axis)).transposed()

M = M.to_4x4()

M.translation = scale * Vector((x, y, z))

print(M)
print(x_axis, y_axis, z_axis)
bpy.ops.object.empty_add()
mt = context.object
mt.empty_display_type = 'ARROWS'
empty = bpy.context.object
mt.matrix_world = M

bpy.ops.mesh.primitive_cube_add()
cube = bpy.context.object
cube.parent = empty

Please ask only one question per post to make your question useful for others too... Please read: https://blender.stackexchange.com/help/how-to-ask

How to create an empty without using ops (allows to don't rely on the object in context in your case): https://blender.stackexchange.com/questions/51290/how-to-add-empty-object-not-using-bpy-ops

I'll edit the other question out

Why not using the matrix again? my_cube.matrix_world.translation? Don't get your question...

A little confused as to what that non bpy.ops does, the use of adding an empty in the right place showing an axis system was useful to indicate the positioning of an object if it were placed there

@brockmann did try to use that however it shifts everything by a transformation- what I wanted was for an object to be positioned in a specific location irrespective of its original location

Read it again and still not sure what you mean. All I can say is: the origin of an object is always the actual position.

So when the code is run the empty is created and put in the position as shown by the matrix/vectors. The empty displays its position with respect to the origin (-500, 200, 1000 etc). When the cube is created it goes to the same position as the empty but when you click on it it says its location is (0,0,0) which is different to what the empty displays

Wasn't notified... I voted to re-open the question.

Oh right didn't realise it was closed

Ok  cube for empty  in prior question,. Don't parent the object to the empty, don't even add the empty. Add the cube as you've done then cube.matrix_world = M  If you do use the empty and parent the cube to it, empty.matrix_world.translation to get its global location.  The python console is a good way to work this stuff out.  @brockmann Think this is a dupe, just wrong dupe. .  https://blender.stackexchange.com/questions/109984/how-to-get-global-object-location-python  https://blender.stackexchange.com/questions/39677/how-do-you-get-an-objects-position-and-rotation-through-script


text:
How to use a wetmap to distribute particles (how to distribute plants where moisture collects)
This is a follow-up to this question - Geometry nodes: How to distribute points on valleys only?
One of the approaches considered was using particles to simulate rain, then using the wet map from dynamic paint to calculate where water flows and accumulates in a landscape. The animation below shows the surface with wet and dry areas.

I'd like to use the wet maps to distribute particles or apply modifiers that rely on vertex weights. Additionally, I'd like to be able to do this as part of an animation.
Is there a way to move the wet map to a vertex map as part of an animation? A preferred solution would not involve python.
The file used to generate this image is here -

As suggested in a comment of this question How to convert a wet or paint map to a weight map you can bake the DP as an image sequence and use these images to control the particle distribution =>https://i.sstatic.net/PUIsp.jpg It requires a bake step and a UV map. Your mountain mesh is quite dense but it works. -- Maybe also helpful Is it possible to get a weight paint value for a vertex group inside of a material?

Particle Distribution
For the particle distribution, you can bake the Dynamic Paint (the wetmap to be precise) to an image sequence. The landscape object must be UV unwrapped for this to work.
Baking Step

create the UV map for the landscape object. It will take a minute or two because your mountain landscape has many vertices.

in the Dynamic Paint settings of the canvas (landscape object) choose Format: Image Sequence and a higher Resolution, for example, 512.

expand the Output section, enter a folder name for Cache Path. This is where the baked images will be saved. The press the Bake Image Sequence button.

Done this, you can deactivate the Dynamic Paint physics on the canvas and the brush with monitor and camera icons on the Dynamic Paint section in the Physics tab or alternatively, on the modifier itself.
Using the Baked Image Sequence
Use the baked image sequence for the shader to visualize it.

choose Open on the Image Texture node and select all images with A. Make sure they are ordered by the file name to have them in the correct order.
enable [X] Auto Refresh for the Image Texture node
set the Number of Frames

Then create a Particle System for the landscape object.

type is Hair, activate the [X] Advanced option
use the cone (tree) object as rendered object (Render > Re[]nder As = Object and .. > Object > Instance Object = the cone). Increase the .. > Scale to a higher values like 0.2.
activate the [X] Rotation (advanced option), and set Orientation Axis to Object Y to have the trees all vertically aligned.
in the Textures section of the Particle System create a new texture in the first slot with the New button below.

Switch to the Textures tab.

select the image sequence that you have created for the shader
tick [X] Auto Refresh and check if the Number of Frames value is correct
in the Influence section, tick [X] Density. And [X] Hair Length if you want to have the size affected.
set Mapping to UV and select the correct UV map if you have more than one

(the particle system has a few old bugs. Sometimes it doesn't update and you have to do a change and revert the change immediately. Here for example are tiny trees... no idea why. Hair Length is not checked).
Geometry Nodes - Point Distribution
This is rather easy to do in Blender 2.93.5 because you can access the vertex color that is created by the Dynamic Paint physics directly in the geometry node:

The drawback here is that it is very slow when you replay the animation.
Related question
Is it possible to get a weight paint value for a vertex group inside of a material?

the 2nd part using Geometry Nodes was exactly what I was looking for. Thanks!


text:
How to texture paint across all objects that share the same material/image?
This is a greybox project, so we shouldn't take in account detail or sustainability. Just something that will "work".
I have several objects that share one UV map and one material. I used Smart UV project for all of them so that it would pack them in the same space. I made a new image and applied it to the material.
I can texture paint each object just fine. However, I need to paint across all of them at the same time, in the 3D viewport (not the image editor). As it is, I need to select each object, then go to Texture paint and I can see my previous strokes, but I need to see them all at the same time (I'm making relationship lines etc). How to do this?
Also, my texture doesn't appear at all in material mode, although I have connected the texture to the diffuse channel.

Hi mate, could You send the .blend here? Its somehow important if You want to draw on each object serapately or exact same shape on some parts of multiple objects in the same time - cause in this case, You could paint on one and affect all others using overlapping islands. I need a better explanation to help (if possible) and cause of that I need your scene.

Added my blend. I want different textures on everything (I want to write what is each block, and how it relates to each other).

@JanMatys did you have any luck with my blend?

If they already share all the same UV space, then temporarily you could then join them together until the paint stage is done.

I'm kinda scared to do so. I have lost work previously with the join method, even though I saved everything externally.

@mechanicarts if you duplicate the objects and join the duplicates your originals will remain intact.


text:
Can I get a UV-irrelevant grid material on blender?
I've been modelling on blender for a long time, and I was never really particular about what my default material is. Now, I've tried probuilder (unity plugin) and the only thing that I really enjoy and miss elsewhere is its default material that displays a grid.
Is it possible to get such a material in blender? This material always displays in 1:1 and never stretches, essentially ignoring UV. If you scale or modify the mesh, the texture is always gonna show the grid as is.

Someone on the blender Reddit made an custom node that does something like this.

He publiced it on blenderswap:
https://www.blendswap.com/blends/view/85263
You can tweak it a bit, here is a node setup you can use:

That's pretty close to what I want. It's a bit too complicated, but obviously if it gets it done it's good enough. Meanwhile I made an experiment (being a beginner in cycles) and it worked also pretty close, except for a small problem. I made a 512 texture and applied it using box mapping on generated coordinates. It works pretty well too, but 3 of the planes are reversed. If I could solve this I'd have a very useful tool in my hands.

You might want to look in to the multiedit plugin, I believe it has the functionality to set origin points of vertex groups what should solve your rotation problem.


text:
Bones are invisible and background screen in Solid View is too bright
I was working on this lego character from a course online. I created a new 2D Animation layout, the way the instructor from the course had done. I created a basic idle and running animation and saved it. I did not work on the project for about 2 days but when I opened the same file, I cannot see the bones of the armature.
The 2D animation layout had about 6 Editor types:
The right hand corner is a slim section divided into the Outliner at the top, and the Properties below it.
In the center, it is divided into 2 main sections:
The one on top is divided vertically in the middle, with a 3D viewport on either side. The left one displays the camera's view focussing on the face of the humanoid model (for 2D animations using grease pencil) and the one on the right is a perspective view of the entire model.
Below this sections I have two editos split horizontally. The one on top is the Grease Pencil Dope Sheet, and the one below is the Action Editor Dope Sheet (the default type).

Now, all the editors seem to be working fine except the 3D viewport displaying the entire 3D model. In Solid View, the entire background is a much brighter colour than what it used to be; and all the custom object shapes that I had created for each of the controlling bones in the armature is missing. It is not hidden in the outliner, nor is any object in the scene in Local View. So I do not understand why it's invisible, and how to revert the background colour. Moreover, I used to be able to see the floor in the Right Side View but now, unless it's in Perspective view, I cannot see it.

However, if I go back to the Modelling or Layout Tab, the Viewport background is the default colour and the custom bone shapes are visible as well.

I use Blender 2.8 for this project and I have attached my project file. Any help to revert these issues is appreciated. Thanks, in advance.
http://pasteall.org/blend/index.php?id=51727

Thank you for letting me know. I have now added the images.


text:
How to position the default blender cube given coordinates, direction Z vector and direction Y vector using python?
New to blender and python here,
Given the following:
Coordinates (X,Y,Z) = (-100,100,1000) and Direction Z vector = (1,0,0) and Direction Y vector = (0,0,-1) where angle between direction vectors is 90 deg
How would I position the default cube in blender there using python?

It is a little hard to understand the expected workflow here, could you add a little more detail ?

Wondering if it is possible to have an add on in blender which will load sources using the above list array into correct positions and rotations like lighttools software.

Ok so you have a csv or excel file with transforms data, and you want to map these values to light objects transforms inside blender, is this correct ?

Yes, I believe so

The excel doc produces a txt doc with the coordinates and direction vectors as shown in the example, can blender take this data?

Please use text to explain the data rather than image.   Blender uses python.  See https://stackoverflow.com (or other python sites, or search here for "[python] csv") re how to import csv or excel etc.    Yes it is possible to make an addon. Suggest edit the question with the python to read the data. (or not)  Add an example of one empty placed to match data line. As the question stands at the moment, to answer (other than "yes it's doable") requires teaching file I/O as well as the blender part. Please consider condensing question to just the how to position empty from data ..

which if I understand correctly is make a 3 x 3 rotation matrix with X, Y and Z axis as columns. The X axis is Y.cross(Z).  Make the matrix a 4x4 and set its translation to coordinate.

From this output:
X Y Z L M N P Q R
-500 200 1000 1 -0.1 0 -0.2 -0.3 -1
Data above means:
Coordinates (X,Y,Z) = (-500,200,1000) and Direction Z vector (L,M,N) = (1,-0.1,0) and Direction Y vector (P,Q,R) = (-0.2,-0.3,-1)
How would I for example position the default cube there?

Yes I read the image. Please edit question with these details.  The angle between two direction vectors is around 100 degrees.  (expect axes to be orthongonal (90 degrees))   Please also edit in an example of expected output.

I'll change the question as to avoid confusion

make a 3 x 3 rotation matrix with X, Y and Z axis as columns. Blender matrices are in rows, so will transpose rows to columns. The X axis is Y.cross(Z).
Make the matrix a 4x4 transform matrix and set its translation to coordinate
Note Added a scale factor so location 1000 -> 10. To avoid clipping. Set to 1 or remove.
import bpy
from mathutils import Matrix, Vector

context = bpy.context
scale = 0.01 # 1000 is a long way away

x, y, z, l, m, n, p, q, r = -500, 200, 1000, 1, 0, 0, 0, 0, -1

y_axis = Vector((l, m, n)).normalized()
z_axis = Vector((p, q, r)).normalized()

x_axis = y_axis.cross(z_axis).normalized()

M = Matrix((x_axis, y_axis, z_axis)).transposed()

M = M.to_4x4()

M.translation = scale * Vector((x, y, z))

#test
print(M)
print(x_axis, y_axis, z_axis)
bpy.ops.object.empty_add()
mt = context.object
mt.empty_display_type = 'ARROWS'
mt.matrix_world = M

or to  add a cube
#test
bpy.ops.mesh.primitive_cube_add()
cube = context.object
cube.matrix_world = M

Thanks for the answer @batFINGER, just wondering how I would go about running this correctly? New to this software.

Paste into empty text in text editor. Click the run script button [>]

If I wanted an object, say the cube for example to be at this specific position but it does not start from the origin, how would I get this to happen?


text:
Normal Map Baking Artefacts on Complex Model
I have sculpted and retopologized a dragon model. When I try to bake a normal map using details from my high poly model I am getting artefacts on my normal map. I get much better results using a cage, but there are still some problems in areas such as the mouth, wings, and under the legs:

There are also similar artefacts under the horns and on other parts of the wings.
The mouth artefacts can be cleared up by not using a cage and putting the ray distance under 0.4, but then I get worse problems on other portions of my mesh such as the upper legs. I have tried using 32bit float and 8k for my normal maps. Changing the placement of my seams multiple times did not make much difference. I played around with the extrusion option when using a cage, but no extrusion gives better results. I could go into gimp (or photoshop), and try to fix the problems manually, but I would like to know why I am getting them. Here are the bake settings that work best for me (to make the cage I took the low poly version went into edit mode then used ALT-S to scale up until the cage covered the high-poly version):

Here is my .blend, but without the high-poly model because it took up too much space:
EDIT: I re-created my cage, manually scaling certain areas more than others then re-baked with the new cage. The normal map looks better in the mouth area, but the normal map applied to the dragon still looks just as bad in the viewport.

In order to get rid of the artefacts on the wings and the feet I had to make my low poly mesh (more) similar to my high poly mesh in the areas that had normal baking problems. For the artefacts in the mouth, under the legs, and under the horns I had to adjust my cage manually to make sure there was no overlap. Sometimes the normal map did not display properly; changing the color space on my image texture "refreshed" the node making the normal map display properly. The normal map has come out fine, and I have not changed any of my bake settings except putting the Margin to 32px instead of the default 16px.


text:
Fixing bad geometry on a complex mesh
I have been modeling a dragon, and I see all sorts of artifacts in the mesh. When I go into edit mode and select all by trait, blender says they are non manifold and interior faces. I have researched many different ways of fixing bad geometry such as merge by distance, Weld modifier, and trying to smooth or use other tools in sculpt mode.
Here is my .blend -->

Did you try select non-manifold operation and see what's going on that mesh?

If it says "non-manifold" it means you have inner faces that need to be deleted.

I had selected non-manifold, but the highlighted areas appeared to be "outer" faces and I did not want to delete those important parts of the mesh. I believe the artifact was caused by using the decimate modifier as described in Xylvier's answer.

I looked over the file and found that over huge parts of the object there are faces overlapping other faces:

Some connected some not. While using a remesh modifier with a low enough voxel (roughly 0.08) size results in the geometry to be clean again:

The resulting mesh will have a throughout higher density and i do not know if you want to retopologize your dragon, as that might be the best way to reduce the density again.
I tried to use the decimate modifier and it actually resulted in similar artifacts, so retopo seems to be the best choice.
Another option going out from the version you shared, would be to cut away half of the dragon and using the mirror modifier. Then you would have to go over half the dragon and manually remove all the overlapping faces, believe me, it will be a good timekiller. Retopo seems in my humble opinion to be the better option.
Happy Blending


text:
Cut/mask multiple planes along a circle at once
My challenge is to create some type of a radial chart so I created planes with an array. I scaled the planes randomly to generate "fake data". Now I want to cut all the bars (planes) along a circle which represents "0".
It is possible to do with the knife project, but this means I would have to do this for every bar?
I would prefer a mask which would automatically hide everything below the inner circle, but I was not able to manage this with the vertex groups.
Any ideas please on how I can make this in a more performant way? I'm using 2.8

first join all your shapes into one object, then cut off with boolean or knife project, then if necessary separate by loose parts?

Make sure all your objects's origins are in the center of the world. Go into Object mode, SHIFT + C to center the 3D cursor, then A to select all, Right Click > Set Origin > To 3D cursor.
Also, apply the scale transform with CTRL + A > Scale or go to Object > Apply > Scale
Give this material to all your objects (only the alpha part is important):

The "Length" node is obtained by using a "Vector Math" node and set the operation accordingly. Similarly for the "Greater than" node, you must first add a "Math" node and change the operation.
To give this material to all your objects, give it to one of them, then select them all with A and SHIFT click on the object with the material. Then go to Object > Make Links > Materials or SHIFT + C > Materials
If you use Eevee, make sure to set the alpha blend mode to clip :

Tweak the Math node threshold :

You can then add a driver to use your bezier circle as a visual guide, and mask the bars under it when you scale it :

Thank you, exactly what I was looking for!

EDIT: this works when all lines are aligned to each other but not when they are starting from different positions from the center as in my example.

Maybe try my method (join all the objects together and apply a boolean), or share your file: https://blend-exchange.giantcowfilms.com/  by the way, how did you make the original shape?

If their origin is in the world center and you have applied the scale with CTRL A, the shader should work. Could you share your file with the link @moonboots provided ?

@moonboots and Gorgious : I added the file to the question. Thx for your time.

so it looks like you've already cut off a circle, no?

@moonboots ah sorry my bad, this was already the workaround, I'll re-upload the inital piece

I don't see any link

@moonboots just added now. thx

so what about joining all your beams into one object, then use a boolean to hide the center and make a perfect circular hole?

@StefanWasserbauer You need to apply uniform scale to all your objects. Select them and press CTRL + A > Scale or go to Object > Apply > Scale

@StefanWasserbauer Edited my answer

We lack a bit of informations about what you want to do but let say you just want to dig a hole circle on your shape:

Select all your beams, join them with J.

Create a cylinder, make it invisible in Viewport Display and in Visibility.

Give your beams object a Boolean modifier with the cylinder as Object and Operation > Difference.

You can change the cylinder radius, you can use shapekeys if you want to animate. You can also apply the Boolean. If you want to separate the beams again, press P > By Loose Parts.

This seems to be the easiest solution by now and the most straight forward. As I like the solution of @Gorgious too it's quite hard which one to mark as the final solution,... Thank you guys for your effort!


text:
loop tool does not create a circle
I want to make a circle edges loop using loop tool ads on. This is my edges

And when I apply the loop tool circle this is what happened

here's my blend file

@JachymMichal unfortunately the To Sphere function does not work for me

You might have some bad geometry.  Can you share your blend file?

@MartyFouts yes. check it out. This is my first time using paste all. I can't use blender exchange because it keeps loading

You have a bunch of duplicate vertices that are messing up the Circle tool.

@HISEROD how to check it out and then delete the duplicate?

You do have bad geometry.  To find and fix it it, I did the following in edit mode:
Go to face select mode and select most of the faces.

Then type h to hide those faces

This isn't strictly necessary but it makes it easier to follow the next bit.
Next I went into vertex select mode, and selected every vertex

and I typed m to bring up the merge menu

and I selected "by distance"

and in the lower bar it told me that it had removed vertices:

Next I tried to select the vertices that you want to make a circle using alt-LMB after deselecting all with ALT-A.  But that failed because you have some extra vertices that are not near enough to each other for 'by distance' to work with the default settings so I opened the merge tool information (at the bottom left of the 3d view)

I had to set the merge distance to 0.01 to get six additional vertices.
After that I reselected the ring, and Loop tool -> circle worked fine.

follow that with ALT-h to unhide the hidden faces and that's that.


text:
How to group selected animation keyframes in the «Graph Editor»
There is a similar method in Edit Mode: Vertex Group. I need something similar but with animation keys in the Graph Editor.

Description of video: A demonstration of selecting vertices in a mesh and then adding them to a vertex group.  This is followed by selecting keyframes in an F-Curve and a question mark — meant to indicate the desire for the equivalent functionality, a sort of "vertex group" for keyframes.
Advantage / application animation key grouping:

Analog - NLA but in one action. Replacement / alternative to NLA. Place the grouped cycles of different gaits in one action further along the timing, in order to substitute one or another grouped part of the desired cycle in the right place of timing in the process.

The keyframes in an F-curve are equivalent to the handles of a curve object and there is no available method for collecting a subset of the handles to create the equivalent of a vertex group.
But you hit on the way Blender solves what appears to be your underlying request.  This is precisely what the Action Editor is meant to provide.  Actions are the equivalent of the subsets, but instead of simply having collections, you create the F-curve in a two step process, by combining actions in the NLA.

Thanks for the reply!
I wanted to do it without NLA. Because the animation created using NLA is difficult to transfer to another file via Append. But F-curve through Append Action is easy to transfer to a new file.

I thought that was the case.  Unfortunately, there is no F-curve equivalent to vertex groups.  But don't give up hope.  There is currently a lot of work being done by developers on animation tools.  Perhaps you could go to RightClickSelect and submit a suggestion.

Ok. Thank you! :)


text:
Assign Random Materials to Loose Parts
I have 5 materials, and I'd like to assign it randomly to loose parts of one object.
Is it possible to do so?

Do you want to assign images textures or just solid colours randomly?

Doesn't have to be image textures, just to assign materials already created.
Material 1,2,3,4,5 to random sperate objects. If that could cycle through materials, that'll be cool also. Just want to assign them to loose parts, without going like: Select object, seperate by lose parts, select the part, assign material, repeat 10 times for 1 obj

This does not answer your question, but you do not have to separate the object in order to assign different materials to different parts.
You just have to create more material slots (in your case 5 total) and select each part and assign it to a different slot, than you can manually set each slot to a different material.
It's not random and it's not automated but at least you don't have to separate the loose parts.

is it ok if my answer could only be used for multiple separate objects instead of loose parts in one object?

Ofc, at least it'll lower the clicking count! ^^

Great! then give me one sec and I will upload the answer

Assuming you already have 5 material slots assigned to the object and the object is your current object, this python script will do what you want:
Note This script works whether the object is in object or edit mode, but if it's in object mode, the changes won't show up until you toggle edit mode.
import bpy
import bmesh
import random
from math import trunc

object = bpy.context.object
if object.mode == 'OBJECT':
    bm = bmesh.new()
    bm.from_mesh(object.data)
else:
    bm = bmesh.from_edit_mesh(object.data)

islands = []

bm.faces.ensure_lookup_table()
bm.verts.ensure_lookup_table()

# https://github.com/Aadjou/blender-scripts/blob/master/bmesh-get-linked-faces.py
def get_linked_faces(f):
    if f.tag:
        # If the face is already tagged, return empty list
        return []
    # Add the face to list that will be returned
    f_linked = [f]
    f.tag = True
    # Select edges that link two faces
    edges = [e for e in f.edges if len(e.link_faces) == 2]
    for e in edges:
        # Select all firs-degree linked faces, that are not yet tagged
        faces = [elem for elem in e.link_faces if not elem.tag]
        # Recursively call this function on all connected faces
        if not len(faces) == 0:
            for elem in faces:
                # Extend the list with second-degree connected faces
                f_linked.extend(get_linked_faces(elem))
    return f_linked
#---------------

examined = set()
islands = []

for face in bm.faces:
    face.tag = False

for face in bm.faces:
    if face in examined:
        continue
    links = get_linked_faces(face)
    for linked_face in links:
        examined.add(linked_face)
    islands.append(links)

for island in islands:
    n = trunc(random.uniform(0,5))
    for face in island:
        face.material_index = n

# update the object's mesh from the bmesh
if object.mode == 'OBJECT':
    bm.to_mesh(object.data)
    bm.free()
else:
    bmesh.update_edit_mesh(object.data)

The script uses the function get_linked_faces that is taken from Madlaina Kalunder's Aadjou github repository.
How it Works
The script uses bmesh, so it starts with the boiler plate to create a bmesh from an object's mesh.  You can replace the line
object = bpy.context.object

with code to use a different object.  Note the script assumes there is an object here.  You might want to protect the rest of the code with
if object:

After creating the mesh and validating the lookup tables, the get_linked_faces function is defined.  It identifies, recursively, every face that is linked to the current face by an edge.  In other words, it identifies the islands in the mesh, that is your loose parts.
Next we initialize some variables.  get_linked_faces uses a tag field that we clear to False.
This is followed by the loop that creates the islands/loose parts by looping through every face in bmesh.
Finally, we loop through all of the created islands, selecting a random color for the island, and assigning it to all of the faces in that island.  Note this relies on having exactly five material slots.  It might be more robust to use
    n = trunc(random.uniform(0,len(object.material_slots)))

but only if you want to use exactly all of the materials assigned to the object.
Finally we end by restoring the object's mesh from the bmesh.  This transfers the data back.
Here's a simple example with an object consisting of 3 cubes, a Suzanne, and a sphere:

Thank you for the efford. This is just what I was looking for Marty. Appreciate it!

You're welcome.  I'm glad it worked out for you.

I'm not particularly great at coding so I was wondering if this works for any amount of material slots as is?

Please follow the steps given below to achieve this result:

Note: this method can only be applied when adding solid colours to an object and all the objects have to be separate.

Separate all the loose parts in the object by pressing 'P' 'loose parts' in edit mode, go to the shading tab and add in an 'object info' node and our favourite 'colour ramp'.

plug in the random of the object info node to the factor of the colour ramp and connect the colour of the colour ramp to the 'principled BSDF', change the colours of the colour stop (the arrows) to whatever you want it to be and simply press the '+' icon on the top to add new colour stops.
Note: do not connect the 'location' of the object info node to the factor of the colour ramp as shown in the GIF. I made a mistake, sorry ;)

The shading is finished, now first press the object where this material is assigned to and then press 'A' so that the object with the colour assigned to is in another colour, press 'Ctrl + L' and select the 'materials' options.

Thank you for this one as well, not exactly what I was looking for, thought it might help.

Ok no problem Jackie


text:
How to control enviroment texture with collection visibility?
I'd like to control HDRI with collection visibility.
Created 3 different Worlds with 3 different HDRIs, and would like to change them with collection visibility.
Here's what I've been trying so far:
import bpy

    if bpy.data.collections["Dark HDRI"].hide_render == False :
        bpy.context.scene.world.name = "Dark"

    if bpy.data.collections["Yellow HDRI"].hide_render == False :
        bpy.context.scene.world.name = "Yellow"

    if bpy.data.collections["Green HDRI"].hide_render == False :
        bpy.context.scene.world.name = "Green"

Tried to find correct context for it but had no luck, and i don't know if this is the best way to solve it, i'm open to ideas. It doesn't have to be worlds, i just want the HDRIs.
Tried MixRGB node as well, it's just updates the lights, but not background:
Here's what i've tried for that method also:
import bpy

if bpy.data.collections["Dark HDRI"].hide_render == False :
    bpy.data.worlds["Dark"].node_tree.nodes["Dark"].inputs[0].default_value == 0

if bpy.data.collections["Yellow HDRI"].hide_render == False :
    bpy.data.worlds["Multiple"].node_tree.nodes["Yellow"].inputs[0].default_value == 1

if bpy.data.collections["Green HDRI"].hide_render == False :
    bpy.data.worlds["Multiple"].node_tree.nodes["Green"].inputs[0].default_value == 1

Hello, not exactly sure what your end goal is but it seems you're only changing the current world's name, when you seem to be wanting to swap the world objects, so you should try something like : if ...: bpy.context.scene.world = bpy.data.worlds["Dark"] etc.

If you can settle for the first collection that is enabled for rendering, then you need code that looks something like this:
import bpy

def enable_world():
    for world in bpy.data.worlds:
        collection_name = world.name + " HDRI"
        try:
            collection = bpy.data.collections[collection_name]
            if not collection.hide_render:
                bpy.context.scene.world = world
                return
        except:
            pass

enable_world()

As Gorgious says in the comments, you need to set the Scene world to the world you are interested in, so this code iterates through all of your worlds, looking for the first one that has a collection associated with it where the collection is enabled for rendering.  The try block is in case you have worlds that you forgot to set up a collection for.
But why do it this way?  It's very error prone.  It doesn't work well if you forget to add a collection, and it doesn't know which one to pick if you have many enabled for render.

Thanks mate, appreciate it!


text:
Interactive clipping plane
In this question, How can I easily animate cutaway views on multiple objects? it was suggested to use the camera clipping distance as a cutting plane.

Is there a way to have an interactive cutting plane that is not parallel to the camera?
What is needed is a way to review complex geometry in real time by moving a cutting plate through the geometry in a way that does not necessarily line up with the camera view clipping planes.

Possible duplicate of How can I easily animate cutaway views on multiple objects?

LuxCoreRender has such a feature: https://wiki.luxcorerender.org/BlendLuxCore_CameraPanel#Clipping_Plane

@DuarteFarrajotaRamos I think this question is asking for an interactive/viewport solution. That question seems to be about doing this in a render.

For use in the viewport, try the clipping border AltB:

This only works in wireframe or solid mode unfortunately