text:
Transform a semi-sphere into a rounded rectangle
I'm new to Blender and I'm struggling to find the way to transform (by an animation shoude be better) a semi-sphere object to a rounded rectangle.
Please look at the image posted where the red semi-sphere:

is transformed into a red rounded rectanlge:
Thanks.

Have you tried shapekeys?

no, I wasn't aware of that--I'm still at a basic level of using Blender...

A Cast modifier on a rounded cuboid should do that for you..

CtrlR cut the default cube in half, V cut the loop
X delete the bottom half, F fill the hole
SX etc. scale to shape in Edit Mode, top edges only, if your reference indicates..
CtrlR cut in loops to even up density.

Add a Cast modifier:

Factor 0 is the original, and 1 is the hemisphere.

This one's followed up with a level of Subdivision Surface.
In the example, I've adjusted the topology of the bottom surface to suit a bit better, and added a Smooth modifier aimed at the bottom surface only, to make the result a bit more reasonable after deformation, bevelling and subdiv. .. but that's optional. You could take that further, or not do it at all.

Please can you elaborate better the steps you made to get the result? Unfortunately I'm not be able to reproduce your result. I'm not be able to get a sphere: I get a distroced cuboid...

The sphere is centred on the object origin, (adjust with Header > Object >Set Origin). The scaling to make a cuboid must be in Edit Mode. (If you scale in Object mode, the sphere-effect will scale along with the object) Will try to fill in some steps for you.

@xdevel2000 see edit.. hope it helps..

Amazing, now it works... however now I've another problem: if I make the animations inserting two keyframes at 0 (factor 1) and at 40 (factor 0) and then I apply the modifer the animation is lost... any help also on this?

The animation is in  the modifier. Applying it will store the mesh at the point of application. If you need to lose the modifier (say, for export) then you could bake its effect, frame-by-frame ... see e.g. https://blender.stackexchange.com/a/230703/35559 search 'Blender Bake Modifier' or somesuch. If you have a particular version of the question not previously covered, then go ahead and post.. we'll do our best :)

I'll try to make a new post to explain better my problem


text:
Texture breaking when painting
Not sure what it could be, got it after upgrading to 3.6.1, please help :(

it should be black

Hello please share your file

@moonboots https://drive.google.com/file/d/1vi2F1ffi-u8fDxJSXiRdKc7WeY1DaQeN/view?usp=sharing

You didn't pack your images, for the moment the material is pink

@moonboots oopsie https://drive.google.com/file/d/16XgqrtPsdgeYcwSVBZYKavmDwplIFc7R/view?usp=sharing

@moonboots should i modify them in paint.net?

It looks like it's a bug due to the image format.
In the Image Editor window, select the image, then Image > Save As > File Format > choose PNG > Save as Image, then, in the Image Editor, AltR to reload the image. This time the painting will work normally. Pack your images.
Or, if you don't want to pack your images, open them in an image software and convert them to PNG (or JPG, or EXR).

source: Stack Exchange

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

sort: votes


text:
Edit mode options missing?
Brand new to blender and imported a model from another program. Went into edit mode but not seeing any option for vertice, face, edge selection? Am I missing something here?

In this moment the mesh is selected but the Metarig is Active (last selected, even if it's hidden). So you are in edit mode of the armature, not the mesh.
In object mode, press Alt H to unhide everything, click on the 3Dview background to unselect everything, then click on the character (it has to become yellowish, not orange), and go to Edit mode.

If the armature is hidden to not obstruct the view when editing the mesh, I would not unhide it... especially not Alt+H to unhide all, this can be very tedious in scenes where you maybe had hidden several objects for various reasons. Just hit Tab in the viewport to go back to Object Mode, then click on the mesh that should be edited and go back to Edit Mode.

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


text:
How to assign a hotkey to 'set origin' context menu?
How can I assign a shortcut to popup the following menu when pressed?

I have looked around and I found that I can right click and "Assign shortcut" on other menus, like this example on pivot point, but I can't do it on that submenu.

Also, I tried the method of looking on the Python Console to find out the value of that menu, but there's no value on that one (just on the sub choices).

It's already part of Object context menu (Select the object, Right-click > Set Origin). Is that fast enough for your purpose?

I noticed that, but I was looking for a quicker way, like the "m" for move to collection that shows the menu without having to go through submenus.

Yeah, get it. By looking through the ui code, you'll see that object.origin_set operator is called via Layout.operator_menu_enum(), not quite sure there is any way adding that to the keymap. In case there is no option you'll have to write a custom operator (addon) or wait until following "bug" is fixed: https://developer.blender.org/T65704

Ah!, Thanks!. I see, I though It was me that I couldn't find it.
Although as you say, I wouldn't see that as a "bug" more like a "feature request".

If you set the keymap to Blender 27X in the Preferences, you can find it under the name: Set Origin. Originally: ctrl+shift+alt+c.

Create a new key map item under 3D View > Object Non-modal and set the identifier to object.origin_set (bl_idname for Object.origin_set() operator).  In order to match the definition of the hotkey in 2.7x, set the event to C and enable ShiftCtrl Alt for the modifier keys:

Note: Assigning shortcuts to enum menus like this (operator in this case), is a known limitation and will hopefully supported in the near future: https://developer.blender.org/T65704

Where did your get that "object.origin_set" value?. I'm asking so I can look for myself next time. thank you for the help!.

From the source file as stated in my second comment. Right-click > Edit Source. Just make sure Developer Extras enabled under Preferences > Interface to have that option within the context menu @Fabman

I didn't have the developer extras enabled, now I see it.


text:
What's the "deselect all" hotkey in Blender 2.8x?
Recently I've been trying to transition from an earlier version of Blender to 2.82. The UI is easy enough to figure out but the thing that really gets me is the bind to deselect all. In earlier versions, I could press A to select and deselect all but now I have to press Alt+A to deselect which really bothers me. If possible, I would like this to work in both Object and Edit mode.
I've tried going into preferences and changing the (de)select binds from Alt+A to A but it hasn't worked.
In essence, I want the keymapping to be the same as in earlier versions of blender; A to select and deselect all.

I am not happy happy about the situation either.⌨

Nah Alt is great and consistent with many other uses.

Related https://blender.stackexchange.com/questions/118778/2-8-select-and-deselect-like-in-2-79 and https://blender.stackexchange.com/questions/130641/how-can-i-get-single-a-to-deslect-in-2-8

Press AA ... that is a double A.
AA will deselect all.

I guess that works. It's not ideal but I'll take it over having to press Alt. Thanks.

@ZaneD I hated it at first but I use the command so often it felt natural after a few days

The old behaviour is still available in Blender 2.82. Go to the Keymap section of Preferences, and in the first panel (titled ‘Preferences’) tick the ‘Select All Toggles’ option.

Thanks for your answer, I had no idea it can be switched on like that :).


text:
Msgbus - How to subscribe to bpy.context.scene?
I'd like to receive a msgbus notification when the active scene is switched, or somehow otherwise capture this event and respond to it in my code.
I thought this would be a fairly simple msgbus subscription to bpy.context.scene, but my listener is not receiving anything from msgbus, not even errors. In fact I don't seem to be able to get msgbus to fire for anything in bpy.context. What I was hoping for was something like an active property for bpy.types.BlendDataScenes that I can hook msgbus into, but I've come up blank and the lack of any kind of output from msgbus has left me fumbling in the dark with mittens on.
Has anyone been here before?

Subscribe to some event that signals scene change.
As with How to get an event when an object is selected?  find the code to change what you wish to notify.
In this case
Changing the scene
>>> C.window
<bpy_struct, Window at 0x7f842eee2f88>

>>> C.window.scene
bpy.data.scenes['Scene']

>>> C.window.scene = D.scenes['Scene.001']
>>>

so in this case will try subscribing to the "scene" property of the Window class.
_I am not aware of anywhere that changing foo.scenes.active sets the context scene.  For example there is no bpy.data.scenes.active.
Search for other msgbus examples for other subscription to try.  AFAIK it is still the case that you cannot get notification of the instance object, so it is garnered from context.
import bpy
from mathutils import Vector, Matrix

handle = object()

# Triggers when window's scene is changed
subscribe_to = bpy.types.Window, "scene" #

def notify_test(context):
    print(context.scene.name)

bpy.msgbus.subscribe_rna(
    key=subscribe_to,
    owner=handle,
    args=(bpy.context,),
    notify=notify_test,
)

bpy.msgbus.publish_rna(key=subscribe_to)

to the rescue again, thank you!

@batFINGER im curious.. how did you know this syntax? subscribe_to = bpy.types.Window, "scene" where is this documented? trying to find something to notify me when i select a keyframe in the Graph Editor.


text:
How to make a Python operator as a Slider?
I am in the process of finishing an add-on I have been making and I am trying to work on some final tweaks. I am wondering how I can make a Python operator that is a Slider which controls the x, y, or z position of the selected object. Something like the image below except that controls position specifically.

Q: How to make a Python operator as a Slider?

Set slider property to True
Consult the docs on UILayout.prop,

prop(data, property, text="", text_ctxt="", translate=True,
icon='NONE', expand=False, slider=False, toggle=False,
icon_only=False, event=False, full_event=False, emboss=True, index=-1,
icon_value=0)

To display the property in the UI  set it to True.  The default is slider = False

slider (boolean, (optional)) – Use slider widget for numeric values

Sample code
def draw(self, context):
    self.layout(context.object, "prop", slider=True)

Make sure to set the minimum and maximum of the property, if unset the default values are +/- the maximum possible value on your system and as a result the slider will sit around the middle and be somewhat meaningless.
Tip: Edit Prefs > Interface > Display and enable "Developer Extras" will enable you to right click over any (most) UI element and view source to open the code behind the UI into the text editor.


text:
How to create fire materials using the new Principled Volume node that visually look the same as the "old method" of fire materials?
There is a new volumetric shader node called "Principled Volume" in Blender 2.79 as of this commit. It appears to support a new temperature attribute, using blackbody temperature.
Using the more or less familiar setup as pictured below, I can get a good enough material, but I would like to know how to achieve the same result with this new shader node.
"Old method" and result:

Setup with Principled Volume node:

Here is the current file to play with.
It does require a current (as of 3/5/18) buildbot build to use the shader.

The question:
How do I set up a material with the Principled Volume node that renders visually the same as the old setup?

I will see if I can play around with this soon, but in the meantime there are a couple of things that look off to me. The flame-heat-colorramp group of nodes is connected to the emission color in the first setup, and the volume color in the second. The first setup also has a much higher emission strength than the second (may have to be this way, not sure yet). Finally from the link you posted I think the blackbody input should be connected to the flame attribute. I will test this when I can and update accordingly.

Would you be able to add your blend file? That way it will be easier for me to try and match the initial result rather than trying to recreate what you have and then match it.

@Brenticus see my edit, have added the file as requested. Haven't had time to test flame to blackbody input, but will look at that.

Here is my final result.
The result using the first node setup:

And the result using final principled setup:

Let me start of by saying that smoke simulation and rendering is not something I am very familiar with, so despite being able to replicate the material fairly well, I don't necessarily understand everything behind why it works the way it does. But I'll explain what I can.
A quick summary of what I did:

Left the default color as white, and used the colorramp as the input for the Emission Color.
Increased Emission Strength to the value you had, but then dialed it back some as it was too strong. I noticed that the two images aren't exaclty the same, and further reducing the Emission Strength could probably fix that.
Increased the Density to half of the value you used in the first setup, as this looked closest.
Left everything else as the default. I tried changing the color and temperature attributes, as well as the Blackbody settings, but they seemed to have no effect with this setup.

So, from what I understand at the end of this, the Principled Volume Shader is basically setup to replicate the original node setup you have, and it does it well. There does appear to be some differences in how the shader works compared to the old method, namely in how the density works. I noticed that (before emission was added, which made the details hard to see) the Principled smoke looked more dense than the manual smoke, but if I decreased the density it would get to the point of areas being nearly transparent before the main density looked similar. More details were visible in the principled smoke, and since in this setup the smoke was colliding with the domain, the principled setup had more defined boundaries, whereas the manual setup was much less defined. Perhaps with some experimentation, or a better understanding of how the shader works, as my knowledge is limited, a more similar result could be achieved.
The good news in all of this is that smoke is now much easier to setup, as the final setup I arrived at was just this:

Hope that helps!

That's a good way to think about it. In this case then the color input would be the smoke color, which makes sense. The color ramp is what defines the color of the fire. Without it it's essentially black and white. From what I have read, the heat/flame attribute should be connected to the blackbody, just in this case with the intense emission there was no visible change, so for the sake of simplicity I left it out, and also in case I got it wrong.

I just realized that I never tried connecting the flame to the Blackbody tint, only to the intensity. That makes sense the more I think about it, and increasing the temperature would make the effect more noticeable. I'm liking the results so far with this node.

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


text:
What is the difference between Sobol and Correlated Multi-Jitter sampling patterns?
In Cycles we have two options for sampling patterns. The default is Sobol, there is also Correlated Multi-Jitter.
The manual  has this to say about sampling patterns:

Pattern
Random sampling pattern used by the integrator.
Sobol
Uses a Sobol pattern to decide the random sampling pattern used
by the integrator. See Sobol sequence on Wikipedia for more
information.
Correlated Multi-Jitter
Uses a Correlated Multi-Jitter
pattern to decide the random sampling pattern used by the integrator.
See this Pixar paper for more information.

After reading these links in the manual,  it is not any clearer if one sampling pattern is better to use, or more efficient than the other for certain scenes, shader types, sample counts, or lighting setups, or any other factors.
What exactly is the difference between the sampling patterns available when rendering a scene in cycles? More specifically, why would one change it from the default Sobol to Correlated Multi-Jitter?

In 2013 there was a long debate in a blenderartists thread, where some argued that for some scenes Correlated Multi-Jitter is better than Sobol, while others saw no real difference.
Cycles creator Brecht van Lommel was initially skeptic, he wrote:

These correlated multi-jitter vs. Sobol comparisons so far seem to confirm my own findings, which is that neither sampler is consistently better or particularly different even (...). Conclusion seems to be that the sampler sequence we have now is about as good as it's going to get, though it's nice to have a second good quality sampler implemented in the code as a sanity check for me.

But later he was convinced, and wrote:

Ah, I missed those comparisons. It seems indeed correlated multi-jitter is handling BSDF x mesh light source sampling better. Maybe that's something that can be fixed in Sobol, need to investigate.

One of the scenes where Correlated Multi-Jitter was better, was a diamond scene from BlendSwap. I wanted to see if the Sobol improved since 2013, so now (December 2016) I repeated the test with Blender 2.78a, but I still see a large advantage for Correlated Multi-Jitter.
100 samples, Sobol:

100 samples, Correlated Multi-Jitter:

The rendering time with Correlated Multi-Jitter was 6% longer than with Sobol, but there is considerably less noise in the image. There are some  fireflies, but they should be easy to filter in post, because their color so drastically differs from the surrounding pixels. Here's the Correlated Multi-Jitter post-processed with a very simple image filter that only removes single-pixel noise:

On the other hand I saw no examples where Sobol was considerably better than Correlated Multi-Jitter, so in general it might be a good idea to change the default setting.
Also note that there is some work going on in the sampling area, for example Blue noised dithered sampling and Micro jitttered sampling. These are planned for 2017.

@cegaton Thank you for the extra points :) About the filter: I didn't want to push my own software, but I actually wrote an open-source 2D image editor (Pixelitor, http://pixelitor.sourceforge.net/), and I like to use it, because I know exactly how it works. This has a simple filter called "Reduce Single Pixel Noise" which for each pixel (and within a pixel for each R,G,B channel) examines the 8 neighbors, and if it's a minimum or maximum, the pixel value is replaced by the next minimum or maximum of the neighbors. Works only if the fireflies are not neighbors.

Perhaps it will help you to know how sampling actually works:
When light is hitting a (let's say) diffuse surface, it is scattered in all directions. Each photon will leave the material in a different direction. Since the sun emits about 10^45 photons each second, consider this as an infinite amount. According to this, the following picture should have an infinite amount of arrows:

Calculating the color of that surface point is basically an integration. (Let's leave out more bounces since each bounce of each ray has also to be integrated). Since there is no way to calculate this at all, Cycles uses the Monte-Carlo integration as an approximation of the end result.
Short version of the Monte-Carlo-integration: Use random sample points and integrate them (in this case by averaging them). According to the Law of large numbers, with time the result will converge.
But taking fully random points isn't that a good idea. So, Cycles instead uses a Quasi-Monte Carlomethod. The difference is, that it doesn't choose its sample numbers (pseudo-)randomly, and replaces them with less random, but better values. This makes sure for example that no region will be sampled significantly more often than others.
The pattern for getting the random values Cycles uses is called Sobol. Compare the two images in the the Wikipedia article and you can see easily why it is better suited. The pattern of Multi-jitter sampling looks really similar to the sobol one, that's why the difference isn't that noticeable.
Each pattern has two important properties: The speed at which it converges (the number of samples you need until it's more or less noise-free) and computation time. How the sequence converges depends heavily on the data you are integrating. That's why some scenes work better with one than another.
Sadly, I can't tell you how to chose your sampling pattern beside trying it out (yet).
EDIT
The paper about Correlated Multi-Jitter says:

We have presented a modification to jittering and multi-jittering that greatly
  reduces the noise in rendered images at higher sample counts while gracefully
  degrading to unstructured noise at low sample counts.

I found this comparison of both methods showing that there is a difference, but it is barely noticeable (to me, in that scene).
Also note from that answer:

For Sobol this works if the number of lights is a power of two, for Correlated Multi-Jitter it works for any number of lights.

This will affect how you set up your sample count depending on light count. For branched path tracing, it is different too.

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


text:
How can I change default file save locations?
I would like to know if there is a simple way to have Blender (ver. 2.76b)save .blend files to a specified location by default. After install, my .blend files always saved to my \documents folder but as of sometime last week, I noticed them also ending up in appdata\local\microsoftwindows\temporaryinternetfiles\
I'd like to change this so that I have a dedicated Blender location, docs, pics, and so on. This answer How do you change the default directory for saving/opening files? says it can't, but I'm hoping something may have changed in the builds since that question was answered.

Head over to your User preferences here :

Extra Tips:
Or you could typically move the windows folder with "mklink" using windows
command prompt. Search google for makelink windows tutorial and you be really
powerful at managing your memory resources.


text:
Sample NURBS curve at distance from start for x,y,z coordinate
Using a modified version of the script found here:
Poly / Bezier curve from a list of coordinates
import bpy

# sample data
coords = [(0,0,0), (2,2,2), (3,3,7)]

# create the Curve Datablock
curveData = bpy.data.curves.new('myCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 2

# map coords to spline
polyline = curveData.splines.new('NURBS')
polyline.points.add(len(coords))
for i, coord in enumerate(coords):
    x,y,z = coord
    polyline.points[i].co = (x, y, z, 1)

# create Object
curveOB = bpy.data.objects.new('myCurve', curveData)

# attach to scene and validate context
scn = bpy.context.scene
scn.objects.link(curveOB)
scn.objects.active = curveOB
curveOB.select = True

bpy.context.object.data.splines[0].use_endpoint_u = True
bpy.context.object.data.fill_mode = 'FULL'
bpy.context.object.data.bevel_depth = 0.1
bpy.context.object.data.bevel_resolution = 5

I am able to create the following NURBS curve from a list of vertices.

What I would like to do is get an x,y,z position along that curve at a known distance from the start. For example, starting at the first point, (0,0,0), what would be the x,y,z coordinates 3 units up, along the curve?


text:
Is it possible to disable the mouse wheel?
I don't see any way of disabling the mouse wheel, or at least to make it not control the zooming. The reason I need to know is that my mouse has an extremely sensitive wheel and I end up zooming in and out uncontrollably when I'm just trying to rotate the view, which is obviously something I need to constantly do. I used some registry edit method to disable the mouse wheel but it only seems to affect some programs and Blender is not one of them. I'd appreciate any help.

Sounds like you need a better mouse.

It should be doable by removing (or changing) the Key Bindings in Blender. Go to File -> User Preferences -> Input and look for any Key Binding which is connected to the Wheel of the mouse. Like this:

In the example I'm deleting the binding for the Zoom in 3D View only. So in 2D Editors, you could still use it if you like. Otherwise, you'd need to remove it section by section.
To get it back, use the Restore button that shows up after you change or delete a binding (it will stay there as long as your keymap is different to the Defaults). If you want to keep your Blender Prefs this way, click Save User Settings


text:
Animate a Bezier curve deforming a mesh, without the mesh awkwardly rotating
I've successfully set up a mesh that's deformed by an animated Bezier curve, with the help of the Animation: AnimAll utility, with one caveat: the mesh rotates inelegantly about the curve as it animates, in all available "Twisting" options.  Ideally, I'd like to implement and distribute my own option with the following formula:
t = dot(v, axis)
v' = b(t) + rotationMatrixBetween(axis, b'(t)) * (v - b(t))

Where v and v' are input and output vertices, respectively, and b is the cubic Bezier curve function.  This has the effect of rotating every vertex by the same quantity that the associated Bezier tangent is rotated from the chosen axis, giving a relatively stable animation.
So the question is, is it possible to implement an additional Twisting Mode as an addon to Blender?  (Using the formula I described, ideally.)  Or, is there a better alternative to achieve what I want?  I'd like to export models consisting of simple shapes deformed by animated Bezier curves for the project I'm working on, and the formula I described is the one that I'm using.
Things I've checked or investigated:

Both the model's and curve's origin are at (0, 0, 0).
I've attempted all three twisting modes with every combination of "Bounds Clamp" and "Stretch", all with the same issue (understandably.)
Browsing the source included with the release distribution hasn't been terribly enlightening for my use case.  A full search reveals a twist_mode being set from the UI and in an import script, but not where it's used.
I could swap to a standard skinning approach as a last resort, but it's far more meticulous to create content with than what I'm wanting (which is, "ridiculously simple", Blender integration issues hopefully notwithstanding.)

UPDATE: Here's the packed blend file, as requested.
UPDATE AGAIN: browsing the actual source (now that I've found it) reveals an entirely C implementation of twisting that can't be extended without recompiling Blender (assuming bevel-handling code in curve.c handles all twisting, bevel or no.  I believe it is.)  I believe "Minimum Twist" without correction for the first point would work well enough for me, if I could change it!  Otherwise, maybe there's some way into tricking Blender to not correct for the first tangent in the curve?

can you  attach an example blend file ( i think people will back off helping to avoid recreating the scenario to start experimenting )

Thanks for the suggestion, link is now included.  Yeah, I figured this is asking a lot.

Maybe try different initial obj rotations in the curve like 0,90,0 and so on.

It is doable as scripting, probably using to_track_quat way.
but an easier way is to use Animation Nodes ad on.
That is a visual / nodal scripting tool really.
There you have a set of spline tools to deal with bezier from creating  to extracting data in any way. More than usual Blender tools.
Specifically for this orient/twist situations, there is a Direction to rotation Node that turns 2 vectors into rotation. Unlike the Blender "Z up" to track quat , it provides a second "guide" direction that can be related to anything.
(I redesigned that node precisely for these problems)
In the example file, one orientation (Z) is the tangents, the other (Y) is controlled by the empty in the back.
-
Here's a file with a possible setup do do what you need.
spline deform AN
You need Animation Nodes to make it work.

A very basic setup, cause you can further combine or animate those too. Or, for example may deform only the points closer to spline, not the far away (as xy here) or vary the second rotation along the spline etc.

I can't get the node tree to work with A.N 2.0. Can you update your answer ?

Sorry for the very late accept, this looks extremely nice. Will try it out once I've changed gears, thank you!


text:
Adding a conical bevel/fillet to a mesh?
Given this mesh: (assume 18mm x 18mm x 12mm approx.)

Is it possible to add a conical fillet (rounded bevel) to the vertical corners?
The cone of the fillet would be 1.85mm - 0.7mm from top to bottom.
Any pointers would be gratefully received.
This image below shows what I'm trying to model (I'm only modelling the outside faces, not the interior socket pieces):

Ideally, I'd also like to add a 0.7mm rounded bevel, which you can see running all along the top edge (as you see here)
Update: Mesh generated by openscad
The mesh shown in Blender:

The original geometry was generated as CSG in OpenSCAD
// SA Row 3
difference() {
     intersection_for(n = [1 : 4]) {
          rotate([0, 0, n * 90]) {
               translate([24, 0, 0])
                    sphere(r = 33, $fn = 90);
          }
     }
     translate([0,0,46]) sphere(r = 33, $fn = 90);
     translate([-33,-33,-64]) cube(66);
}

Just to give a clear indication that all the surfaces are (save for the base,) sections of a sphere. (note $fn is the resolution/polycount)

Might be interesting: http://blender.stackexchange.com/questions/28042/how-to-model-a-keyboard-key

These are spherical keys, so they need a different modelling style.  The main faces are created with 4 intersecting spheres and then a difference operation with another sphere to create the spherical dip in the top.  That's the easy part.  Filleting the edges is all I need now.  Really appreciate the additional feedback all the same.

@zeffii - Files are at https://github.com/getclacking/SA-profile-keys-3D-models

@zeffii - thats correct, conical fillet, radius changes size from 0.7 to 1.2mm from bottom to top.

@zeffii - you can see it in the photograph, also see here http://www.keycapsdirect.com/pdfs/SAFamily.pdf

I was wondering if I should be modelling this using Nurbs surfaces instead of going the CGS route...

The bottom has to be sliced off, but the rest of the faces are spherical chords

Blender doesn't currently (Nov 2015) have a fillet that does variable radii, but you could approach the same effect with the Subdivision surface modifier to some degree. If you guide the geometry the result will look quite good.
My approach would be to Shrink-wrap a Polysphere over the exported Object.

Below:

On the left is the original import,
in the middle is a polysphere (a Cube subdivided a few times and then vertices are transformed with a 'To Sphere' operation),
to the right is the result of a Shrink wrap from the Polysphere onto the Original geometry

With a bit of experimentation with the ShrinkWrap modifier and tweaking of the Polysphere, you could get very close to what is desired. Because Blender isn't a solid modelling CAD program it is bound by the underlying topology with respect to what can be filleted nicely.
Even on this mesh adding a Subdivision Surface modifier produces visually OK results, this probably doesn't meet tolerance requirements.

Tweak the polysphere (translating up/down mostly) and the offset value, till it approaches acceptable results.
The ShrinkWrap object's shape is important
You'll find that being more specific about the geometry of the Shrinkwrap object will help the eventual wrapped geometry. Here i started by making a copy of the 8 extreme vertices of the imported object, and make a Cube using those vertices. Subdivide the sides and scale extruded the top inwards.

That would work well enough, this is a project only for mocking up key cap designs, so as long as they're rounded at those top corners it will look right.

I checked the .blend, the rendering still looks sharp, anything I need to tweak?

Yes! The results are good enough for my use case.  Thank you

And this is a great approach :)

I can't see the topology of your object but something like that can probably be done simply selecting top/bottom edge circles and 4 side edges, and using bevel command (CTRLB), eg: scrolling with the mouse wheel to increase subdivisions...

Topology on my object is a very dense mesh, the faces are spherical chords (I don't know if that's the correct name for them.) as opposed to cylindrical chords. Not sure if that will make a difference.  The main thing is to change the radius of the side bevel as it goes from top to bottom.

Oh also the top is concave, not flat.

I'll post a wireframe render soon

Wireframe / Mesh view added to question.  I'll add the csg for reference


text:
take screenshots programmatically in bge?
import bge

from bge import render, logic

def makescreenshot():
    path = logic.expandPath("//")

    def main():

        cont = bge.logic.getCurrentController()
        own = cont.owner

        render.makeScreenshot(path+"image.png")

    main()
makescreenshot()

^This is the code I have to take a screenshot of the current scene and I want to connect this with an always sensor to the camera, but the only way I know to do so is by using bpy...is there any way to take screenshots using bpy or is there any way to add logic bricks using bge?
Thanks!

You want to create logic bricks setup in Blender? I think that is possible. I can remember someone published a generator to be used by the node editor. Btw. makeScreenshot() supports "//" already and the code does not benefit from the nested function "main". So you can get really simple code. - edit: I just checked he generated the python code not the bricks. - sorry

The Blender API http://www.blender.org/api/blender_python_api_2_75_3/bpy.ops.logic.html contains something like this: bpy.ops.logic.controller_add(). It might help you to investigate further.

In Bge you can indeed add an always sensor and link it to the python script


text:
What is the reason these two UV maps interfere with each other?
The selected face shouldn't be painted with the text "This" from the third texture of the material (see in Property region on the right):

There are two UV maps used for the cube mesh, one for the full cube (6 faces), one for the top face alone. The material includes three textures, the two first ones (background colors and white dots) are to be used with the full cube UV map visible in the middle panel, the last one is the text, also visible in the middle panel. Its map is the large square around it.
The selected face, and the other faces except the blue one, keep receiving the portion of the circular text they would receive with the full cube map. What's wrong?
Using Blender Internal (2.79).
File is available here.

Does that happen even at render mode? Also, please show us the list of UV maps.

@Allosteric: It's the same on the rendered image. UV maps visible on this second screenshot.

I tried a similar setting and didn't reproduce. Why not upload your .blend if you don't mind.

@Allosteric: I added a link at the end.

The problem is that your UVMap Face 1 is actually mapping the Face 1.png

In your list of UV Maps, select the UVMap Face 1.
In the 3D view, select all the faces except the dice face 1.
In the UV/Image editor, press W twice (Weld) and move the dot to some where safe(transparent)

That'll resolve your problem.

This works as intended, thanks. However I don't understand why UVMap Face 1 was created with coordinates for other faces, as I think I selected face 1 only before unwrapping. I expected the UV map would only contain selected vertices, as explained here: "Begin by selecting all faces to be unwrapped in the 3D View"). It's very confusing, and I don't get a correct understanding of how UV maps are used by Blender.

@mins I'm not quite sure, but I think any new made UV map will copy a previous UV map. As far as I observed, the very first UV map is weld in the left corner (by default) but the subsequent maps mimic the previous ones


text:
Create still copies of a moving object (using python scripting)
I have an object A that is constrained to move on a path and I want to create still copies of it while it moves on the path. I tried the following code but it failed. In particular, it arbitrarily moves the object A itself and all the copies go crazy. Could you please help me fix this? Thank you!
A = context.active_object

for i in range(1, copies_number+1):

    A.constraints["Follow Path"].offset_factor = (i-1) / (self.copies_number-1)

    A.constraints["Follow Path"].keyframe_insert(data_path='offset_factor', frame=i)

    copy = duplicate(A) #this is a function that I have introduce to duplicate objects

    bpy.context.view_layer.objects.active = copy

    bpy.ops.object.visual_transform_apply()

    for constraint in copy.constraints:

       copy.constraints.remove(constraint)

Without operators
Here is an example of doing this without operators.

Have the constrained object as active
Create a copy, strip the follow path constraints from it.
Create all the copies needed from the copy
Loop thru the copies,

calculate the frame,

set and keyframe offset based on frame

change to that frame

give the copy the same matrix world as original at that frame

link copy to collection

Test script:
import bpy

N = 10 # number of copies

context = bpy.context
ob = context.object
scene = context.scene
collection = context.collection

copy = ob.copy()
cons = [c for c in copy.constraints if c.type == 'FOLLOW_PATH']
while cons:
    copy.constraints.remove(cons.pop())
copies = [copy.copy() for i in range(N - 1)]
copies.append(copy)

frames = 250
for i, copy in enumerate(copies):
    f = i * frames / N
    # find constraint properly 0 for example sake
    ob.constraints[0].offset_factor = f / frames
    ob.constraints[0].keyframe_insert("offset_factor", frame=f)

    scene.frame_set(f)
    copy.matrix_world = ob.matrix_world
    collection.objects.link(copy)

Amazing thank you very much! By the way, I found the mistake in my code. I am not deselecting everything and then selecting only the copy. If I take care of this selection business then it works. I am not sure if I am supposed to ask this here, but is it also possible to remove from each copy any possible drivers that the copies might inherit from the original object (in case the original object has any drivers)? We remove the constraints from the copies, but I do not know if it is also possible for drivers. Thank you!


text:
How to visualize reflection of a beam or ray
I need to know how light is reflected on the objects given a fixed spot as light source. The best way would be to render a laser beam, however such laser beam is not easy to design/render and heavily depends on the rendering engine. So I need a more easy possibility to check. Do you have an idea how this could be achieved?
I am using Blender 2.8.

Are you using 2.8 or 2.79. How would you handle refraction, diffuse, rough glossy? Anything where a beam would "split".

A laser beam should not be visible until it get reflect by something. The dust in air is the most common thing that "catch" laser. What you looking for might be the volume rendering and small angle spot light. Both are pretty complicated in CG.

Searching on BSE might give you some ideas https://blender.stackexchange.com/search?q=laser

If I understood, you are looking for a representation of a single ray, without the use of render engines.
You can create geometry with python, which is raycasted. I modified the script from this laser question to create an object, which contains the laser as geometry.

Start with the first "hit" point at (0, 0, 0) and the casting direction (0, 0, 1) in the objects orientation. The following steps are

Use the scenes ray_cast method to cast a ray. Get the hit position and the normal of the hit face.
If the normal is on the side of the incoming ray, reverse it. The resulting angle between direction and normal ray will be < 90°.
Get the difference between direction and normal ray. Rotate the direction ray twice by this difference. The direction ray is now "mirrored" along the inversed normal ray.
Inverse the direction ray. This is the new direction ray in which direction we cast from the hit position.

import bpy
import bmesh
import mathutils

EPSILON = 0.00001
MAXIMUM_ITERATIONS = 50
OBJECT_NAME = 'light_plane'

def get_create_object(scene):
    ob = scene.objects.get(OBJECT_NAME)
    if ob == None:
        me = bpy.data.meshes.new("me")
        ob = bpy.data.objects.new(OBJECT_NAME, me)
        scene.collection.objects.link(ob)
    return ob

def do_raycast(scene):
    object = get_create_object(scene)
    points = [object.location]

    _, rot, _ = object.matrix_world.decompose()
    direction = mathutils.Vector((0, 0, 1))
    direction.rotate(rot)

    for i in range(MAXIMUM_ITERATIONS):
        origin = points[-1] + direction * EPSILON
        result = scene.ray_cast(scene.view_layers[0], origin=origin, direction = direction)
        hit, location, normal, index, ob, matrix = result
        if not hit:
            break

        if normal.dot(direction) < 0:
            normal *= -1

        rot_dif = direction.rotation_difference(normal)
        direction.rotate(rot_dif)
        direction.rotate(rot_dif)
        direction *= -1
        points.append(location)

    points.append(points[-1] + direction*10)
    bm = bmesh.new()
    [bm.verts.new(pt) for pt in points]
    bm.verts.ensure_lookup_table()
    for i in range(len(bm.verts) - 1):
        bm.edges.new((bm.verts[i], bm.verts[i + 1]))

    bmesh.ops.transform(bm, matrix = object.matrix_world.inverted(), verts = bm.verts)
    bm.to_mesh(object.data)
    bm.free()

for h in bpy.app.handlers.depsgraph_update_post:
    bpy.app.handlers.depsgraph_update_post.remove(h)
bpy.app.handlers.depsgraph_update_post.append(do_raycast)

In 2.9+ the Scene.ray_cast method takes different arguments. Replace the line with this for 2.9+
        graph = bpy.context.evaluated_depsgraph_get()
        result = scene.ray_cast(graph, origin=origin, direction = direction)

I'm not sure how to implement your script in my scene. It's created a light_plane object but I don't see the ray. I'm using Blender 2.93
Edit: I see that it's working in 2.81 in fact, so perhaps nevermind

@LukasKawalec I added two lines at the bottom of the answer.

May be relevant  https://blender.stackexchange.com/questions/91161/calculating-estimating-the-normal-at-any-location-on-a-face

I don't have enough reputation to comment on the Leander post.
I've modified the script to have several rays. It's naive and rusty, but there's an important detail - if you get your evaluated_depsgraph_get() every time you call a ray, you'll get stack overflow in Blender.
The rays on the screenshot are displaced manually, script doesn't do that.
Trees models by reymarch.
Other than that fix, the rest modification is pretty trivial:
import bpy
import bmesh
import mathutils

EPSILON = 0.001
MAXIMUM_ITERATIONS = 4

OBJECTS_AMOUNT = 9

def get_object(scene, name):
    ob = scene.objects.get(name)
    return ob

def do_raycast(scene, graph, object):
    #object = get_create_object(scene)
    points = [object.location]

    _, rot, _ = object.matrix_world.decompose()
    direction = mathutils.Vector((0, 0, 1))
    direction.rotate(rot)

    for i in range(MAXIMUM_ITERATIONS):
        origin = points[-1] + direction * EPSILON
        #graph = bpy.context.evaluated_depsgraph_get()
        result = scene.ray_cast(graph, origin=origin, direction = direction)
        hit, location, normal, index, ob, matrix = result
        if not hit:
            break

        if normal.dot(direction) < 0:
            normal *= -1

        rot_dif = direction.rotation_difference(normal)
        direction.rotate(rot_dif)
        direction.rotate(rot_dif)
        direction *= -1
        points.append(location)

    points.append(points[-1] + direction*10)
    bm = bmesh.new()
    [bm.verts.new(pt) for pt in points]
    bm.verts.ensure_lookup_table()
    for i in range(len(bm.verts) - 1):
        bm.edges.new((bm.verts[i], bm.verts[i + 1]))

    bmesh.ops.transform(bm, matrix = object.matrix_world.inverted(), verts = bm.verts)
    bm.to_mesh(object.data)
    bm.free()

def raycast_all(scene):
    graph = bpy.context.evaluated_depsgraph_get()
    for i in range(1,OBJECTS_AMOUNT+1):
        ob = get_object(scene, 'ray' + str(i))
        if ob is not None:
            do_raycast(scene, graph, ob)

for h in bpy.app.handlers.depsgraph_update_post:
    bpy.app.handlers.depsgraph_update_post.remove(h)
bpy.app.handlers.depsgraph_update_post.append(raycast_all)


text:
How come edge loop select does not work?
I try an Edge loop select in the following object. But Blender 2.79 does not select anything, are there any hidden parameters which can influence edge loop select?
(I try this from the Select menu in Edit mode)

Loop selection doesn't work with triangular topology, because at an intersection, it can't determine which path to choose.
You can convert the topology to quads with the Tris To Quads function (select all the faces then Alt+J).

Sorry not working, see updated post above. IMHO the algorithm always should decide based on least arc difference which way to go, the challenge keeps the same for quad based geometry.

Based on what i see in your second screenshot, it should work. Maybe you've got some duplicates (try W/Remove doubles). Consider uploading your file if you can.

It is working now on some edges but not the whole loop, maybe the arc tolerance is very low.

Oh, I see, there are still some tri type faces in the converted. So it really must made sure all adjacencies are quad faces at least.

There is no arc tolerance, this tool is based solely on topology (in a mathematical meaning : what is connected to what), not on position. Source : https://stackoverflow.com/a/7202140/10972299

If it's possible to convert to quads, then loop select, then why can't the algorithm use the same (convert to quads) in the background and try to emulate the behavior non-destructively. I think that is the expected behavior,


text:
How to select a near by face without its center being in view?
I have a big model and I am zoomed in the view, so I can not see the center of a face. Usually I select a face in Edit mode by clicking its center dot. But how can I select a face, let us say by nearest to mouse point. The images below show the situation (Unselected, Selected, Center of face).
Edit: It turns out selection with RMB is not working only for my model, I will check what might be the reason for this.

Blender 2.77

If you activate the mesh select mode "face" you just (right) click on any face area, it should be selected...

Unfortunately this is not working for faces which extend the view. When the face is fully in view I can Right-Click or press B to select with a box.

could you share an example blend (eg with: http://blend-exchange.giantcowfilms.com/) , with the view set as you say?

You are right it is working with a new model but not in my complex model which I can not share here. I will have a look deeper to be able to reproduce what might make the problem.

ok. check doubles, normals, loops... too.

The mesh has a couple of Boolean operators in it, but I can not detect any problems. But thanks for your quick suggestions.


text:
toggle Object Mode <-> Pose Mode by script code
I want to toggle Object Mode to Pose Mode by script code, because I usually run blender in Object Mode but sometimes I need to add some keyframes while I run blender. that is why I want to toggle Object Mode to Pose Mode by script code. plz help T_T
I Used and combined this codes.. let me know how to solve it sir T.T
bpy.ops.object.select_all(action = 'DESELECT')
bpy.ops.object.select_by_type(extend = False, type = 'ARMATURE')
bpy.ops.outliner.item_activate(extend=False, deselect_all=True)
bpy.ops.object.posemode_toggle()
bpy.ops.pose.group_select()
first_Bone = bpy.data.objects['Armature'].pose.bones["first_bone"]
first_Bone.select_set(True)

Probably the easiest way for you to toggle between Object Mode and Pose Mode is to simply call bpy.ops.object.posemode_toggle() again. If you're in Object Mode, that will switch you to Pose Mode. If you're in Pose Mode, then you'll go to Object Mode. Here is a link to the Blender 2.83 API, though unfortunately the description is sparse.
Here's a quick script you can run to test, where here I've also created an armature and showed one way to move it via keyframing (since it seems like you were interested in doing that).
import bpy
from mathutils import Vector

# Make armature
bpy.ops.object.armature_add(enter_editmode=False, location=(0, 0, 0))
arm = bpy.context.object

# Enter pose mode.
bpy.ops.object.posemode_toggle()

# Assign keyframes to the armature.
arm.pose.bones['Bone'].keyframe_insert('location', frame=0)
arm.pose.bones["Bone"].location += Vector((0,2,0))
arm.pose.bones['Bone'].keyframe_insert('location', frame=20)
arm.pose.bones["Bone"].location += Vector((0,0,2))
arm.pose.bones['Bone'].keyframe_insert('location', frame=40)

# Return to object mode.
bpy.ops.object.posemode_toggle()

If the code above is in a file test.py, then run blender -P test.py.
If the last line is commented out, you will see this when Blender opens in Pose Mode:

If you leave it un-commented in the code, then you will see this when Blender opens in Object Mode:

Oh thank you very very much!! I understand what you mean. Thanks for your Answer!! 8-)

Sounds good. If this answer worked for you, please consider accepting it. @DeerWorld


text:
Open Blender GUI from .py script
Can I open GUI window from bpy module and control scene from script?
Example:
import bpy
bpy.context.window_manager.windows["Default"].open()

@batFINGER i just want open Blender window from .py script in Linux and use same bpy in script and in window (blender builded as module already)

Suggest changing title of q to "Open GUI window from bpy built as python module".  Going by This is mainly limited to features which can be usable in background mode, so you cant for instance do OpenGL preview renders. from https://wiki.blender.org/index.php/User:Ideasman42/BlenderAsPyModule my guess is you can't.

Blender built as a python module does not support a gui interface, it's runs as if blender was started in background mode. You can verify this by checking the background value
>>> import bpy
>>> bpy.app.background
True

If you are working on an addon, you can edit the scripts and then  disable/enable the addon to re-load the changes in blender. You may also want to look at the notes on remote debugging using eclipse.
You can open a text file in blender and run it as a script, you can reload the file after changes and then run it again. You may find the addon I link to in this answer helpful, the other answer there shows how to run a script straight from the file in blenders python console.


text:
Incorrect render image

Hey there! Can you solve this problem? Scene is looking OK in rendered viewport, but something messed in final render. I am using volumetric matherial only in the ocean.

Try looking in the outliner to see if something that is hidden(the eye is grayed out) is set to render(the camera icon is NOT grayed out).  If you want to hide this object you can click the camera and it will not render in the final render.

The problem was in the hidden cube, which i've used in the boolean oprations and hadn't diasable for rendering. Thank you.


text:
How to update the dependencies of a driver via python script?
i need to be able to update the dependencies of my drivers via script, does anyone knows how to? thank you very much in advance!
my script works on changing the values of the drivers , but sometimes i may need to update
import bpy
import random # Random floating point number between lo and hi
def randf(lo, hi):
    return random.uniform(lo, hi)
bpy.app.driver_namespace["randf"] = randf

could you provide a script mwe?

import bpy
import random
Random floating point number between lo and hi
def randf(lo, hi):
return random.uniform(lo, hi)
bpy.app.driver_namespace["randf"] = randf

@miceterminator

Can you clarify "driver dependencies"  Is what is referred to as  the_"update"_ effectively the result of re-running script above, ie setting ranf to another float between 0 and 1, How /  when to flag the update?

@batFINGER  you know the button "update dependencies" in the driver panel in the graph editor? i wanted to access that one. by the way , somebody already gave me a solution : https://blenderartists.org/t/driver-update-dependencies-via-script/1126347

Here, an awesome guy gave me the solution!

Looking at the source code, the button appears to be a direct function
  rather than a python operator:
but = uiDefIconTextBut(block, UI_BTYPE_BUT, B_IPO_DEPCHANGE,
ICON_FILE_REFRESH, IFACE_("Update Dependencies"),
0, 0, 10 * UI_UNIT_X, UI_UNIT_Y,
NULL, 0.0, 0.0, 0, 0,
TIP_("Force updates of dependencies"));
UI_but_func_set(but, driver_update_flags_cb, fcu, NULL);

The way I update a driver in my add-on is by adding and removing a
  space on the driver’s expression attribute. As far as I could tell, it
  acts the same way:
driver.expression += " "
driver.expression = driver.expression[:-1]

When I had the same issue during driving a node group node (mixShader), I solved it by finding the expression in bpy.data and just setting it to the original expression.
More or less a same hack as Francesco Shanigawe Kobane, but saves one line.
bpy.data.node_groups["<NodeGroup>"].animation_data.drivers[0].driver.expression = '<expression>'

thank you so much @aventau for the answer! gonna try that!


text:
How to set origin to selected vertex for 2D shapes (fast) ? (blender 2.8 +)
is there a way to set the origin to selected vertex faster? (for both shapes and objects)
there are a lot of steps to do it right now and it's frustrating.
I found a similar topic but it's old and not working with blender 2.8 2.9 and ... .
an addon similar to this topic would be great.
Shortcut for setting origin to vertex
thanks for your time.

AFAIC the addon linked to https://blender.stackexchange.com/a/134460/15543 does exactly this (written for 2.8, tested on 2.91).

thanks but it's not working with 2D shapes origin.

related: https://blender.stackexchange.com/questions/193145/how-can-i-make-a-custom-gizmos-to-set-the-origin/193202#193202

You can activate the "3D Viewport Pie Menus" vanilla addon,
there is a checkbox to enable "Origin Pie Menu" in its preferences.
Once activated, you can select a vertex/edge/face in Edit mode and with the shortcut choose to move origin to selection.

For curve objects: when you are in Edit mode, select a vertex, then in the Search menu search for the Origin to selection.

Move grease pencil origin to average of selection in edit mode.
_Note have not converted to operator or added shortcut, have simply pasted scripts into text editor and run via "Run Script" (play button).

I'm assuming by 2D shape you are referring to a grease pencil object.  The equivalent of method shown in https://blender.stackexchange.com/a/134460/15543 using GP is
import bpy
from mathutils import Vector
from bpy import context

ob = context.object
mw = ob.matrix_world

gp = ob.data
active_layer = gp.layers.active
active_frame = active_layer.active_frame
selected_points = [
        p for layer in gp.layers
        for frame in layer.frames
        for stroke in frame.strokes
        for p in stroke.points
        if p.select
        ]
if selected_points:
    cl = sum([p.co for p in selected_points], Vector()) / len(selected_points)
    for layer in gp.layers:
        for frame in layer.frames:
            for stroke in frame.strokes:
                for p in stroke.points:

                    p.co -= cl

    ob.matrix_world.translation = mw @ cl

Move grease pencil origin to 3D cursor loc in edit mode.
import bpy
from mathutils import Vector
from bpy import context

ob = context.object
mw = ob.matrix_world

scene = context.scene
cl = mw.inverted() @ scene.cursor.location
gp = ob.data
active_layer = gp.layers.active
active_frame = active_layer.active_frame
for layer in gp.layers:
    for frame in layer.frames:
        for stroke in frame.strokes:
            for p in stroke.points:

                p.co -= cl

ob.matrix_world.translation = scene.cursor.location

thanks for your time,i mean 2D curves,(in 3dsMax we use word SHAPE).

i've edited the "top answer" to be more accurate answer.

I see you have removed your comment doesn't work for 2D shapes there too.  Please instead  edit your own question using blender terminology like "2D curve" and "Control point" not vertex.

ok,sorry for that,and thank you.


text:
How to create a sawtooth flange?
For connecting parts I am thinking of a sawtooth flange. How could this be done by modifying a face of a cube or a cylinder? Please note there is a fine but important difference between a sawtooth and a simple thread.
In the end would like to 3D print this, however I am aware that it might be challenging for a printer.

Connected are both parts here. Usually these are plastics. The advantage is, you can still lose the parts by moving B in Z-Direction upwards.
The sawtooth is a special curve which might be achieved by a modulo function.
In the end I can imagine following solution:

Create a curve which is defined by a function
Apply the curve to a surface or mesh (this is known to me)

The question is: Is 1. supported by Blender?

I think it would be helpful to add an image of a 'sawtooth flange' for those of us unfamiliar with one.

Controlling geometry by some mathematical functions is done using Sverchok add-on, there's a big chance this can be done too.


text:
Why does the knife tool create random extra geometry?
The knife tool seems to be generating duplicate vertices, creating additional unwanted geometry. Is this a bug or related to camera or tool settings?
Any idea?

edit:
Clarifying the vert:

What extra geometry are you referring to? I don't see it in your illustration, just the geometry I would expect to see from using the knife tool.

@brasshat yes, the last selected vert I move around. I've added a still image to show the specific one.

One duplicated vertex and you call it a bug? When you use a knife tool how often does it happen? Frequently or in this case only?

@PaulGonet Not calling it a bug. Just asking if it is or something related to a setting someone might know. It happens randomly around half the time. I haven't been able to reproduce it consistently based on any setting or scenario,

That is just an expected limitation of detecting intersections with  mesh objects, some times it just fails to read depth or face intersections and an occasional extra vertex is created.

I can reproduce that same effect by extruding an edge, cancelling, and then using the knife tool.  Is it possible that the mesh has duplicate geometry?  Remove doubles maybe?  In other words, if the problem is repeatable enough for you to produce a gif, I would consider the mesh as being the culprit.

@Duarte Farrajota Ramos I have the same thoughts. FredLierman you may have accidentally pressed the LMB just before the knife snapped to the edge. That's all. Not a big deal here. BTW I wonder why this question have so many upvotes while some very valuable ones have less...

@PaulGonet "I wonder why this question have so many upvotes" Yeah, you got me wondering the same. I guess animated gifs are attractive, other than that it is pretty useless. Its like asking why there are bugs in software. Well obviously humans ain't perfect and mistakes are made.

@DuarteFarrajotaRamos thanks for all the suggestions. However there are no doubles and I'm not clicking middle mouse button.
The reason for the upvotes is possibly that this is a common issue/question.

try using line tool instead, it is pretty similar to knife tool, works pretty well and has some additional functionality, like create faces and objects
https://github.com/Mano-Wii/Addon-Snap-Utilities-Line/wiki

Link only answers are discouraged here. When posting an answer where you link to an addon or external resource please try to provide a short description of the page you are linking to, why it is relevant and what it does.


text:
How do I space quads evenly?
Is there a way in blender or an addon that allows me to select a bunch of faces (or verts) and evenly distributes (or relaxes) them into quads clean quads.
Without screwing up the vert ID/order.
Edit:
I would like to have the shapes of my quads to turn into perfect squares while maintaining the volume of the object and the vertex order.

I would like to have the shapes of my quads to turn into perfect squares while maintaining the volume of the object and the vertex order.

look for the edit button at the bottom of your Question's content and press it to make changes to your original Question.

I think it's impossible to preserve volume of the object and make all the polygons as perfect squares. Something will be sacrificed. One tool would be smoothing, but as modifier (either Smooth or Laplacian). It allows setting a vertex group which will control where smooth takes place; so several modifiers probably might change things a bit.

Select the inner Vertices, press W > Smooth and adjust Smooth Vertex settings:

You can also access Smooth Vertex operator settings via F6:

Another way is selecting a whole row or column of vertex and then Scale in X or Y axis to a factor or Zero with S > X + 0
Alternatively place the 3D cursor over the vertex you wish to align to, press . to transform relative to the 3D Cursor position, and then repeate the scale process described above. S > X + 0

That works great on a 2d surface like a plane. But on anything else it will loose volume. Smooth is essentially just relaxing the geometry.
I would like to have the shapes of my quads to turn into perfect squares while maintaining the volume of the object and the vertex order.

@user3730158 you should include the extra limiting criteria in your Question, so that people can give more exact answers.

... and so that they're not just wasting their time giving what turn out to be inexact ones.

You may also look into Laplacian Smooth which I believe has improved smoothing algorithms that better preserve volume while smoothing mesh.

LoopTools are great for this. It's an Addon which can be enabled in the User Preferences, it ships with Blender. To use it, select an Edge Loop, expand the options of LoopTools in the Tools Panel, and try the Relax Tool, like indicated here:

Using the Selection Mode the Relaxing will really only happen on selected vertices (can also be faces). Using Parallel it will operate on loops which are parallel to the selected one.


text:
Python Operator: Context is Incorrect
I currently am writing python operator whith the task of appending the current scene into a new file and then linking it back into the original file. There is one problem: When loading a new file the bpy.context changes and I do not quite know how to reload it. This leads to the error "context is incorrect" when trying to append the original scene into the new file. Here is how my code looks so far:
class BPC_main_Outsource(bpy.types.Operator):
    bl_idname = "scene.outsource"
    bl_label = "Outsource"
    def execute(self, context):
        compScene = bpy.context.scene #get scene
        bpy.ops.wm.save_mainfile() #save current file
        blendFile  = bpy.data.filepath #get path of current file
        apFilename = compScene.name #determine scene's name
        bpy.ops.wm.read_homefile() #load a new file
        oldScene = bpy.context.scene #get current scene in new file
        blendFile = blendFile.replace("\\", r"/")
        apPath = "//" + bpy.path.basename(blendFile) + "/Scene/" + apFilename #build append path
        apDirectory = blendFile + "/Scene/" #build append directory
        bpy.ops.wm.append(filepath=apPath, directory=apDirectory, filename=apFilename) #append scene from main file
        bpy.ops.scene.delete() #delete old scene in new file
        #TODO: save file, open original file, link back
        return {"FINISHED"}

Any help on how to fix this would be greatly appreciated. Thanks in advance.

How about, save the file, remove all scenes but the context scene, save the file to the new "scene" location, then reopen original.

Could be problematic because have to import the scene back into the original file (and there I also have to open a file & link/append a scene into it).

Does this help: http://blender.stackexchange.com/questions/6101/poll-failed-context-incorrect-example-bpy-ops-view3d-background-image-add

Thanks. I had a look at it before. No, it does not really help, it just covers how to fix trying to execute a Operator in an invalid area. In my case the problem is that the whole bpy.context is not accessible through the script (at least it seems like it).

Yes, I did. Well that is what happens when not double checking after trying to shorten a code segment to put it in a question... Thanks, edited it.

not sure why this received a downvote. perhaps you can explain what the purpose is of this script Paul? it seems a bit convoluted -- but you might have a good reason for it.

I currently am writing a AddOn which is supposed to allow users of it to "outsource" scenes (put them in an external .blend and link them back into the current file) in order to allow for versioning and multiple artists working on different (vfx) shots (scenes in .blend).

Script saves the current file, removes all scenes but the context scene and saves that to a file in the current blends directory with name "SCENE_<context.scene.name>" eg SCENE_Scene.blend for the scene.name of "Scene".
After which it reopens the original file, links to the scene in the created file, and deletes the original.
import bpy

class BPC_main_Outsource(bpy.types.Operator):
    bl_idname = "scene.outsource"
    bl_label = "Outsource"

    @classmethod
    def poll(cls, context):
        return bpy.data.filepath != "" and context.scene.library is None

    def execute(self, context):
        from os import path

        compScene = context.scene #get scene
        blendFile  = bpy.data.filepath #get path of current file
        clean_name = bpy.path.clean_name(bpy.path.display_name(blendFile))
        apFilename = compScene.name
        screen_name = context.screen.name
        scene_file_path = blendFile.replace(clean_name, "SCENE_%s" % apFilename)

        if path.isfile(scene_file_path):
            print("Scene file %s already exists" % scene_file_path)
            return {'CANCELLED'}

        bpy.ops.wm.save_mainfile()

        # remove all but context scene
        for scene in bpy.data.scenes:
            if scene == compScene:
                continue
            bpy.data.scenes.remove(scene)

        # save with only compScene
        bpy.ops.wm.save_as_mainfile(filepath=scene_file_path)
        # reopen original,link saved scene
        bpy.ops.wm.open_mainfile(filepath=blendFile)
        scene = bpy.data.scenes.get(apFilename)
        # link the scene back
        with bpy.data.libraries.load(scene_file_path, link=True, relative=True) as (data_from, data_to):
            data_to.scenes = [apFilename]
        # rename the original scene, remove crashes my blender
        screen = bpy.data.screens.get(screen_name)
        scn = screen.scene
        if scene and screen:

            scene.name = "%s_ORIGINAL" % scene.name
            scn = bpy.data.scenes.get(apFilename)
            #c = context.copy()
            print("CONTEXT", bpy.context.window, context.window)
            c = {"scene": scene,
                 "screen": screen,
                 "area": screen.areas[0],
                 "region": screen.areas[0].regions[0],
                 "edit_object": None,
                 "blend_data": bpy.data,
                 "window": bpy.data.window_managers[0].windows[0]
                 }
            bpy.ops.scene.delete(c)
            screen.scene = scn

        return {"FINISHED"}

bpy.utils.register_class(BPC_main_Outsource)

# test run
if bpy.ops.scene.outsource.poll():
    bpy.ops.scene.outsource()
else:
    print("Failed POLL is scene already linked?")

Yes, I did. I saw your script was completely fine about two seconds after I wrote the comment. My apologies. Your answer was much appreciated.

Any idea why trying to delete the original scene results in a crash?

My guess is context is lost while loading a new file, during the restricted context time , a print of context.scene, context.window all show None (using bpy.context also).  To get around this creating a datapath from the data of the file before reload and then getting them from the data after reload appears to be the way to go.  I've posted code that "works" but would suggest putting a lot of checks and balances in it and even a try except (which I try to avoid)  after the file save, to reload if something goes wrong.  Wondering if re-importing bpy as bpy_ may be useful here.

importlib.reload(bpy) may be woth a try but I do not really think it is going to help a lot...
The context problem was sort of what my question was (and still is) all about. But thanks for pointing out the datapath method in your initial answer that one really was extremely helpful!

Did you try the new code?.  Forgot to mention I updated it.  It's working for me on most occasions.


text:
How to have each EnumProperty item display a custom tooltip when using operator_menu_enum?
The Blender UI for built-in operators shows custom tooltips for menu items shown using operator_menu_enum.
For example:

And the code looks like this:

But, whenever I try to add items to a menu using operator_menu_enum, Blender just displays the __doc__ string from my Python class, while ignoring the description from my items tuple.
My example code:
 modifier_items = [
    ('solidify', 'Solidify', 'Add solidify modifier (custom tooltip, ignored)', 'MOD_SOLIDIFY', 1),
]

# ...

class CustomModifier(bpy.types.Operator):
    """Add modifier (__doc__ string)"""
    bl_idname = "myops.modifier_add"
    bl_label = "Custom Modifier"
    bl_options = {'REGISTER', 'UNDO'}

    modifier_type: bpy.props.EnumProperty(
        items=modifier_items,
        name='Modifier Type',
        description='Type of modifier to add to mesh'  # this is also ignored
    )

# In the bpy.types.Menu subclass code:
# ...
layout.operator_menu_enum("myops.modifier_add", property="modifier_type", text="Add Modifier",)
# ...

And this is the result I get:

Edit
I originally posted the wrong image of the Blender built-in tooltips

I know this question is 6 months old, but hopefully my answer helps some people.
First, you need to create a new variable above your enum. This variable contains your enum items.
Then, set the items in your enum variable to the items variable you declared above. This will act the exact same as you had it before, with the added benefit of being able to access the entire tuple of items later.
Next, there is a built-in classmethod called "description", it allows you to set the description of an operator at runtime. In this method, we are going to unpack our tuple of items and use it to get our description. We then return that description, which tells Blender to use it when we hover over the operator.
The following code must be placed inside your operator class:
enum_items = ("title1", "Title 1", "desc1"),
        ("title2", "Title 2", "desc2"),
        ("title3", "Title 3", "desc3"))

my_enum: bpy.props.EnumProperty(items = my_enum)

@classmethod
def description(cls, context, properties):
    items = {id: desc for id, name, *desc, in cls.enum_items}
    desc = items[properties.my_enum][0]
    return desc

looks like there's some bugs in your code
my_enum: bpy.props.EnumProperty(items = my_enum) should be my_enum: bpy.props.EnumProperty(items = enum_items)
and desc = items[properties.my_enum][0] should be desc = items[properties.my_enum][2]
but even in changing this it doesn't work, can you update your code ? thanks


text:
How can I add a new object on mouse click?
I am looking for a code, that adds an uv sphere on a mesh when a mouse click happens. I saw the topic: Adding new object on mouse click? but there are no answers there. I guess a modal should be implemented on the LEFTMOUSE clicks, but I can't seem to find any simple examples and explanations.
import bpy
import bgl
import bmesh
from bpy_extras import view3d_utils
import mathutils
from mathutils import Vector

"""Functions for the mouse_coords_to_3D_view"""
def get_viewport():
    view = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view)
    return view

def get_modelview_matrix():
    model_matrix = bgl.Buffer(bgl.GL_DOUBLE, [4, 4])
    bgl.glGetDoublev(bgl.GL_MODELVIEW_MATRIX, model_matrix)
    return model_matrix

def get_projection_matrix():
    proj_matrix = bgl.Buffer(bgl.GL_DOUBLE, [4, 4])
    bgl.glGetDoublev(bgl.GL_PROJECTION_MATRIX, proj_matrix)
    return proj_matrix

"""Function mouse_coords_to_3D_view"""
def mouse_coords_to_3D_view(x, y):
    depth = bgl.Buffer(bgl.GL_FLOAT, [0.0])
    bgl.glReadPixels(x, y, 1, 1, bgl.GL_DEPTH_COMPONENT, bgl.GL_FLOAT, depth)
    world_x = bgl.Buffer(bgl.GL_DOUBLE, 1, [0.0])
    world_y = bgl.Buffer(bgl.GL_DOUBLE, 1, [0.0])
    world_z = bgl.Buffer(bgl.GL_DOUBLE, 1, [0.0])
    view1 = get_viewport()
    model = get_modelview_matrix()
    proj = get_projection_matrix ()
    bgl.gluUnProject(x, y, depth[0],
                     model, proj,
                     view1,
                     world_x, world_y, world_z)
    return float(world_x[0]), float(world_y[0]), float(world_z[0])

"""drawing point OpenGL in mouse_coords_to_3D_view"""
def draw_callback_px(self, context):
    # mouse coordinates relative to 3d view
    x, y = self.mouse_path
    mx, my = self.mx, self.my #got from modal

    # mouse coordinates relative to Blender interface
    view = get_viewport()
    gmx = view[0] + x
    gmy = view[1] + y

    if False:
        #c= bgl.Buffer(bgl.GL_UNSIGNED_BYTE, [3,1])
        #bgl.glReadPixels(x, y, 1, 1, bgl.GL_RGB, bgl.GL_FLOAT, c)
        #c= bgl.Buffer(bgl.GL_SHORT, [3,1])
        c = bgl.Buffer(bgl.GL_FLOAT, [3,1])
        bgl.glReadPixels(gmx, gmy,1,1,bgl.GL_RGB,bgl.GL_FLOAT,c);
        draw_square_follow_cursor(c, gmx, gmy)
    else:
        draw_uv_sphere(mx, my, 0.5)

def draw_uv_sphere(mx, my, s):
    ob = bpy.data.objects['Cube']
    v = ob.data.vertices[0].co
    mat = ob.matrix_world
    x,y,z = mouse_coords_to_3D_view(mx, my)
    mv = Vector((x, y, z))
    bpy.ops.mesh.primitive_uv_sphere_add(segments=42, ring_count=42, location=mat * mv, size=s)

def draw_square_follow_cursor(c, gmx, gmy):

    mouse3d = mouse_coords_to_3D_view(gmx, gmy)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor3f(0.0,0.0,255.0)
    bgl.glPointSize(30)
    bgl.glBegin(bgl.GL_POINTS)
    bgl.glVertex3f(*(mouse3d))
    bgl.glVertex3f(mouse3d[0], mouse3d[1], mouse3d[2])
    bgl.glVertex2f(gmx,gmy)
    bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

def draw_corner_square(c):
    for area in bpy.context.screen.areas:
        if area.type=='VIEW_3D':
            X= area.x
            Y= area.y
    dist= 100 #distancia del punto al cursor
    mouse3d = mouse_coords_to_3D_view(X+dist,Y+dist)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor3f(c[0][0],c[1][0],c[2][0])
    bgl.glPointSize(30)
    bgl.glBegin(bgl.GL_POINTS)
    bgl.glVertex3f(mouse3d[0], mouse3d[1], mouse3d[2])
    bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

def draw_square(c):
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor3f(c[0][0],c[1][0],c[2][0])
    bgl.glBegin(bgl.GL_POLYGON)
    bgl.glVertex2f(-0.5, -0.5)
    bgl.glVertex2f(-0.5, 0.5)
    bgl.glVertex2f(0.5, 0.5)
    bgl.glVertex2f(0.5, -0.5)
    bgl.glEnd( )

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

class ModalDrawOperator(bpy.types.Operator):
    """Draw a point with the mouse"""
    bl_idname = "view3d.modal_operator"
    bl_label = "Simple Modal View3D Operator"

    def execute(self, context):
        draw_uv_sphere(self.mx, self.my, 0.5)
        return {'PASS_THROUGH'}

    def modal(self, context, event):
        #context.area.tag_redraw()

        if event.type == 'MOUSEMOVE':
            self.mouse_path = (event.mouse_region_x, event.mouse_region_y)
        elif event.type == 'LEFTMOUSE':
            self.mx, self.my= event.mouse_x, event.mouse_y
            self.execute(context)
            return {'PASS_THROUGH'}

        elif event.type in {'RIGHTMOUSE', 'ESC'}:
            if False:
                bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
                context.area.header_text_set()
            return {'CANCELLED'}

        return {'PASS_THROUGH'}

    def invoke(self, context, event):
        # the arguments we pass the the callback
        args = (self, context)
        # Add the region OpenGL drawing callback
        # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
        #self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_VIEW')
        self.mouse_path = []
        self.width = bpy.context.window.width
        self.height = bpy.context.window.height
        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}

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

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

if __name__ == "__main__":
    register()

Q: How can I add a new object on mouse click?

Similarly to This Answer  The following adds a sphere on left mouse press.  Needs to be invoked from a 3d view.
import bpy
from bpy_extras.view3d_utils import region_2d_to_vector_3d, region_2d_to_location_3d

class ModalTimerOperator(bpy.types.Operator):
    """Operator which runs its self from a timer"""
    bl_idname = "wm.modal_timer_operator"
    bl_label = "Add Sphere on Click"

    _timer = None

    def modal(self, context, event):
        if event.type in {'RIGHTMOUSE', 'ESC'}:
            self.cancel(context)
            return {'CANCELLED'}

        if event.type == 'LEFTMOUSE' and event.value == 'PRESS':
            # left click

            if context.area.type == 'VIEW_3D':
                region = context.region
                r3d = context.space_data.region_3d
                x, y = event.mouse_region_x, event.mouse_region_y
                view = region_2d_to_vector_3d(region, r3d, (x, y))
                loc = region_2d_to_location_3d(region, r3d, (x, y), view)
                bpy.ops.mesh.primitive_uv_sphere_add(location=loc)

        if event.type == 'TIMER':
            #print("timer")
            pass

        return {'PASS_THROUGH'}

    def execute(self, context):
        if context.area.type != 'VIEW_3D':
            print("Must use in a 3d region")
            return {'CANCELLED'}

        wm = context.window_manager
        self._timer = wm.event_timer_add(0.1, window=context.window)
        wm.modal_handler_add(self)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        wm = context.window_manager
        wm.event_timer_remove(self._timer)

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

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

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.wm.modal_timer_operator()

# note code edited from text editor > templates > python > modal timer operator.

is this still supposed to be working in Blender 3.1? I get a ```AttributeError: 'NoneType' object has no attribute 'type'````error


text:
Particle Flow along a Curve with Turbulence
I'd like to replicate the effect in the follwing the picture:

I did create a curve with a particle flow on it already but I don't know how to make this kind of eruption effect.
Scene Download
Would be nice if someone can me help out.

If you can maybe share some of your settings we can help you more. Because its mostly about tweaking

I add a download link to the scene


text:
How to mirror knife cuts on existing mesh?
I have an existing mesh model with bones, UVs, animation etc. and I want to change the mesh slightly without causing too much destructive change.

The above shows the head with the -x and x direction labeled. The edge pointed by the green arrow is done by a knife cut because I want to cut new geometry to fill in a face tattoo. I also turned on "Enable X symmetry in the X direction" at the top right corner.
When I use the knife cut on the -X side, I expect the cut to mirror on the X side, but it didn't. Then I selected the new vertices and go to Mesh > Symmetrize, the new vertices is mirror to the -X side. However, they are on top of the existing geometry. In below image, on the -X side, I move the vertex at the side of the -x cheek to show the vertex is actually separate from the cheek's edge.
Question: How do I properly do the knife cut that can mirror -x/x? I will be happy is there is a way to merge the floating vertex to the existing edge on the -x side, while maintaining symmetry.
I am using Blender 4.0

The knife cut won't be symmetrized automatically with the X symmetry option on, this tool will only move or remove the vertices that are moved or removed on the opposite side. What you can do though is select the new edge and Mesh > Symmetrize and it will be mirrored:

Also, the symmetry will work as long as you keep the other side symmetrical, if you begin to change it unsymmetrically, you are breaking the symmetrey and you won't be able to do any symmetrical operation:

That's what I did "Mesh > Symmetrize and it will be mirrored", however, as seen from my screenshot, although it generate the new vertex at the correct X location, however, it is separate from the existing edge. I want it to be along the edge, same as the -X side where I cut the edge. Any advice how can it be done? Thanks.

It's because your mesh is not really symmetrize, you could symmetrize the whole thing but you said that it would be too destructive

Thanks for your confirmation that Mesh > Symmetrize will not work. I think I don't full understand what is considered symmetry by Blender then. Anyway, I gave in and used a mirror modifier on the entire mesh. The surprising good news is that the vertex weights and groups are not destroyed. I not exactly sure why rig, weights, groups are preserved because I definitely cut the mesh into half using Auto Mirror addon tool. Good for me.

The symmetry will work as long as you keep the other side symmetrical, if you begin to change it unsymmetrically, you are breaking the symmetrey and you won't be able to do any symmetrical operation. As for the Mirror modifier, it won't destroy your material if it was made of an image texture for example and if your UVs were already overlapping


text:
How to delete a mask in the movie clip editor?

I can't find find a way to remove masking data in the Movie Clip Editor. How to get rid of it?

Hold down Shift and click on the X button right beside the mask dropdown.

This will unlink the 'mask data-block' from your file. To get rid of the mask's data, you can either save and re-open your blend-file or just click the Purge All button in the Outliner:

Or after clicking Shift+X open Outliner, switch it to Orphan Data and press Purge All. This will remove all unused datablocks but no reopening needed


text:
Example of persistent usage of «bpy.msgbus» and how to manage it?
I was searching for a way to get notified when the user of my addon interact with for example a particle setting or texture setting. I found out about bpy.mgsbus but there’s literally too little info about it anywhere. Here’s what I found so far:
import bpy

handle = object()
sub_particles = bpy.types.ParticleSettings

def notify_test(*args):
    print("Notify changed!", args)

bpy.msgbus.subscribe_rna(key=sub_particles, owner=handle, args=(), notify=notify_test,)
bpy.msgbus.publish_rna  (key=sub_particles )

This code above is working fine for subscribing to any change user is making in any particle settings change, but how can we make it persistent, meaning being active when the addon is enabled. I am aware that an msgbus is not an handler. I saw an args options=set() from the function bpy.msgbus.subscribe_rna i'm doing some experimentation right now with options={"PERSISTENT"}.
The other issue I have is that the code bpy.msgbus.clear_by_owner didn't work for me as I didn't figure out what's in the args yet. So we could add as a question: How to remove the msgbus once set?  and also we could add How to make sure that the msgbus is not active? as it seems there's also no lists of active msgbus available.  Information we can get from the console:
#CLEAR BY OWNER
bpy.msgbus.clear_by_owner(owner)
.. function:: clear_by_owner(owner)
Clear all subscribers using this owner.

#PUBLISH RNA
bpy.msgbus.publish_rna(data, owner, args, notify)
.. function:: publish_rna(data, owner, args, notify)
:arg key: Represents the type of data being subscribed to
   Arguments include
   - :class:`bpy.types.Property` instance.
   - :class:`bpy.types.Struct` type.
   - (:class:`bpy.types.Struct`, str) type and property name.
:type key: Muliple
Notify subscribers of changes to this property
(this typically doesnt need to be called explicitly since
changes will automatically publish updates).

#SUBSCRIBE RNA
bpy.msgbus.subscribe_rna(data, owner, args, notify, options=set()
.. function:: subscribe_rna(data, owner, args, notify, options=set())
:arg key: Represents the type of data being subscribed to
   Arguments include
   - :class:`bpy.types.Property` instance.
   - :class:`bpy.types.Struct` type.
   - (:class:`bpy.types.Struct`, str) type and property name.
:type key: Muliple
:arg owner: Handle for this subscription (compared by identity).
:type owner: Any type.
:arg options: Change the behavior of the subscriber.
   - ``PERSISTENT`` when set, the subscriber will be kept when remapping ID data.
:type options: set of str.
Returns a new vector int property definition.

https://blender.stackexchange.com/search?q=msgbus

Fair enough, changed the question

The PERSISTENT option doesn't make the subscription remain active when loading files. It is for ensuring that the subscriber remains registered when remapping ID data. Subscriptions will be removed when loading a new file. Persistent application handler appended to bpy.app.handlers.load_post can be used to call bpy.msgbus.subscribe_rna() when a new file is loaded.
bpy.msgbus.clear_by_owner() requires the owner that you've also passed to bpy.msgbus.subscribe_rna() as argument. It will clear all subscribers by this owner.
Below is an add-on that demonstrates the use of the msgbus. It creates a panel "msgbus" with two operators that allow to register/unregister a handler for the message bus. Once registered, whenever the active object changes, it prints information about it to the terminal/console.

bl_info = {
    "name": "Example add-on persistent msgbus",
    "author": "Robert Guetzkow",
    "version": (1, 0),
    "blender": (2, 81, 0),
    "location": "View3D > Sidebar > My own addon",
    "description": "Example add-on that uses msgbus",
    "warning": "",
    "wiki_url": "",
    "category": "3D View"}

import bpy
from bpy.app.handlers import persistent

# For more information see source/blender/python/intern/bpy_msgbus.c
# and https://developer.blender.org/P563

# Object that will store the handle to the msgbus subscription
subscription_owner = object()

def notification_handler(*args):
    print(f"Object: {bpy.context.object.name}, Location: {bpy.context.object.location}, Args: {args}")

def subscribe_active_obj(subscription_owner):
    # What the subscription is for, in this example the active object.
    # Note that for properties it may be necessary to use `path_resolve`
    # as shown in https://developer.blender.org/P563
    subscribe_to = bpy.types.LayerObjects, "active"

    # Subscribe to the msgbus to call the handler when the key is modified.
    # Please note that not every UI interaction will publish an update,
    # despite modifying the key you've subscribed to. For instance, when
    # subscribed to `bpy.types.Object, "location"`, changing the location of
    # an object through the move tool won't call the handler automatically,
    # while updating the location property in the "Tranform" panel in the
    # sidebar will. The publishing of an update can be forced through
    # `bpy.msgbus.publish_rna()`.
    # The "PERSISTENT" option ensures that the subscriber remains registered
    # when remapping ID data, it does not mean that the subscription remains
    # persistent when loading a different file. This can be accomplished with
    # a persistent application handler that is called on file load.
    bpy.msgbus.subscribe_rna(
        key=subscribe_to,
        owner=subscription_owner,
        args=("a", "b", "c"),
        notify=notification_handler,
        options={"PERSISTENT",}
    )

    # Register the persistent handler, ensures that the subscription will happen
    # when a new file is loaded.
    if load_handler not in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.append(load_handler)

def unsubscribe_active_obj(subscription_owner):
    # Clear all subscribers by this owner
    if subscription_owner is not None:
        bpy.msgbus.clear_by_owner(subscription_owner)

    # Unregister the persistent handler.
    if load_handler in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.remove(load_handler)

@persistent
def load_handler(dummy):
    subscribe_active_obj(subscription_owner)

class SCENE_OT_msgbus_register_active_obj(bpy.types.Operator):
    bl_idname = "scene.msgbus_register_active_obj"
    bl_label = "Register Handler"
    bl_description = "Register msbus handler for the active object."
    bl_options = {"REGISTER", "UNDO"}

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

class SCENE_OT_msgbus_unregister_active_obj(bpy.types.Operator):
    bl_idname = "scene.msgbus_unregister_active_obj"
    bl_label = "Unregister Handler"
    bl_description = "Unregister msbus handler for the active object."
    bl_options = {"REGISTER", "UNDO"}

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

class EXAMPLE_PT_panel(bpy.types.Panel):
    bl_label = "msgbus"
    bl_category = "Active Object"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"

    def draw(self, context):
        layout = self.layout
        layout.operator(SCENE_OT_msgbus_register_active_obj.bl_idname)
        layout.operator(SCENE_OT_msgbus_unregister_active_obj.bl_idname)

classes = (EXAMPLE_PT_panel,
           SCENE_OT_msgbus_register_active_obj,
           SCENE_OT_msgbus_unregister_active_obj)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)

    # Unsubscribe and remove handle
    unsubscribe_active_obj(subscription_owner)

if __name__ == "__main__":
    register()

Please note that the message bus doesn't notify for every kind of update.

The message bus system is triggered by updates via the RNA system.
This means that the following updates will result in a notification on
the message bus:

Changes via the Python API, for example some_object.location.x += 3.
Changes via the sliders, fields, and buttons in the user interface.

The following updates do not trigger message bus notifications:

Moving objects in the 3D Viewport.
Changes performed by the animation system.

The implementation of the message bus can found in bpy_msgbus.c.

I'm curious, the event handling model in Blender doesn't seem to be complete and it is a bit confusing because it seems to be divided, some events are handled through msgbus and others through bpy.app.handlers. So it looks like one of these 2 systems is legacy code. I've done mostly event handling via bpy.app.handlers but it also has alot of limitations as to being able to handle specific events. Are they both legacy or only one of them? Which of these 2 systems is eventually going to be the system developers want to finish implementing or is there a new event system to be introduced?

btw the links for "doesn't notify for every kind of update" and "bpy_msgbus.c." in your post is probably outdated. might need to update to the new location of those links

@HarryMcKenzie I'm currently not quite in the loop about developments in this area, but the handlers are the solution that should be used for most general cases. The msgbus is quite low level. Both links have been fixed. Blender moved from Phabricator to Gitea and the URL changed in the process.

thank you. maybe you know the answer to this person's question. His msgbus code looks correct but it's not supported or something.

@HarryMcKenzie While I haven't looked at Blender's source code for the color palette the explanation provided in the bug report appears to be correct.


text:
What is the benefit in use of Ctrl+J?
I have created an rdc file from google maps using RenderDoc, imported it into Blender (had to use version 2.83) and 'cleaned it up' by removing all unwanted vertices using the lasso select 'tool' with x-ray on as per videos on Youtube and very happy with the result.
Watching another video tutorial the author used CtrlJ which joins everything into one mesh.
First of all apart from having one one mesh in the 'collection' what are the other advantages and are there any disadvantages?
I will want to copy the object to another object when complete.

Before CtrlJ

After CtrlJ

Well, it's a quite simple tool, the advantages and disadvantages are quite simple as well: it joins meshes. But you started your question with cleaning up meshes etc., Ctrl+J has nothing to do with cleaning up in a sense of making any geometry better or less messy. It's just that you have now one object in Object Mode where before were two or more. In Edit Mode the meshes are still separate parts.
The advantages are less objects in the Outliner and you can move, rotate, scale them all at once in Object Mode and all those before separate meshes stay together in relation to each other, no matter which Pivot Point you choose. In Edit Mode, if there are vertices close together you can merge them by distance to avoid doubled vertices. You can't merge two vertices even in the exact same location if the meshes belong to different objects. You can't create edges or faces between vertices if they are separate objects either. So joining meshes with Ctrl+J let's you do all those things. Of course other things like changing material is easier when it is all one object instead of multiple ones.
The disadvantages are for example, now that all those meshes are one object, you cannot simply have one with a Bevel Modifier and the other without or with different settings. To do that in one object you have to use methods like Bevel Weight or Vertex Groups to differentiate between which part of the mesh should be beveled and how much. But it's worse with the Subdivision Surface modifier, since this has no option to restrict the subdivision to certain vertex groups.
Applying materials is different, too. In separate objects, one can have e.g. a red material, the other a blue one. If they are one object, you have to assign faces to material slots to define which part of the object should have which color.
The good thing here is: if two objects already have different materials before joining, the Ctrl+J join will create a second slot for the second material and automatically assign it to the faces from the second object.
There are more examples to come up with, but as a general rule the advantages and disadvantages are simple, as I stated before: joing meshes into one object (apart from reducing the entries in the Outliner) let's you do many things in Object Mode that are sometimes difficult or may cause problems with multiple objects. In Edit Mode it is sometimes the only way to edit meshes together which would not be possible if they were separate objects.
On the other hand it's sometimes harder to do individual tasks on different meshes in one object which are maybe easy to do on separate objects. But altogether it depends a lot on how you are working and what kind of workflow you prefer. So I suspect this question will be closed due to asking for opinion-based answers instead of practical solutions.

Thanks. Sorry for confusing you about 'cleaning up' Yes I know that has NOTHING to do with using Ctrl J and I only included that to describe everything I did.  As the model is simply 3D photogammetry there would  be little if no need to add a modifier but take on that information as it might be important for me later with other projects. Being able to rotate, scale etc shouldn't be a problem either especially selecting A(ll).   Thanks again Gordon.

My examples were not specifically for your model, the advantages / disadvantages of joining meshes are a general thing... Of course modifiers might not be of need here, but I thought my answer to be incomplete if I had just written "doesn't make much difference here"  ;-) Although to clean up geometry it still helps if you can connect different parts in Edit Mode. Regarding scaling and rotating: what I said was the object meshes would stay in the same relations to each other, no matter which Pivot Point you choose. For example if you use Individual Origins on multiple objects...