text:
set yaw, pitch and roll for camera
I want to do two things:
Set the yaw, pitch and roll of the camera and the reverse, extract yaw, pitch and roll from the camera.
I got some confusions using the rotations in Blender. I use the Euler rotation modes. As I understand, for example XYZ Euler means first a rotation around the local (and global) z axis, followed by rotation around the global Y and then X axis. Thus, to set yaw pitch roll for a normal object, one would use YXZ as z is the yaw, x the pitch and y the roll.
The problem comes when using cameras: For cameras the typical z axis (pointing upwards) would be the y axis, while x is still pitch and z is roll. However, it does not simply work to use ZXY Euler since one has to first turn the camera about 90 degrees in x direction to align local y and global z axis.
Does anyone know to to solve this problem? Is it for example possible to change the axis system of the camera?

If we look through your ideal camera, does X point right, Y point up, and Z point towards us?

@Leander. That is how it is at the moment. Is it possible to switch Y and Z? Any other solution would also be welcome.

Ok, so you want X to point right (pitch), Y to point towards us [not away!] (roll) and Z to point up (yaw), correct? And when changing the Roll, the other axes don't change, and when changing the pitch, the yaw axis doesn't change. Then yaw axis changes both other axes, correct?

thats correct: I basically want to be able to read of yaw pitch and roll from the rotation_euler property, which is not possible because if the camera rotation is (0, 0, 0), the camera faces down.


text:
Is there a way to create a pause between movements in Animation Nodes?

I want to create a translation or a rotation, but with pauses every custom number of frames (Preferable with an interpolation) , like in the GIF. How can I do this?

can you mark one answer as the correct answer, or say why your question isn't solved yet?

I'm sure there are many ways to create this effect but here is one relatively simple one:

The essential node here is Mix Euler List. For translation you could use the Mix Vector List node.
The Mix Euler List node takes a list of vectors and a value between 0 and 1 (can be higher when Repeat is enabled). If the factor is 0 it will output the first element, if it's one it will output the last one. All values inbetween will result in an interpolated output. (eg. 0.1 will be something between 0° and 90° in the z-axis).
The downside of this approach is that the time intervalls are always the same, but it seems to work in your case. You can animate the time somehow to change the intervalls using the same approach but this can become messy very quickly so I didn't do it here.

A very cheap way to show the pause longer is to add the value twice or more in a row in the Create Euler List.

Do you think we should expose those Mix XX List nodes to menu?

Not sure if its worth it to create another 6 menu entries or so...

True, but even for me, I actually didn't know these nodes until seeing this answer (shame on me.. :P). So my concern is: Whether or not should we create something without being found by most ppl... As for this specific one, maybe a new "List -> Mix" category is a workround for that.

Here is a way to achieve this which is easy to adjust. I've separated the parameters as inputs to a group subprogram.
It uses div/mod on the timestep to figure out the whole divisor and remainder portion of the timestep divided by "segment duration". It applies whole segments by multiplying by the supplied "segment rotation", and then applies an interpolation curve to the progress through the current rotation.
This could be adjusted to use a matrix instead of a rotation, allowing a more complex periodic motion to be applied, with pauses between intervals.

Here is another way:

NOTE: The setup above is for equidifferent result. Actually you can use different Delay, Rotation Increment, Interpolation and/or Duration value by adding new iterator(s) to the same loop, then use list(s) of same length to the iteration amount, for more variations.

what is "reassign loop paramater"? I can't find it. Is it depreciated?

@DavidJeske the Reassign button can be found in the Advanced Node Settings panel for each Loop Input node with parameter created. See here.

For the purpose of learning I tried to create another way of doing this.
(I also learned time goes really fast doing this :) )
First create an Empty and animate one sequence to your liking using the F-Curve editor. I let the nodetrees speak for itself.

Make sure to set Evaluate F-Curve to Absolute, else it won't repeat.

Make sure to set 'Allow negative index' on the [Get list Element] node.

Although you could animate the sequence on the target object if you like. I do not recommend this! It will make swapping to a different rotation much harder.
Now you could even make an List of Objects and select the object to use depending on the frame for example.

good idea. There are two things you can improve in that node tree: 1. use the Combine Euler node instead of Combine Vector. This way you don't need the Vector to Euler node. 2. To get the last element of a list you can use the Index -1. make sure that you enabled Allow Negative Index first (in the advanced settings).

@JacquesLucke Thanks for pointing that out. I updated the images.

source: Stack Exchange

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

sort: votes


text:
Global Variable/Node across multiple materials?
How can I get a Node input/output (e.g. a single Color/Value) that I can control from the one spot, but have mapped across multiple materials? For example, to control a value (say, Glass Shader IOF, or a Mix Shader Fac) across 30 different materials (that may or may not have different node setups, but all use the input I want as a driving factor somewhere inside).
I've got a few ideas so far, but am not sure which will work and/or which will be the best way to go about it:

Use a Node Group
I tried setting up an input inside a node group, then using the node group in various locations - however I could only seem to automate/keyframe the 'default' values of things inside the group (these changes didn't flow through into the instances of the group).

Script node
I could set up a Script Node that returns the value I want - however I imagine this would be tricky to automate, and it would also lock me into OSL, which feels a bit roundabout and also rules out GPU rendering (not essential but it would be nice)

Driver
I could set up a dummy object or material, set up drivers through to the things I want to control, then keyframe the dummy object and that might achieve what I want. However this again feels a bit roundabout/messy.

Background: I'm working on a model that has a non-trivial number of materials (just over 100, auto-generated from a 3D scanner), and am trying to set up effective backface culling in rendering by using the method described here. This involves scripting the addition and connecting of all the extra nodes (Mix shader controlled by Geometry Backfacing, and a Transparent BSDF node to make the faces be rendered transparent from the back), because doing it manually for all 100+ materials would be a pain. It's not essential, but I was thinking it would be nice to be able to control the overall effect by automating all the Transparent BSDF Alpha amounts - I'm just not sure how I'd go about controlling that from a single point though.

This can be done with node groups.
I think you were trying to edit the attributes of the node group instance itself. Instead, try editing/animating the attributes of the nodes inside the group:

Just add a value node (or any input nodes you want, e.g. RGB for color) and press ⎈ CtrlG to make it into a group.
Changes the values of the nodes inside the group will take effect everywhere the group is used, even across different materials. So in this case changing the value node will change the brightness of the diffuse material and the AO material.

To supplement this answer, you can then edit the value inside the group simply by pressing Tab when the group is selected (took me a while to find out)

Just a reminder : the "rendered preview" mode from "3d view" do not update animated node values from node group (With Blender version 2.79b) but the result is ok during "rendering animation / image".

If you need them inmated you could use drivers instead. They are a little more complex but also more powerful than just group nodes, and you could link any 2+ values.

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

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


text:
How can I run blender from the command line to export and import models
I am interested in exporting and importing 3d models using blender via the command line, as mentioned in this question.
So now I want to know how I can import and export the models in blender with python using this method?

Apart from the info that this question already gives you, you need to figure out the operators to call from the Python script.
Enable Python Tooltips (User Preferences -> Interface -> Display), then go to the import action in the File menu. Rather than clicking on it, hover your mouse over the menu item and inspect the tooltip. That'll tell you which operator to use. Do the same for the export, and you should have the information you need to build up your Python script.
You can get more help from the Python console (in the Scripting layout), by just typing the name of the operator. For example, >>> bpy.ops.import_scene.obj will give you:
# Load a Wavefront OBJ File
bpy.ops.import_scene.obj(filepath="", filter_glob="*.obj;*.mtl", use_ngons=True,
use_edges=True, use_smooth_groups=True, use_split_objects=True, use_split_groups=True,
use_groups_as_vgroups=False, use_image_search=True, split_mode='ON',
global_clamp_size=0, axis_forward='-Z', axis_up='Y')

This tells you which options there are, and what the defaults are.

Hi @Sybren, thanks for your answer, and what you mean by Python console (in the Scripting layout) ? am newbie to  python as well as blender

At the top of the Blender window, you see a drop-down list with "Default" in it. That's the screen selector. You can select predefined "screens" (which I referred to as "layouts", sorry for that), or create your own. If you select the "Scripting" screen there, you'll find an interactive Python console at the bottom of the screen.
There is more info in the Blender manual about screens.

Yes i got it, thanks for the tip, and this may help me lot

Done :) @Sybren


text:
How Can i make save and load for bge
I probably need the help of a Python script to make this work.
What I want is: The player will be able to save and turn off the game, but continue from where they saved when they next log in. Items such as gold, weapons, etc. must be stored.
It feels like something hard to do and I am not managing to figure it out alone. Although I love problems and solving them, in this case I need help.
I know that BSE People should not  ask more questions.
But.
Is this stupid or must I have several Scenes in my game. Say that my player goes into a house. Should the house then be in another Scene, or should I move camera and player to inside the house from the same Scene?
Any advice would be very helpful. I have no one near me whom I can ask.
//
Robin W

So have multi scene is for the best. its a Zelda spin off thing,
Open world. but when enter a new area it will been in a other scene.
Thanks.
( this time without google translate...) (hope you can understand.)

I suggest to abstract the requested features into different aspects of your game

Storage
Persistence

Storage
Convert game states into store-able data and back.
Store

extract the states from your game (positions, properties, animation frame ...)
convert it into a storable format (e.g. strings, lists, ...)
store it into a storage

Example:
import bge

storage = bge.logic.globalDict # globalDict is a predefined storage provided by the BGE

def store():
    playerStorage = {}
    storage["player"] = playerStorage # create a storage in storage

    player = bge.logic.getCurrentScene().objects["Player"]
    playerStorage["position"] = list(player.worldPosition)
    playerStorage["health"] = player["health"]

This is just a very simple example demonstrating a basic storage system. When you have more data, you will need a much more complex data structure to keep all the states of all the different objects.
You do not need to use bge.logic.globalDict. You can create your own storage (similar to playerStorage).
Do not store any references to data that can't be persisted such as KX_GameObjects, KX_Scene, Vector. You need to extract the data that can be applied to a different object later.
Beside game states you need to store enough data to uniquely identify target objects for later restore. In the example it is the key "player" assuming this data is from an object called "Player". [Object names are not unique, so you need to store additional data].
Restore
Is the reverse of Store.

read the data from storage
convert it to game states
identify the game objects it belongs to
apply it to that objects

Be aware the objects you stored the data from are not necessarily the same objects you will restore it to. If that sounds confusing: Imagine you restarted the scene. This means the original scene is gone and all of it's objects are dead. But you created and loaded a new scene with new objects that look the same. But they are different object.
The objects do not even need to be equal. E.g. you stored the data of a walking character (e.g. health). Then you restore the data to a vehicle as the character is sitting inside the vehicle.
Identifying objects can be tricky. In most cases the object name is sufficient enough.
Example:
import bge

storage = bge.logic.globalDict

def restore():
    playerStorage = storage["player"] # will result in error if nothing was stored before
    player = bge.logic.getCurrentScene().objects["Player"]
    player.worldPosition = playerStorage["position"]
    player["health"] = playerStorage["health"]

In this example we assume that data from storage "player" should be applied to an object called "Player". The above operations assume these data exist. Otherwise the processing will return an error. You need to apply a proper error handling.
Usage
Store and Restore are useful within several situations:

pre-step of persistence
scene switch by keeping game states of related objects (such as player stats)
object occlusion (objects out-of-sight are removed - and re-added when coming into sight again)
network communication

Persistence
Often referred as Save/Load. It means you ensure the game states persist without a running game session. A typical situation is to persist the game states to a file.
There are several different ways to implement such a system. A very simple one is to use the build-in Persistence via GameActuator:
Save
The GameActuator in Save mode marshals the data from bge.logic.globalDict into a file called <your-blend-file's-name>.bgeconf.
Example:

You simply activate the actuator and the BGE persists the previously stored globalDict to file.
Be aware this overwrites any previously saved data!
Load
The GameActuator in Load mode replaces the content of globalDict with the content from file <your-blend-file's-name>.bgeconf.

Be aware: the complete globalDict will be overwritten!
A missing .bgeconf file will show a warning in the console.
All together
Now you have all the aspects together. You always need to consider the timing. This means you better store before save, restore after load. You always have the option to skip the persistence (e.g. on scene switch).
Advanced
The above examples are very simple. You will need to establish you very own storage. You might even want several different storage objects.
Always be sure what you store where.
Do not mix storage with other purposes (e.g. managing an inventory via globalDict). This will sooner or later result in heavy design issues.
The python part can become quite a lot of code. I suggest you do some training first to be able to manage that.
There are other ways to persist data. E.g. you can pickle the data via Python and save the pickled data to file. This supports more data formats than marshalling. E.g. you can store custom classes.
I hope it helps


text:
How to apply the UV map of a scan to a retopologized model?
Using photogrammetry, I obtained a perfectly textured model. I created a retopologized low density mesh of it. Now, I'd like to apply the UV map of the original scan to the new mesh. What is the best option to do it?


text:
How to toggle material view mode by hotkey (similar to Alt-Z/Shift-Z)
I want to be able to toggle "Material" view mode by using hotkey.
Shift + Z toggles rendered mode and Alt + Z toggles textured mode.
I want my hotkey to toggle material mode.
I tried to assign a new hotkey with the following command I copied from console window:
bpy.context.space_data.viewport_shade = 'MATERIAL'

But it didn't work.

You can add the new shortcut by :

go to User_Preferences > Input > 3D_View > 3D_view(Global) > Add_New
setup the new shortcut as follows ( ⇧ Shift + Q are just an example choose your own ) :

@IvanKartofanov you're welcome ,always look at similar shortcuts to figure out how to add new ones

Apart from the already given, and fine, answer, you could also enable the pie menu addon. This changes some common hotkeys (like Z) to show a pie menu. It takes a bit getting used to, but after a while it's fast and pleasant to work with.

Definitely way better than trying to keep track of the other hot keys. Furthermore, the pie menu always keeps the options in the correct orientation even if not all are there to aid in (muscle?) memory.


text:
draw lines like electricity from objects origins, across particles in a volumetric material to other object?
How would I draw lines connecting object to other objects using particles to simulate lighting inside a volume? I want to use it in a fire sim like this.

Can post a picture of what kind of effect you are looking for?

If you want to create effect of lightning strikes, proobably the best way could be to actually model those "lines"

this is to be procedural, and arc from a point to another point, In bge I would label the targets with a property but I have very little bpy experience. The first thing I intend to use it for, is to have minnor 'zaps'into the air targeting to a second particle system, to make a ball lighting type effect...

I have been thinking about it, and I need to use the point on line mathutils to get a vector, and apply a force to push particles into a line, and also apply turbulence, and somehow ensure there are more particles on the 'start' side then the 'end' side.
Then I will use fire sim + particles to 'draw' the lighting,
but yeah, point on line force between two points..... I can't do that in BPY can I?


text:
How to to split an element to make a rotation point to animate a follow path
I am trying to animate a double bus, like this one:

Do I need to split the bus in the middle so that both bus parts can rotate individually over a path using the Follow Path constraint? I don't have enough experience in animating to know how to achieve this. Any suggestions? This is my bus so far:

Take two:

I looked into the Follow Path constraint a bit more, but could not come up with anything. I instead decided to rig the bus. Basically, I added a base bone with a Follow Path constraint and two bones on either end with Follow Path constraints and an Offset: value to make sure they stayed at the front and rear of the bus. I then added two bones for the two halves of the bus. They are following the base bone's movements (parented) and have a Track To constraint so they point towards the two end bones. I did all the weight painting myself, so it would take forever to write a lengthy tutorial. Instead, I explained what I did, and am including a second .blend file. Note that you may want to adjust the start and end values in the .blend file.

Well, I have to admid that this is working quite well, not perfect but if I spend more time on it, it should work. I always avoid working with bones because I don't understand one single thing of them so here a few questions. 1)You said you added 2 bones for the bus halves but I count 5? 2)I can't find the follow path contraint you added

Two bones actually move the bus. The other 3 simply provide targets that keep the original 2 moving and pointing in the right direction. 2) Ctrl + Tab into pose mode with the bones selected and go to the newly appearing Bone Constraints tab in the Properties panel. 3) If my answer helped, please consider accepting it. 4) If you fool with the weight painting on the bus object, you could very well eventually get a smoother movement.

You're very welcome. Always glad to help.

Hey, I have a new questions: http://puu.sh/p3tW7/9fa24a0ddc.png .1) Did you create bones in edit mode from the horizontal bone? 2) If I select all bones and the mesh, what parent option do I need to select?

ya 2) I am not sure @Vinc199789

And did you add the Track_front and Track_back bones in edit mode or are these lose bones parented?

They are not parented.

Is it possible that you can make a small video of how you rig + adding the contraints?? I keep failing getting the bones correct.

Glad to hear it!

I think you will do much better using a Curve object modifier than a Follow Path constraint.
To utilize this, first delete the constraint. Next, align the center point of your mesh with that of the curve (make the locations the same). Then, go to the Object modifiers tab in the Properties panel. After that, add a Curve modifier. Select the curve in the dropdown menu that you want your mesh to follow. Play with the Deformation Axis: until your mesh is aligned along the curve the way you want. Your modifier should now look something like this:

To move your mesh along the curve, move the arrow that corresponds to the Deformation Axis: you selected.

Here is a .blend file:

Hey, Thanks for your answer. I also experimented with this but the problem is that at the mesh also deforms at the outside. I thought maybe could the follow path contraint solve this issue


text:
Insert fcurve keyframe point whilst keeping curve shape
I have 2 keyframe points on an fcurve with free bezier handles, and using Python I want to insert a point in between these keyframes whilst keeping the custom shape of the curve with the handles. I can insert a keyframe point no problem using
fCurve.keyframe_points.insert(frame, value)

but I'm not sure how to do so without affecting the shape of the fcurve. Is this possible?

You would need to read the value at that frame and then insert a keyframe with that value, if you want to insert one but not change the f-curve.

I can get the value at a keyframe between the points no problem, but the issue is if either of the existing points has free handles which have been moved to change the shape of the fcurve, then inserting a point won't keep that shape. I'm wondering if there is a way to insert a value (which I know lies on the curve) whilst keeping the custom shape defined by the handles?

This is actually relatively straightforward.  The Python API has access to the coordinates of the keyframe_points of the fcurve .co and the handles .handle_left and .handle_right.  You can create a new point between the other two and set up the handles using De Casteljau’s Algorithm : https://www.clear.rice.edu/comp360/lectures/BezSubd.pdf

possible duplicate of http://blender.stackexchange.com/questions/45311/how-do-i-subdivide-f-curves?rq=1

Thank you, I've almost got it working with the snippets. The only problem is that I want to add a point at a particular keyframe between 2 existing keyframes, rather than at a time t along the Bezier path (e.g. midway between 2 keyframes isn't necessarily midway along the curve, so I can't use t = 0.5). I can't find if the Python API exposes the time t for a point on an f-curve or if I'm just missing something obvious :)

Just a quick note that I now estimate t for a specific point. @MutantBob if you post your comment as a solution (with snippets from the other post) I will mark it as the answer and add my t-estimation function as a note below it.

I would actually recommend that you post your frame->t mapping as its own answer.  Even thought it does not represent a COMPLETE solution to the problem (nor does mine), it deserves the formatting capabilies available to answers.

Subdividing Bezier curves is normally done using De Casteljau's algorithm.  However, fcurves aren't pure Bezier curves.  It is not hard to make a bezier curve "run backwards" along the time axis.  Since this would create ambiguities in the animation system, blender prevents that by using modified handle coordinates whenever the handles could make the curve backtrack in the time axis.  Once we understand that math, we have what is needed to properly subdivide the fcurve.
The solution is already covered at https://blender.stackexchange.com/a/57453/660 .  It includes an excerpt from http://web.purplefrog.com/~thoth/blender/python-cookbook/subdivide-fcurve.html .  I got bored and added the logic needed to map from frame->t so it should now be a fairly complete solution.  I'm not copying the code over here, because keeping it up-to-date in both articles on stackexchange is tedious.


text:
conversion to blender
To give background:
Back in 2007 I started working on a model of the Great Crystal area of Final Fantasy XII using a modeling program named MilkShape3D. I wanted to be able to allow people to view the model on the web using a browser, but the OCX provided by the author has issues and never worked exactly the way I wanted it to (although it did render the models). To do it, the models had to be saved out in a format he called msz (the extension of the files generated was .msz). The model files natively were .ms3d files. The unfortunate part of all this is that the OCX required DirectX 9 to work. As we all know, Direct X is no longer supported by any browser, so the OCX is now useless.
To get to the point:
I am looking at Blender as a possible solution to making my models more current (as MilkShape3D is seemingly no longer supported), but conversion seems to be an issue. While MilkShape3D exports to a multitude of model formats, Blender doesn't seem to be one of them. Is there a known way I can convert my MilkShape3D models to Blender format?
To ask a second somewhat related question:
The new model-viewer control for web pages (<model-viewer>) uses the glTF format. Does Blender support this format, or does it have a different way to render models through a browser (if any)? (I think the blend4web tag answered this question in part.)

This is the section in the Blender manual on import/export formats.

glFT is supported by an add-on. It's activated by default (File > Import) https://docs.blender.org/manual/en/2.80/addons/io_scene_gltf2.html

Thanks to both of you, John Eason and Blunder. Those links are just what I was looking for.

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


text:
Baking And Unwrapping Alpha
i wanted to ask a qustion, so i just created a procedural "rorschach" like material, and to do it i used only 1/4 of a spehere and mirrored it to x y z plane, so the texture can have 4 side symetry, the question is, how do i bake it? since its only unwrapping 1/4 of the sphere.
if i apply mirror modifier, and unwrap it, then the texture wont be symetrical.
the second question is, how do i bake alpha because my texture is partially transparent
the texture looks like this in cycles rendered view
here i put google drive link for u guys to look at the blender files
Thankyou in adnvace!

It might be helpful to people trying to help you if you uploaded an example blend file to the site https://blend-exchange.com and add that link in the question.

You can use several UV slots !
Add a new UV slot, in the mesh panel, and unwrap your sphere fully.
You will bake to this slot, so make sure it's enabled for rendering, with the camera icon checked next to it.
Your noise texture will need to find and use the mirrored UV layout, so add a UVMap node, and plug it in.

Now when you bake, it will bake from the mirrored UVs, to the full UVs
And to bake alpha, best practice is to plug the value directly into Surface output and bake with Emission type. This will bake only color data, and no shading.


text:
Why does origin point does not follow the armature and the object?
i have a problem when combining my animation with some geometry node that require the origin point as the reference. heres the photo of my origin point getting left behind meanwhile the animation is already moving forward

The Animation does in fact not alter the position of your origin point. Instead, the animation occurs relative to this origin point - you can move your complete object including the animation by moving the object origin (which is what happens when you move the object itself, not in an animation setup with bones). To make your setup work, you should set your reference either

on a mesh point of your animated object which is actually afected by the animation
or better create an empty that you attach to your animated figure in a way that it also folows the animation an use that as reference.


text:
Geometry Node Won't Render, but appear fine in viewport
so i baked a cloth sim and instanced some string number to the vertices using geometry node, it does appear just fine in my viewport timeline, but when click render it won't render any instances. Here's the file and the photo:


text:
Python - Making a "character" jump to another object's x, y ordinates while facing the 'go to' objects front
I know little of code so this is a bit difficult to me.
This is just the set up for a 'player' to grab a crate and pull it back and forth.
I have 4 empty triggers set up so the crate can be grab from each of the 4 sides
However I want the 'player' to copy the x, y position and direction of the trigger that the player initiates the grab.
*Basically, I want the player's movement to be locked into a specific position as it moves the crate around."
Here's what I current have written
import bge

cont = bge.logic.getCurrentController()

own = cont.owner

scene = bge.logic.getCurrentScene()

trigger1 = scene.objects["trigger1"]

player = scene.objects["player"]

q = cont.sensors["Keyboard"]

if q.positive:

player.worldPosition = trigger1.worldPosition

I just don't know how to separate "worldPosition" into x, y, z

trigger1.worldPosition.x trigger1.worldPosition.y trigger1.worldPosition.z

That worked but I still need a 'worldRotation' command

worldOrientation


text:
Boolean with curves
I am trying to cut out a section from a "spherical shell of yarn", without much success.
Using a python script, I created a series of coordinates on a spherical surface:
import bpy
import numpy as np
import random

npoints = 100
R0 = 1

a = 1.0-np.random.rand()*2.0
theta = np.random.rand()*2*np.pi
coords = []
for j in range(npoints):
    b = (np.random.rand()-0.5)/np.sqrt(npoints)*2
    if (a+b > 1.0 or a+b < -1.0):
            a = a-b
    else:
            a = a+b
    phi = np.arccos(a)
    theta += np.random.rand()*2*np.pi/npoints
    R = R0*(1.0+np.random.rand()/10.)
    coords.append((R*np.cos(theta)*np.sin(phi), R*np.sin(theta)*np.sin(phi), R*np.cos(phi)))
# create the Curve Datablock
    curveData = bpy.data.curves.new('myCurve', type='CURVE')
    curveData.dimensions = '3D'
    curveData.resolution_u = 2
    curveData.fill_mode = 'FULL'
    curveData.bevel_depth = 0.02
    #curveData.materials.append(mat1)

# 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)
    curveOB.rotation_euler = (np.pi-2.*np.random.rand()*np.pi,np.pi-2.*np.random.rand()*2.*np.pi,np.pi-np.random.rand()*np.pi)  # Note that you need to use radians rather than angles here

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

This generates a shell of yarn, as showed in the image below.

I would like now to cut out a quarter of this spherical shell. To do that, I tought to add a cube to the scene and apply the boolean operator "difference" to all of the curves. Indeed, this strategy does not work as I cannot aplly a boolean operator to the bezier curves... I am now wondering how to proceed.
Could another option be to identify all coordinates of the bezier which are found in a certain region of the scene and eliminate them?
Addition after the comment, stating if I cannot modify the script. I can, but the result is not as i wanted. What I can do, is to rotate the chain with the script, and eliminate all the coordinates which are located in a certain volume. But then, when I create the curve, all the coordinates will be connected, and therefore there will be still chain segments (straight) in the area I wanto to free.
Once the coordinates of the chain were created, I rotated it with
def randomrot(coords):
x = 2.*np.random.rand()*np.pi -np.pi #random angle between 0 and 2pi
y = 2.*np.random.rand()*np.pi  #random angle between 0 and 2pi
z = 2.*np.random.rand()*np.pi  #random angle between 0 and 2pi

Rx = [[1., 0., 0.], [0., np.cos(x), -np.sin(x)], [0., np.sin(x), np.cos(x)]]
Ry = [[np.cos(y), 0., np.sin(y)], [0., 1.0, 0.0], [-np.sin(y), 0.0, np.cos(y)]]
Rz = [[np.cos(z), -np.sin(z), 0.], [np.sin(z), np.cos(z), 0.0], [0., 0., 1.]]
return np.matmul(np.matmul(np.matmul(coords,Rx),Ry),Rz)

Then I can cut out all the points from the coordinate list which are located in a certain volume with:
        for i in range(len(rotcoords)):  #cuts the top quarter corner of the polymer sghell
        if rotcoords[i,0] < 0.0 and  rotcoords[i,1] < 0.0 and rotcoords[i,2] > 0.5:
            None
        else:
            newcoords.append(new[i,:])

The output then looks so:

Many greets,
Leo

can you instead of trying to cut curves, edit script?

I completed the question with your comment... It does not completely work out.

Please upload a .blend

Using bmesh.

Recommend using bmesh for this. Where instead of splines, use edges. The vertices in the same location as the spline points. Manipulate the bmesh via the API and then convert to curve.  If there was a bcurve module would use that, but there isn't and curve edit operators are designed to drive one bonkers.
In the test script below, for part 1 I've used all of the  string curves to make one bmesh.  Would change up the creation script in question to create a bmesh in first place, for answer sake I've scripted to use the curves created via the script in question.
All edges which have a vertex in the positive quadrant are selected. The selection is then bisected by one of the 3 axis planes. The resulting geometry bisected again and again by other two axes. This will add a vertex on each edge that crosses the planes.
Next all edges that have both verts in the positive quadrant are removed and the subsequent mesh converted to a curve.  I've used the operator here for example sake. Your question already displays how this is done via API.
The resulting curve object has multiple splines rather than being multiple objects, see note below.
import bpy
import bmesh

context = bpy.context
#PART 1 load all single splne curves to one bmesh
scene = context.scene
bm = bmesh.new()
curves = [o for o in scene.objects if o.type == 'CURVE']
for c in curves:
    verts = [bm.verts.new(p.co.xyz) for p in c.data.splines[0].points[1:-1]]
    for i in range(len(verts) - 1):
        bm.edges.new((verts[i], verts[i + 1]))
    bmesh.ops.transform(bm, verts=verts, matrix=c.matrix_world)

# select all edges with a vert in pos quadrant
def is_inquadrant(v):
    return all(getattr(v.co, axis)  >= -1e-4 for axis in "xyz")

geom = [e for e in bm.edges if any(is_inquadrant(v) for v in e.verts)]

# bisect the selection by three axis planes
ret = bmesh.ops.bisect_plane(bm,
            geom=geom,
            plane_no=(0, 0, 1),
            plane_co=(0, 0, 0))
ret = bmesh.ops.bisect_plane(bm,
            geom=ret['geom'],
            plane_no=(0, 1, 0),
            plane_co=(0, 0, 0))
ret = bmesh.ops.bisect_plane(bm,
            geom=ret['geom'],
            plane_no=(1, 0, 0),
            plane_co=(0, 0, 0))
# Now have new verts on cuts, select edges with both verts in quad
for v in bm.verts:
    v.select = False
for e in bm.edges:
    e.select = all(is_inquadrant(v) for v in e.verts)
# remove them
geom = [e for e in bm.edges if e.select]
bmesh.ops.delete(bm, geom=geom, context=2)
me = bpy.data.meshes.new("BallEdgeMesh")
bm.to_mesh(me)

bm.free()

# add as mesh to scene.

ob = bpy.data.objects.new("BallMesh", me)
scene.objects.link(ob)
scene.objects.active = ob
ob.select = True
# convet to curve
bpy.ops.object.convert(target='CURVE')
curveData = context.object.data
curveData.dimensions = '3D'
curveData.resolution_u = 2
curveData.fill_mode = 'FULL'
curveData.bevel_depth = 0.02
for s in context.object.data.splines:
    s.use_smooth = True
    s.type = 'NURBS'

Note:
If you must have one object for each string:
It would be more efficient to make only one "string" curve object (bpy.data.curves) and link  to each object instance.  Using methods similar to above would only need to add a new curve if it is bisected.
Finally welcome to bse, and kudos on writing a great first question.


text:
Set vertex normal in a stable manner with python
I wanted to set normals from a script, using this code (in a class method):
for face in modelMesh.polygons:
    face.use_smooth = True  # normals have effect only if smooth shading
for i in range(len(self.vertices)):  # set normals here because they seem to be lost in some calulations
    if self.normals[i] is not None:
        modelMesh.vertices[i].normal = Vector(self.normals[i])
for loop in modelMesh.loops:
    loop.normal = Vector(self.normals[loop.vertex_index])

however, if this sets the normals to the mesh's vertices, they are reset after using 'modelMesh.update()' or switching edit mode on and off
(and btw it seems that the loop normals stay 'Vector((0,0,0))' whatever I try, even '.normal[:] = Vector((1,0,0))' and '.normal[:] = (1,0,0)')
is there a way so set vertex normals permanently using python?
thanks in advance

I found it by observing two mesh importing add-ons, but I didn't understand how exactly it worked.
What I know is that it can only affect loop normals, not face nor vertex normals (so that won't help you if you have faces with "front" and "back" part swapped)
mesh.create_normals_split()

for face in mesh.polygons:
    face.use_smooth = True  # loop normals have effect only if smooth shading ?

# <set normals (mesh.loops[ ? ].normal= ? )>

# create custom data to write normals correctly?
mesh.validate(clean_customdata=False)  # important to not remove loop normals here!
mesh.update()

clnors = array.array('f', [0.0] * (len(mesh.loops) * 3))
mesh.loops.foreach_get("normal", clnors)

mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons))

mesh.normals_split_custom_set(tuple(zip(*(iter(clnors),) * 3)))
mesh.use_auto_smooth = True
mesh.show_edge_sharp = True  # optionnal

What I don't get... the "mesh.loops.foreach_get(..." seems to always return an array of 0.0... whatever the values in "foreach_set(...". Any idea?

maybe update() -ing the mesh before that?
I mean, your problem is precisely what I avoided with this piece of code
by the way, to cover the 2% chance that you didn't see that, you must set the loop normals in the middle of the code.
Hope it helps...


text:
Is there something you're supposed to write in for blender scripts in BGE?
I couldn't find anything online and well... when I bring up my code, which makes a simple sphere in BGE blenders game engine it doesn't run til after I close the game and that's where it creates the mesh. Is there something you're supposed to put into the code for blender to run it outside of the viewport?
here's my code, it runs and does what I want it to... only after I've closed BGE which noone else seems to have run into.
import bpy
for obj in bpy.context.selected_objects:

    bpy.ops.mesh.primitive_uv_sphere_add(location=origin)
    bpy.ops.transform.translate(value=(ObjX,ObjY,ObjZ))
    setMaterial(bpy.context.object, blue)
    bpy.ops.object.shade_smooth()

if __name__ == "__main__":
    run((0,0,0))

Those are Blender module operators, not game engine ones. You can't run Blender operators inside game engine, nor create or alter Blender data during a game run.

well what good is that

Simple way to paste scripts here.  In blender text editor, select all, hit the tab, this makes whole script tab right one, copy and paste here.  Shift tab, moves it back.

bge add objects
::: script run once

here's my code, it runs and does what I want it to... only after I've closed BGE which noone else seems to have run into.

Your code is Blender code rather than BGE code.
You basically tell Blender what to do. But you want running a BGE game session.
BGE behavior is setup via Logic Bricks (Logic Editor). You can create a custom Controller brick. It refers to a text block (script mode/module mode) or an external python file (module mode).
The code should not refer to Blender (do not import bpy). When you distribute your game Blender will not be available and running such code will result in errors.
More information can be found at Blenderartists.org. E.g. The BGE Guide to Python Coding
Just to let you know: The BGE does not support mesh creation. All objects and meshes must be loaded either at startup or via Python code while running the game. You can make copies of loaded objects as long as they are inactive (reside on an hidden layer).


text:
How do I make objects jump back to start within a given radius of an area after a collision to a specific object?
How do I make objects jump back to start within a given radius of an area after a collision to a specific object?
What I am trying to do is make a rotating snow plain (who's texture is invisible) jump back up to its initial Z position and choose a random X, Y position within a specific radius. I would like for it to do this after colliding with a specific plain object that's been placed under the terrain.
[out of game snow]

[Edited version to better show what I need]
[]2

While I wasn't exactly able to get the effect I wanted using this method I found that I could take a UV sphere, or possibly an Ico-Sphere and set the texture to an alpha clip while also simply rotating them on the Z and X(y depending on which way you want it to rotate) directions. This gives a nice looking snow effect, and might even work with dust. The shape must always be close to the ground in order for it to give a desired effect.


text:
Animation Not Rendering all the Way Through
I have several cameras that each take over at some point during the animation. While rendering, the last camera doesn't render; only the first one does.

I thought maybe it would be because I can only have a limited number of cameras, so to make a test, I erased the first. However, the last one still does not work.
I am using the VSE for post processing.

Please supply a blend file.

@AnthonyForwood thanks for answering, and solve it.

OP's answer to the question that was originally an edit.
I solved the problem! I'll leave it here if anyone needs the help.
The problem was that in the VSE, the scene I used initially lasted only 700 frames. Later, I added more animation to the scene, but did not lengthen the VSE Scene strip.


text:
Switching between pan and orbit while holding MMB
In previous versions of Blender I've used, pressing or releasing Shift while holding  MMB would switch between orbiting and panning, without needing to let go of  MMB. In my fresh installation of Blender 2.77 (on Ubuntu Linux 16.04), pressing or releasing Shift while holding  MMB does nothing; if I wasn't holding Shift when I pressed down  MMB, then it would stay in orbit mode, no matter what. How would I restore the old behavior?

Borrowed from:
https://blender.stackexchange.com/a/187781/143201
This is verified working in Blender 3.0.1 and involves changing the keymap:

Go into Edit -> Preferences -> Keymap
Search for view3d.rotate and find the one bound to Mouse / Middle Mouse
Under View3D Rotate Modal, click Add New
Pick Switch to Move from the list
Expand the tiny ▶ next to Switch to Move (if you try and do it on the A just to the right without expanding, it won't let you pick Shift)
Click the A next to Switch to Move and press Left Shift
Pick Press from the drop-down to its right

Now repeat the process for view3d.pan, Switch to Rotate, and Release

This is a setup that works great in Blender 3.6.5 and solves the problem of not getting stuck moving when you release the Middle Mouse.
Go to Blender Preferences > Keymap > 3D View > 3D View (Global)
And add these four items as the picture shows.

Basically:

Add a Switch to Move on Left Shift Press and a Confirm on Middle Mouse Release to your Rotate View Modal.
Add a Switch to Rotate on Left Shift Release and a Confirm on Shift + Middle Mouse Release to your Pan View Modal.

Got to File > User Preferences > Input > 3D View > View 3D Rotate Modal and add a new key combination
Set it to Switch to Move and add any key combination you like.
I did not succeed settings it to work with the Shift key though, it seems to not like "modifier keys" on their own, but most other combinations will probably work.

As you said, this doesn't work for modifier keys, so this unfortunately won't work for me


text:
How do I create a squeeze tube packaging?
I've just moved from Cinema4D to Blender and I would like to create a squeeze tube where it is rounded at the bottom and tapers into a thin ellipse at the top. In Cinema4D I used a loft nurb and a circle spline. I've found the cirlce path in Blender but how do I connect them to create this shape?
Thank you for any help.
Edit: I want to create packaging like the image below.

Can you add a screenshot of what you hope to accomplish?

I've added an image in to the original post of what I'm looking to create.

I believe a mesh approach instead of a curve approach will be faster. This is my final result:

The Procedure
Delete the default cube by keying X to open the Delete menu and keying Enter.
Shift + A > Mesh > Cylinder adds a cylinder. S, then Z, then 3 scales the cylinder up on on the Z-Axis by a factor of 3.

Tab into Edit Mode. Place the cursor in the middle of the tube but to the right side, a few pixels to the right of the red arrowhead shown in the above image. To add loopcuts so our mesh has both more detail and square faces, key Ctrl + R, then 28. Do not do anything else. Your mesh should look like the following. Note the pink loops around the circumference.

Key Enter, then  RMB immediately to confirm the loopcuts in their default position. Use Alt +  RMB while hovering the cursor over the topmost edgeloop to select it. Key O to turn on Proportional Editing and set the Proportional Editing Falloff Type to Sharp ( in the 3D Viewport Menu Bar). Proportional Editing will allow us to move multiple edge loops at once in proportion to one another. Key S, then Shift + Z, then 1.5, then  MW scroll up until you have a white circle about the size shown in the following image (6.12). This will stretch the top of the squeeze tube outward giving it its distinctive curvy edges.

Confirm the scaling with Enter.
Key S, then Y, then 0.03, then  MW scroll up until you have a white circle about size 9.85. Confirm the scaling with Enter. This will thin the top into part two of its distinctive shape, shown below.

Key E, then 0.4, then Enter to extrude the top of the squeeze tube up along the top face's Normal. This gives the tube its heat sealed top thing. Key Ctrl + Tab, then 2 to switch to Edge Select Mode. Use Alt +  RMB to select these edge loops:

Key Shift + E, then 1. This Creases the edges so that they stay in their modeled position during a Subsurf operation, performed next. Tab out of Edit Mode. Go to the Properties panel > Object Modifiers tab and add a Subdivision surface and Edge split modifier, shown below. The Subsurf will smooth the mesh, while the Edge Split will retain hard edges at the Creased edges after Smooth shading the mesh, performed next.

Go to the 3D Viewport > Toolshelf > Tools tab > Edit dropdown and select Smooth shading.
Here is the .blend file:

Thank you so much for this, I will try it out. I really appreciate all of your time and help.

The top part is reason I've gone with the plane. It creates ugly ngon and it isn't straight. Filling it with grid fill or merge at center isn't a good way too.

@Shiro Glad that it helped you!

Can you add in your answers a bit more short explanations of your steps instead of strict listing used keyboard shortcuts ? It's a bit hard to read that because one has to have very good imagination to visualize your procedure.

@MrZak Ok, I'm listening. Can you comment an example of what I wrote and then how you might improve upon it? I'm not quite sure I understand exactly what's troubling about it. Thanks for the feedback!

I've already wrote what looks weird. Your procedure consists of wall of shortcuts and commands assumed to do. You provide info about how to do (imho too much detailed, but whatever) but rarely about why and what in fact are you doing (short resume). Have you ever tried to visualize to yourself those isntructions without opening Blender ? One has to switch back and forth between Blender and browser in order to make your step-by-step. It's hard to remember "S > Z > 0, RMB, E, A" etc. It's much easier when it's "Scale faces to 0 by Z axis to flatten them, select one, extrude, deselect".

@MrZak Ok, I'll look at it. Maybe the reason I generally don't do it is because I can visualize what all the shortcuts do without Blender. Also, most OPs can, too, because so far, I haven't heard back from any of them :) Another reason that I write in keyboard shortcuts is so anyone with even a minuscule amount of knowledge pertaining to Blender can understand and make what I make. People like us might not need it, but some noob who stumbles across this post still might.

@MrZak See my edits. If you approve, please consider upvoting :). If you still don't, I'll welcome more input.

In this case I would not go with Curves as they aren't best choice in terms of modeling in Blender. My method is based upon simple plane which gives us very simple base geometry and allows to have nice top part of model. Starting with circle will give massive headache to close and straighten up this part of a mesh.
This is method I've used to model it:

Add a Plane - Shift + A > Mesh > Plane.
Go to Edit Mode.
Select all vertices, press E and extrude along Z axis.
Select top edge and press S > Y to squize it.
Extrude top edge along Z axis once more.

You should have now something like this:

Add Modifier > Subdivision surface and set it to 4-5 (preview and render).

Now we need to crease some edges.

Select all top vertices and set Mean Crease to about 0.6.

Do the same with bottom vertices but this time Mean Crease should be 0.3.
Add Loop Cut (CTRL + R then hover cursor over mesh) to 'main part' of the mesh and place it near bottom edge.
Choose Smooth Shading. Object Mode > Tools Panel (left side of the screen) > Shading > Smooth.

Here is blend file to play with:

Thank you so much for helping me with this in so much detail, I really appreciate your help.

I've forget to add step to set Smooth Shading. You could set it in Object Mode > Tools Panel (left side of the screen) > Shading > Smooth. I'll add it to the edit.

Blender does support NURBS but its support is quite limited at the moment.  What you are looking for is Add -> Surface -> Nurbs Cylinder.  Then you would have to manually tweak the control points to generate the desired shape.

That's great, thank you. How did you add more control points to it?

Just selected one loop and extruded (E key).

authors: Дмитрий Потапов


text:
Cycles Render Output Black
So my problem is simple: My render output is black.
I have rendered correctly before but now fear that I have accidentally changed a setting. I can't seem to figure out what it is...
My file is on Google Drive; hope that's okay.
Thanks guys.

Please post your file here for BSE questions.

Apologies. Will do next time.

Go to the Properties panel > Render Layers tab > Layer dropdown and erase BoneMaterial as your Material:

From the Wiki (regarding Material Override):

Overrides all material settings to use the Material chosen here.
Examples of where this might be used:

To check lighting by using a plain diffuse material on all objects

Render a wireframe of the scene

Create a custom render pass such as an anti-aliased matte or global coordinates.

You had inadvertently changed every material in the scene to one that did not render correctly.
EDIT:
Newer versions of blender don't use layers, but "collections" so the override function is in the scene>View Layer section.

Additional info:
Where is the Layers panel in Blender 2.8?
2.8 - Is it possible to assign (override) a material to a whole collection?

Thank you so much. I was looking for close to two hours. :)

May I suggest adding a few words as to why the material override caused the problem? May prove helpful to someone else in the future.

@Tim Glad to help!

@Timaroberts Does this help?


text:
Blending materials
I was wondering how to blend materials to get a nice look to my meshes. At the moment they're looking like:
as you can see at the top, the dirt material doesn't blend with my grass material. Is there a way to do that?
PS, if there is a way, if I export this mesh to ue4, will it still have the gradual material?
Thanks, Max

There is a way to do this using BI Nodes. As for the exporting, I don't know. Here is the final result:

Add two materials to your plane, a dirt and a grass. Assign the dirt material to the top of the plane. Make sure the dirt material is brown/black, and the other is greenish. For the grass texture, click the nodes button:

Go into side orthographic view, Tab into Edit Mode, key U to open the Unwrap menu, and select Project from View (Bounds).
Go to the Properties panel > Textures tab and add a new texture. Set it to Blend. Under the Color dropdown, check Ramp. This will control how much brown vs. green there is, where it fades, and how sharp the fade is. Under the Blend dropdown, choose Vertical. Under the Mapping dropdown, set the coordinates to UV and select the previously created UV Map. Make sure nothing is checked under the Influence dropdown.

Open a Node Editor. Use the following node setup.

Here is the .blend:

Just a note: to export, set one material to black and another to white. Make both materials shadeless. Bake the material map and use that in UE4 to blend the dirt and grass materials.

Max, whether or not your blended materials will export to UE4 depends upon how UE4 is designed. Most game engines do not presently support cycles render, so it is possible export will not work.

This question is tagged blender-render.

For the use within Blender you could go with vertex colors. Just Tab into Vertex Paint mode, choose a color and paint away. However, to use this in any RT engine you need to bake the vertex colors to a texture.


text:
Materials not applied after importing .obj (ShapeNet)
I want to use Blender to generate a dataset of videos. As a basis I want to use ShapeNet.
When importing the .obj file, blender also correctly loads all the materials from the .mtl file. By that I mean that they are listed in the material tab of the properties window. But for some objects the materials are not correctly applied to the surfaces.
Example: The object with the ID 3dw.e480a15c22ee438753388b7ae6bc11aa should look like this:

However, if I just import the file in blender, the rendering will look something like that:

So, the colors of the knobs work, also the textures of the pillows, but the rest of the colors don't.
What seems strange to me is, that I cannot select the different faces and color them myself in blender. Also, if I move the main part of the bed, a frame of lines will remain there. Maybe this has something to do with the problem:

Similar problems occur for many objects. For example 3dw.b1696ffd98c753ccea88a0a7eb1222bb. There, the problem with the frame of lines does not occur and I can color the airplane afterwards, but it somehow does not load the materials when imported.
How can it be, that it works for some objects but for others it doesn't?

Possible duplicate of .fbx export why there are no materials or textures?

I don't think so. I did not export the model but start with an .obj and a .mtl file. The materials are all listed in the materials tab of the properties window, they are just not applied to the faces they ought to be.

This problem with the materials in Blender with the ShapeNet objects seems to be a common one. This worked for me (I used ShapeNetSem):
You can convert your .obj models to .gltf format using the obj2gltf package. Be sure that the ShapeNet textures can be found during converting: I had to put all the .jpg texture images inside the same directory as the .obj and corresponding .mtl files (you can see which textures are needed for a model by opening its .mtl file in a text editor). Then import your .gltf models in Blender. They should now load properly.
On top of that, you can also try to turn off Backface Culling and Auto Smooth, in Blender. This wasn't necessary in my case, but I've read it helps for some people.


text:
Setting up a Sky: bpy.context.world = None
I am trying to set up a sky in my script using
bpy.context.scene.world.use_sky_paper = True which results in the following error:
AttributeError: 'NoneType' object has no attribute 'use_sky_paper'

Why does bpy.context.scene.world return None? Is there some setup required for the world?
I encountered a similar problem, when trying to see which area is active via bpy.context.area.type where area is None.
Update: bpy.context.area is always None when running script headless.

Your assignments working as expected for Blender 2.78c... Also context.area.type is never none. Cycles or Internal? What blender version? Are you trying to execute that commands headless (without UI)?

I am using blender 2.78 with internal render. I am not scripting inside blender but using an external python script executed with blender --background --python <name_of_script>. Executing print(bpy.context.area) prints None to the console.

Since you are running these commands headless and bpy.context.area returns the active area of the UI, it's totally obvious why the property is none. Also I have no problems printing World.use_sky_paper to the command line. Does this example helps?

ok. So that part of my question is answered. The mode of the object is already object mode. The error persists when inserting bpy.ops.object.mode_set(mode='OBJECT') as suggested by the example.

If not set scene.world is None.  Simply set it, for example to a world named "World" with scene.world = bpy.data.worlds.get("World") , or create a new one.
import bpy

scene = bpy.context.scene

if scene.world is None:
    # create a new world
    new_world = bpy.data.worlds.new("New World")
    new_world.use_sky_paper = True
    scene.world = new_world

I am at the moment on another device: On my MacBook, it seems scene.world is already defined from the beginning. So I can check your solution only tomorrow. Any idea why that can depend on the PC, if blender version and script are the same?

My guess would be to check startup.blend, you may have inadvertently removed world from scene.

Solution works. Problem was indeed with startup.blender

Is this a pre-2.8 fix?


text:
Install external package in Blender (python websockets)
I'm working on a script that processes some data coming from a web application running on a phone. The web application, written in javascript, sends data to the "blender python server" using websockets.
The code doesn't compile with the error:
ImportError: No module named 'websockets'
But that's not true, I have websockets installed, using pip, on my machine. And I've already used them with no problems. Is it possible that the blender environment prevents me to use them? Did anyone ever have any problems with some modules installed using pip?

You need to look at using third party modules with blender as it uses its own copy of python. It is also possible to set sys.path so that blender can find your system modules.

The solution, as suggested by @Javier is to install the python modules inside the python blender folder.
On my Mac machine, the python module folder is located at:
/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5
Hence, we can install a new python module running a pip command:
pip install -t <direct directory> <package>

Update for Blender 2.8:
Blender 2.8 simplifies the installation of external packages, coming with pip already installed. To install an external package go to python's bin folder and run:
./python3.7m -m ensurepip (Just the first time)
./python3.7m -m pip install package

You need to have the modules youre planning to use, on the python path where blender looks for the modules. blender comes with its own python installed. browse the blender directory youll find it. This is probably the cacuse.
just copy your python/lib/sitepackages folder on it and I think youll have it done...


text:
Decimate only "bad" objects in a scene
I'm working for a company and they have to optimize 3d scenes to be rendered in virtual reality. The problem is that the people who are modeling the scenes are really bad at doing that. I've seen scenes where small objects had a really large amount of vertices (imagine a scene where a building has, let's say, 100 k vertices, and only one lamp has 15 k vertices...)
I want to write a script that decimates the geometry only for those objects that have an insane number of vertices but, how do I detect them?
I was thinking about computing the volume for each mesh and compare it with the number of vertices, but this would be really expensive and I'm not sure It's a good way to detect such meshes.
Any suggestions?

I feel your pain. Had House model for VR, had hidden pipes in the walls that had a huge number of vertices not to mention the Aircon unit on the outside wall had 100k vertices. For the aircon I gave up decimating it and just modelled it from scratch.

This script:
import bpy, bmesh

THR = 4  # <-- the only parameter. The smaller, the stricter

for element in bpy.data.objects:
    if element.type != "MESH": continue

    # reset
    for m in element.modifiers:
        if m.name == 'ScriptedDecimate':
            element.modifiers.remove(m)

    # scoring function
    vert = len(element.data.vertices)
    areabbox = (element.dimensions.x*element.dimensions.y
               + element.dimensions.y*element.dimensions.z
               + element.dimensions.x*element.dimensions.z)*2
    indicator = vert/areabbox

    # select and decimate!
    if (indicator > THR):
        element.select=True
        decimator = element.modifiers.new("ScriptedDecimate", type = "DECIMATE")
        decimator.ratio = (THR/indicator)**(2/3)
        bpy.context.scene.update()
    else:
        element.select=False

can be useful.
It creates a Decimate modifier for each element where the number of vertices, divided by the surface area of the bounding box, is greater than a set threshold THR. It also adds these object to your selection (and removes all the unaffected meshes). It resets its actions every time you run it again (to avoid double modifiers).
The Decimate Ratio depends on "how far" the original vertex count per area was from the threshold (but it doesn't try to decimate it right to the point where it doesn't exceed the threshold!).

↑↑   verts, faces (tris): 6171, 7182 (12218) → 1743, 2601 (3374)


text:
Replace matrix @ vector list comprehensions with something more efficient
I'm looking to replace list comprehensions like the following with something more efficient and I was wondering if numpy can be used.
[obj.matrix_world @ v.co for v in obj.data.vertices]

I can do this, which is significantly faster, but still lacks the matrix multiplication, that needs to happen for each coordinate.
coords = np.empty((len(obj.data.vertices), 3), 'f')
obj.data.vertices.foreach_get('co', np.reshape(coords, len(obj.data.vertices) * 3))

I was hoping it would just be
np.matrix(obj.matrix_world) @ coords

But that fails with (FWIW, It's just a cube, hence (8, 3))
ValueError: shapes (4,4) and (8,3) not aligned: 4 (dim 1) != 8 (dim 0)

Similarly, doing
for co in coords:
    np.matrix(obj.matrix_world) @ co

fails with
ValueError: shapes (4,4) and (3,) not aligned: 4 (dim 1) != 3 (dim 0)

So I've hit a wall now. Numpy can't multiply a 4x4 matrix with a 3d vector, but Blender can. How do I solve this in a numpy way?

edit:
Based on @JoseConseco's excellent reply below, this is what I'm doing now
mx = active.matrix_world
verts = active.data.vertices
vert_count = len(verts)

coords = np.empty((vert_count, 3), 'f')
verts.foreach_get('co', np.reshape(coords, vert_count * 3))

coords_4d = np.ones((vert_count, 4), 'f')
coords_4d[:, :-1] = coords

coords = np.einsum('ij,aj->ai', mx, coords_4d)[:, :-1]

Note, that there's no need to convert the (mathutils) Matrix into an np array. It works fine just like that.
Based on my tests, doing this via numpy is ~3 times faster than the list comprehension.

Even though your problem takes place in Blender, it's a generic math problem and there is a StackExchange for math.  I imagine that you will have an easier time finding linear algebra guru's over yonder ;)  There will be some here too of course, no offense intended :)   https://math.stackexchange.com/

Maybe yes, but I don't speak their language :) and felt this should be a common enough (or at east useful) issue in Blender circles.

I'm voting to close this question as off-topic because it is a general Python problem which isn't specific to Blender.

I think the question is fine. I would suggest editing title, such that it is more akin to the question  "replace matrix @ vector list comprehensions  with something more efficient"

Quickest way AFAIK:
mat = np.array(self.curveObj.matrix_world)

verts_co = np.zeros((vertCount*3), dtype=np.float)
mesh.vertices.foreach_get("co", verts_co)
verts_co.shape = (vertCount, 3)
verts_co_4d = np.ones(shape=(vertCount, 4), dtype=np.float)
verts_co_4d[:, :-1] = verts_co  # cos v (x,y,z,1) - point,   v(x,y,z,0)- vector
splinePoints_world = np.einsum('ij,aj->ai', mat, splinePoints)

In addition to JoseConseco answer, changing
np.einsum('ij,aj->ai', mx, coords_4d)[:, :-1]

into
np.dot(coords_4d, mx.inverted())[:, :-1]

Should improve performance.
The entire script:
vlen = len(obj.data.vertices)

vco = np.empty(vlen * 3, 'f')
obj.data.vertices.foreach_get('co', vco)

coords = np.empty((vlen, 4), 'f')
coords[::4] = 1.0
coords[:,:-1] = vco.reshape((vlen, 3))

coords = np.dot(coords, obj.matrix_world)
res = coords[:,:-1].reshape((vlen*3))

obj.data.vertices.foreach_set('co', res)

reshape is basically free operation in Numpy, so should be used liberally. np.empty also just allocates memory, doesn't write it so maybe saves some time.

Thank ambi, I appreciate you chiming in! I'm also using empty and reshape. I've also just noticed that float64 seems to be faster than float32. I still need float32(need coords for gpu drawing) at the end,  so I just change it at the end, and it's still faster.
As for, np.dot() I'm actually getting a different result from it than via the einsum() method.  I need to study this some more. Thanks again, much appreciated!

Mesh.transform(Matrix)
As an alternative to using numpy
If the desired result is to transform the vertex coordinates by a matrix then the mesh transform method does exactly this, internally with the passed matrix.
ob = context.object
mw = ob.matrix_world
me = ob.data
me.transform(mw) # transforms all verts by matrix

Timing it.
Timing the methods outlined. Have included mesh transform, a method using mesh transform but returning a list of transformed coordinates, and the two numpy methods outlined above.
Note it is my opinion (test code to put empties at result commented out) that using dot product requires the matrix to be transposed, rather than inverted.
import bpy
import numpy as np
from mathutils import Matrix

import time

REPS = 1000

def time_it(func):
    def wrapper(*arg, **kw):
        t1 = time.time()
        for i in range(REPS):
            func(*arg, **kw)
        t2 = time.time()
        print(func.__name__, (t2 - t1))
    return wrapper

def vert_coords(me):
    n = len(me.vertices)
    coords = np.empty((n * 3), dtype=float)
    me.vertices.foreach_get("co", coords)
    return np.reshape(coords, (n, 3))

@time_it
def transform00(me, matrix=Matrix()):
    me.transform(matrix)

@time_it
def transform0(me, matrix=Matrix()):
    copy = me.copy()
    copy.transform(matrix)
    coords = vert_coords(copy)
    bpy.data.meshes.remove(copy)
    return coords

@time_it
def transform1(coords, matrix=Matrix()):
    n = len(coords)
    coords4d = np.empty(shape=(n, 4), dtype=float)
    coords4d[::-1] = 1
    coords4d[:, :-1] = coords
    return np.dot(coords4d, matrix.transposed())[:,:-1]

@time_it
def transform2(coords, matrix=Matrix()):
    n = len(coords)
    coords4d = np.empty(shape=(n, 4), dtype=float)
    coords4d[::-1] = 1
    coords4d[:, :-1] = coords
    return np.einsum('ij,aj->ai', matrix,  coords4d)[:,:-1]

ob = bpy.context.object
mw = ob.matrix_world
mesh = ob.data
copy = ob.data.copy()
coords = vert_coords(mesh)
transform00(copy, mw)
bpy.data.meshes.remove(copy) # clean up
transform0(mesh, mw)
transform1(coords, mw)
transform2(coords, mw)

'''
# add empty at coordinates to test
transform = transform1 # choose a method
for p in transform(vert_coords(mesh), ob.matrix_world):
    bpy.ops.object.empty_add(location=p)

'''

Some test runs on default primitives
Cube verts: 8
transform00 0.004887104034423828
transform0 0.18675923347473145
transform1 0.08976554870605469
transform2 0.0721430778503418
Sphere verts: 482
transform00 0.014344215393066406
transform0 0.40707826614379883
transform1 0.12292027473449707
transform2 0.12022829055786133
Suzanne verts: 507
transform00 0.012979984283447266
transform0 0.398883581161499
transform1 0.1199808120727539
transform2 0.11667346954345703

Findings.
If the outcome is transforming the vertices then Mesh.transform is way quicker.
The einsum method comes out a squeak quicker than dot product
Trying to leverage off transform, to get an array of transformed coords by copying a mesh, transforming and foreach getting the result, has to much overhead and is slowest.
Iterating over each vertex via a list comprehension (results not shown) is slower again.

Thanks, that's really interesting to use mesh.transform(). It is indeed incredibly fast and I've started to use it in some other areas now.

This is not an answer, but a consecutive question. I hope that is ok.
I'm working on a modal operator and want to quickly get vertex coordinates to pass them to a shader.
The code works fine when working with a list comprehension like this:
self.vert_data = np.array([mat @ v.co for v in verts], np.float32)

Here is how it looks like in the viewport, when working as intended:

For some reason, I'm not able to get implement any of the above methods. Whichever I use, the result turns out like this:

The vertices blow up and cover the entire scene (or so it seems). I'm pretty sure that I'm missing something very obvious here, but I can't find.
Here is the code that I wrote following the answers above:
coords = np.zeros(vert_count * 3, dtype=np.float32)
verts.foreach_get('co', coords.ravel())
coords = coords.reshape(vert_count, 3)
coords_4d = np.ones((vert_count, 4), 'f')
coords_4d[:, :-1] = coords
# self.vert_data = np.dot(coords_4d, mat.inverted())[:, :-1]
self.vert_data = np.einsum('ij,aj->ai', mat, coords_4d)[:, :-1]

Many thanks!

I haven't touched this code in ages, but I have this in there:
01 # float64 seems faster to calculate than 32, + the einsum turns it into 64 anyway
02 # but float32 is needed for gpu drawing, so convert
03 coords = np.float32(coords)
maybe try this.

Oh wow, I just saw this now. Thank you so much. I will definitely try! :)


text:
How to select scale x,y,z keyframes all at once in graph editor
For a simple scaling animation, I am trying to change the bezier curve for all three dimensions at the same time. I know that I can box select the keyframe itself and move it with g, but I cannot figure out how to grab the handles for all three dimensions at the same time.
Thanks for the help :)

In the Graph Editor, on the right side you will see the sidebar that shows you all objects and items that have some animation attached to it. Select your object from that list and make sure to widen the drop menu of it beside its name. There you will see the different axis. Using Shift select all of the. Next in the actual editor press A once or twice so all handles are selected and then press S to scale all of them.

To select all the keyframes, click Control+A.

...It should be just "a".  You don't need Ctrl.


text:
How to quickly assign an individual material to color thousands of cubes at the same time with python API in Blender 2.8?
Let us just say you have a 100x100 cubes 2d grid and each cube will be assigned its own individual material. How can you do this? My code below worked initially when I created all the cubes as individual objects but it took a very very long time to create that many cubes. I was then told I can speed up this process by just copying over the mesh from the first cube to help create the next cube. This speeded up the process but when I tried to run my coloring functions all the cubes now shares the same color material. I assume this is because the new cubes inherited it's material from the creation of the first cube. I think its has something to do with the last else statement below but I am not sure.
How can I keep the speed gain from copying cube mesh to create cubes without inheriting the initial material color from the first cube as well? I asked this question in the Blender official chat a whiles ago and was told to use MaterialSlot(bpy_struct) and I have no idea how it works.
Full relevant code
class Create(Animation):

    def __init__(self, collection_name, H, W, y_axis):

        self.collection_name = collection_name
        self.H = H
        self.W = W
        self.master_collection = bpy.context.scene.collection
        self.myCol = bpy.data.collections.new(self.collection_name) # Automatically create the correct layer
        bpy.context.scene.collection.children.link(self.myCol)

    def create_block(self, x_axis, y_axis, z_axis):
        """
        1) Takes the Height and Width and create a 3D wall in Blender
        2) Center it in the middle, assign it to the given collection
        3) Translate corresponding pixel values to the correct mat color

        Args:
            H -- The height(int)
            W -- The width(int)
            collection -- The collection this block belongs too(str)
        """

        if self.collection_name == "input_image": # try mycol flag

            self.x = x_axis
            self.y = y_axis
            self.z = z_axis

        elif self.collection_name == "filters":

            self.x = x_axis + 69
            self.y = y_axis
            self.z = z_axis + 69

        pixel_idx = 0 # corresponding pixel value index from the tensor

        bpy.ops.mesh.primitive_cube_add(size=2, view_align=False, enter_editmode=False, location=(self.x, self.y, self.z)) #create initial cube

        cube = bpy.context.scene.objects[0] # remove the duplicate cube from initbpy.ops

        for height in range(self.H): # z-axis

            for width in range(self.W): # # x-axis

                new_cube = bpy.data.objects.new(self.collection_name + "cube", cube.data) #cube.data = mesh struct

                new_cube.location = (self.x, self.y, self.z)

                self.myCol.objects.link(new_cube)

                #self.master_collection.objects.unlink(new_cube)

                self.x += 3

            if self.collection_name == "filters":
                self.x = x_axis + 69
            elif self.collection_name == "input_image":
                self.x = x_axis

            self.z += 3

        bpy.ops.object.delete()

    def fill_pixel_value(self, tensor_img):

        self.image_flatten = tensor_img

        self.obs = bpy.context.scene.objects

        for i, o in enumerate(self.obs):

            name = o.name #grab the cube's name

            mat = bpy.data.materials.get("Material")

            if mat is None:

                mat = bpy.data.materials.new( name + "_Material" )

                #Change the mat color to the corresponding image_flatten tensor values
                # This used to work but now the first cube I made has the dominate material.

                mat.diffuse_color = ( self.image_flatten[i], self.image_flatten[i], self.image_flatten[i], 1 ) #RGBA

                # Assign it to object
            if o.data.materials:

                # assign to 1st material slot

                o.data.materials[0] = mat

            else:
                # no slots

                o.data.materials.append(mat)

One mesh, object linked materials.
You are trying to make same linked mesh have different materials on a different object. Using object linked materials can use only the one mesh, and N x N materials and objects.
import bpy
context = bpy.context
scene = context.scene
count = 32

bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
ob = context.object
dx, dy = ob.dimensions.xy
bpy.ops.object.material_slot_add()
ob.material_slots[0].link = 'OBJECT'

mat = bpy.data.materials.new("Mat")
ob.material_slots[0].material = mat
for i in range(1, count * count):
    o = ob.copy()
    o.material_slots[0].material = mat.copy()
    # set some mat props
    o.location = (dx * (i % count), dy * (i // count), 0)
    scene.collection.objects.link(o)

One material could be used here instead by mapping texture coordinates via the object.

Method 2: 1 material, N x N objects and meshes.
Grid, UVMap image texture, edge split, solidify, separate by loose parts
Using the same methods as outlined to you here https://blender.stackexchange.com/a/131765/15543
Material is an image texture mapped to the UV. This way we only have one material. The UV can be mapped to 1 pixel squares.

Result of script. Image is 128x128, grid was split 32 x 32

So each block has a top with 4x4 pixels.
import bpy
context = bpy.context

bpy.ops.mesh.primitive_grid_add(
        size=10,
        x_subdivisions=33,
        y_subdivisions=33,
        calc_uvs=True)

ob = context.object
me = ob.data
me.materials.append(bpy.data.materials["Material"])
sfy = ob.modifiers.new(name="Solidify", type='SOLIDIFY')
sfy.thickness = 1 / 3
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.edge_split()
bpy.ops.mesh.separate(type='LOOSE')
bpy.ops.object.mode_set()

bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')

Creating 128 x 128 objects and as many materials too is going to be slooooooooooooooooow.
Can be optimized for speed somewhat. Not sure it's worth it for zero feedback.

Method 3: 1 object, 1 mesh, N x N materials.
Single cube, applied array modifiers, materials assigned to each part
Similarly to this answer https://blender.stackexchange.com/a/61254/15543 can create an array mesh very quickly.
After the array modifiers are applied the faces are still ordered such that each 6 belongs to a cube.  A new material is added for each and assigned.  The row and column of the parts can be obtained using integer div and modulus and hence can be mapped to pixel colour.
For example sake I've only made a 32 x 32 array. Note the offset is at 1.5, change to 1.0 to have touching cubes.
To make each a single object, separate by loose parts as above. This is the rate-determining-step.  As one mesh, individual parts can be animated via hooks, armature, shapekeys.
import bpy
from bpy import context
# add a cube
bpy.ops.mesh.primitive_cube_add()
ob = context.active_object
me = ob.data
# add two array modifiers
count = 32
arrays = {"x": (1.5, 0, 0),
          "y": (0, 1.5, 0)}

for axis, displace in arrays.items():
    mod = ob.modifiers.new(axis, 'ARRAY')
    mod.count = count
    mod.relative_offset_displace = displace
    bpy.ops.object.modifier_apply(modifier=mod.name)

def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i+n]

material_index = 0
for cube in chunks(me.polygons, 6):
    mat = bpy.data.materials.new("Mat%d" % material_index)

    mat.diffuse_color[0] = material_index / 100
    me.materials.append(mat)
    for f in cube:

        f.material_index = material_index
    material_index += 1

Alternatively could use a UV map here also, for 1 object, 1 mesh (with NxN parts) and 1 material.

Thank you for all these wonderful pieces of information. I did manage to figure out why its not working and it's exactly like you said. I was trying to apply a material to an object's mesh which was the same cube mesh, instead, I should of created to material under the object itself. Thanks again.

Follow up question, I am currently trying to integrate the first method you showed me. I want to loop through all my OBJECTS after I create them. I first want to create an empty material slot but when I tried to use bpy.ops.object.material_slot_add() I get RuntimeError: Operator bpy.ops.object.material_slot_add.poll() failed, context is incorrect? I tried to google a lower level version of it but no dice.

i) Set object to active first, ii) override context, or iii) add a 'DATA' slot by appending a material to mesh, then change the slot link to 'OBJECT' and remove material from mesh.  Code above copies object with one object linked material slot so you only have to do it once.


text:
How to add custom color picker in blender material panel?
I would like to add a custom colour picker for a custom material section. The colour picker should be below the red line in the image:

I found a code but this make the colour picker on the "tool panel" and not on the "material panel". This is the code:
import bpy

class POSE_PT_test(bpy.types.Panel):
    bl_label = "Test"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Testing"

    @classmethod
    def poll(self, context):
        return True

    def draw(self, context):
            self.layout.prop(context.scene, "test_color", text='Detail Color')

def register():
    bpy.utils.register_class(POSE_PT_test)
    bpy.types.Scene.test_color = bpy.props.FloatVectorProperty(
        name="myColor",
        subtype="COLOR",
        size=4,
        min=0.0,
        max=1.0,
        default=(1.0, 1.0, 1.0, 1.0)
    )

register()

Hope someone can help me to change this code so that it will be on material panel and below the red line. Thanks in advance.

To change your test code to be a panel in materials tab of properties space use   bl_space_type = 'PROPERTIES' and  bl_region_type = 'WINDOW' and bl_context = "material" .  As for adding under red line in image above, (without an ugly hack) would need to edit into the draw code of that panel.

Related Rearranging elements of a panel

@batFINGER Can you guide me to make it under the red line in the image above? I have tried the code suggested by you but it gives error on line bpy.utils.register_class(POSE_PT_test)

You need to change:
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_context = "material"

The panel will end up like this
class POSE_PT_test(Panel):
    bl_label = "The title in the materials section"
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_context = "material"
    bl_options = {'DEFAULT_CLOSED'}
    tag = 0

    @classmethod
    def poll(self, context):
        return True
    def draw(self, context):
        layout = self.layout
        col = layout.column(align=True)
        col.prop(context.scene, "test_color", text='Detail Color')

This is a little late but hope it can help anyone else that comes here


text:
How can i render a frame number in blender video editor
i wanted to show the number of the photographic sequence like this
how can i do it in blender video editor? thank you!

https://blender.stackexchange.com/questions/73961/how-to-add-frame-numbers-over-footage-in-blender-video-editor?rq=1

@JohnEason There is no Blender version given in the question, presuming it's the current stable version - is the accepted linked answer still valid? Is there a working Animation Nodes addon for the latest Blender release?

@GordonBrinkmann There are actually two answers on that page and the bottom one is more relevant to later Blender versions. I'll knock up an answer which should apply to all recent Blender versions.

@GordonBrinkmann: Animation nodes is working for all versions (since it came out at least) - but you may have to compile it yourself.

Does this answer your question? how to add frame numbers over footage in blender video editor

@JohnEason Yeah, but the second answer is a bit unsatisfying since it is just using the metadata over which you have not that much control.

@GordonBrinkmann I assume that's exactly what the original poster was asking for!

@JohnEason I assumed when the question says "like this" it should be looking more individual and maybe some option where to place the number.

@GordonBrinkmann I agree about the placement. In fact if you leave the default items selected and render a frame they end up in all four corners of the image! :^(

@GordonBrinkmann: i know, that's why i voted to close the question because of duplication - and that's what the site does, if you vote it, it adds the comment. You should have known that...

See the Blender Manual entry about Metadata. To add the Frame number to your rendered output, select the Output Properties icon in the R/H panel and scroll down to the Metadata section. You can then check only the information you want shown in the rendered output. Check Burn into Image and choose a suitable font size and colour. I'd suggest at least 24 px font size. The frame number is displayed in the bottom left corner of the output and as far as I can see there's no way of changing its position on the image.

This is the output when frame 7 is rendered

I would do it with Geometry Nodes. Just take any object like a plane for example and add a Geometry Nodes nodetree to it.
Then you take a Scene Time node and plug the Frame output into a Value to String node and that into a String to Curve node. There you can adjust all the settings for font, size, alignment etc. to your liking. Afterwards comes a Fill Curve node and a Set Material node.
Now you can put this object in front of the camera so that it is placed wherever you want it in the image. Parent it to the camera and it will stay there no matter how the camera moves. If you do not want the frame number to interact with anything in the scene, go to the Object Properties > Visibility > Ray Visibility and disable everything except for Camera.
The nodetree:

And the result:

Of course you can put anything in there, the frame number, the seconds, or calculate something based on frames or seconds and put that in there. You could even animate the frame number to be moving while the animation is running.


text:
How do I auto hide other object while editing a selected object
i've been working with almost 30 iterations, and i want to be able to compare them in object mode, but hiding and unhiding some object are annoying because i also have other boolean happening. what i really want is to be able to work on my edit mode, wihtout seeing the other object that i dont select, and as soon as i hit tab and back to object mode, i will be able to compare them all. thanks!

Perhaps selecting the object you want to edit then going into Local View using the Numpad Slash Key will do the job. This will hide all other objects in the 3D viewport until you hit the Numad Slash key again.

Why don't you use Local view? The advantage over hiding and unhiding is, if you don't do it manual, unhiding with Alt+H reveals all objects even if you want to keep some hidden. Switching to Local view will only keep the selected object(s) visible and when you switch back, individual visibility settings of other objects are unchanged. Local view is Numpad / to toggle on/off. @3fingeredfrog Oops, I typed my comment a few seconds too long ;) I forgot an advantage, you can rotate and zoom your Local view as you need it for editing, but when you go back the view is like before.


text:
Is it possible to use bpy in python scripting without Blender app open?
I'm trying to automate the process of rotating multiple NIFTI 3D file and taking screenshots of that rotation using bpy, but WITHOUT blender app itself open.
Not sure whether it will work however...
Thank you all for your help!

No.  But it is possible to run Blender without opening the user interface and use command line arguments to invoke the python script.

To be more precise, you could build Blender as a module for another program and use bpy from the modular blender in that program, but for your purpose, it would be a lot easier to invoke a script from the command line.


text:
How to add images to a deck of cards in an automated way?

I am adding png to material for each Plane Object, problem is I have 1000 of these plane objects for 1000 images to import for each one.
Is there an addons or script I could use for that please because it's very time consuming as you can imagine and it's killing my eyes?

Does each object receive a different image?  If not, you could just assign the same material to every object.  If so, how would you tell a script which image to use for each object?

1000 different images indeed, I was hoping there would be a script out there which could do it matching the name of the image and the name of the object : example   Plane001.png for the material of Plane001 object

I'm using Blender 3.0.0
Try the below python script for 1,000 Planes with PNG materials.
It should produce:
Plane000 to
Plane999
(Note: starts at zero to give you 1,000 Planes)
Also in this code the images should be located in "C:\img\Plane000.png", etc...
Make sure all PNG files are there
Maybe test with 15 at first!
import bpy

# -- create planes
for idx in range(0, 1000):
    # ---- Name for this plane
    plane_name = "Plane" + f'{idx:03}' # ie "Plane000"

    # ---- Create the Plane
    bpy.ops.mesh.primitive_plane_add(size=1)
    obj = bpy.context.active_object
    obj.name = plane_name

    # ---- Create the Material for the plane with PNG
    mat = bpy.data.materials.new("material-" + plane_name)
    mat.use_nodes = True
    nt = mat.node_tree
    # -- Material Output node
    n_mout = nt.nodes['Material Output']
    n_mout.location = (200,0)
    # -- BSDF material
    bsdf = nt.nodes["Principled BSDF"]
    bsdf.location = (-200,0)
    # -- Texture img
    n_texImg = nt.nodes.new('ShaderNodeTexImage')
    filename = plane_name + ".png"
    bpy.data.images.load("C:/img/" + filename)
    n_texImg.image = bpy.data.images[filename]

    n_texImg.location = (-600, -100)
    # -- Links
    nt.links.new(n_texImg.outputs['Color'], bsdf.inputs['Base Color'])

    # ---- Add material to plane
    obj.data.materials.append(mat)


text:
Cant Texture paint on my mesh
so I am not able to texture paint my mesh
the texture is attached to mesh in shading nodes
I have deleted and added the brush again but its not painting

Can you give more details? It would also be helpful if you could share the file.

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

Could try the normal common issues: 1. Check the Normals are facing outward 2. Check that the mesh has UV for painting 3. Make sure the Image Texture used as a target is not also loaded as a Brush Texture in Circular Reference resulting in a similar color to the painting.


text:
Filling hole after using screw modifier
I Have no idea how to fix the hole that is generated by the screw modifier automatically.
Blender version 2.93

If the top and bottom inside points are exactly on the Z axis, there shouldn't be a hole.  Have you tried making sure those points have X and Y coordinates that are exactly 0?

Thanks man It worked !

If the top and bottom inside points are exactly on the Z-axis, there shouldn't be a hole. Have you tried making sure those points have X and Y coordinates that are exactly 0? –
Marty Fouts

works exactly after setting X and Y coordinates zero.
In other cases answer given by @KickAir8p can be helpfull

Although Marty Fouts' comment is a good point, if you've already converted this to a mesh and applied the Screw modifier, then I'd suggest you go into edit mode, select all the edges around the hole, and use Grid Fill.

I tried to do that by referring to other tutorials but every time I select the edge in edit mode it only selects the source edges and not a complete set of edges.
I can see the object is completely selected in Object mode , in edit mode its only selecting source edges

Sorry, what I recommended should work if you've both converted this to a mesh and applied the Screw Modifier -- then if you go into Edit mode you should be able to select all of the edges around the hole and use Grid Fill (I've edited my answer to clarify this a bit).  If you haven't done either of these then you probably want to go with Marty's comment.

I Had a problem with X and Y  coordinates  of vertex , This might help as well If I encounter anything more Thanks for your Answer.


text:
Property fields are not shown in popup dialog, why?
I am attempting to learn Blender and therefore following some Youtube "courses"...
The below code should present a popup dialog with two property fields.
import bpy

class WM_OT_myOp(bpy.types.Operator):
    """Open the Add Cube Dialog Box"""
    bl_label = "Add Cube Dialog Box"
    bl_idname = "wm.myop"

    text = bpy.props.StringProperty(name= "Enter Text", default = "")
    number = bpy.props.FloatProperty(name = "Scale Z Axis", default = 1)

    def execute(self, context):
        bpy.ops.mesh.primitive_cube_add()
        return {'FINISHED'}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)

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

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

if __name__ == "__main__":
    register()

    bpy.ops.wm.myop('INVOKE_DEFAULT')

However, in my case what I see is this:

The fields for text and number do never show up. Anyone to tell me why?

replace = with : in the property definitions eg text: bpy.props.StringProperty(name= "Enter Text", default = "")

Using ':' definitely did the trick. Thanks so much!!
However, the guy in the video definitely used '=*, *not: ':'.
How did he manage? Something changed?

It changed when 2.80 released if I'm not mistaken, if you tutorial is more than 2 years old that's why :)


text:
Selecting a set of vertices and pressing F will not always create a face connecting to ALL selected vertices
Sorry if this is a stupid question. Running Blender 3.4.1 (same issue with experimental 3.6)
Assumption:
Selecting a set of vertices (more than 3) and pressing F should generally create a face. This is what I thought.
(Most often it works, but not always. This is the problem.)
Case:
Creating two cubes, placing them exactly on top of each other. Then dragging one cube a little along (say Y axis) to offset it. Then selecting both cubes and ctrl-J to join (I hope the picture indicates my intention.)
I have now created a mesh with intersecting faces, I know. The 3D print tool informs of this.
So I attempt to manually fix this by deleting each offending face and recreate it. Thus I start by removing one face (see figure) then selecting all 5 vertices involved and pressing F. A face appears, but alas, it does not connect to all five vertices, only four (will not stick to the one pointed to by the red arrow). This is what I do not understand.

If I remove all offending faces first and then recreate them, everything works fine. It seems that I cannot do it one by one face.
(And no, I have no vertices on top of each other.)
Could anyone shed som light on why this is so? Bug of feature? (Or just me failing to understand something obvious?)

Well, the fifth vertex the arrow is pointing at is not connected to the edge between the vertex to the left and right. The shortcut F is for the Fill tool, so it fills the hole between the four connected vertices. Although F can create edges between unconnected vertices, in this case it simply fills the hole and ignores the single vertex.
What you can do in this case to merge the two unconnected cube meshes: enable the Auto Merge function and also Split Edges & Faces in the Options.

If you now select all vertices, hit G to move and directly enter 0, Return to make sure they don't move at all (do not abort the movement with right-click!), the mesh gets split and merged where the vertices and edges are touching. If you now select the five vertices and hit F, the new face is connected to all of them.

I believed I would have to fix this face by face...  In fact - using Auto Merge and Split Edges & Faces - it appears I can select all and move by zero (as you suggested), and that will fix everything in one single step. Brilliant!
Thanks a lot!

@JoNoS In this case it does, sometimes when the edges are not so well aligned it might not work as good. Of course there's still a chance by changing the Threshold value to something higher, but you have keep in mind that when a vertex is too far away for example and you change the threshold to merge it nevertheless, this might result in changing the geometry quite a bit, since the parts will be merged at their median point and this can result in faces no longer being planar etc.