text:
Elegant way to animate a binary value?
Lately, I've been doing a lot of animation with binary values: things such as changing the visibility of an object, changing the value of a constraint from 0 to 1, etc. The way I'm doing this currently is by, on one frame, keyframing it, then on the next frame, changing the value and adding a new keyframe. But, since there aren't actually any frames in between the keyframes, this seems like a weird way to do it. Is there any better way? Or is this how it's done? Are there any add-ons that make this more elegant?

You don't have to put a "holding" keyframe before each one.  Binary values will only change on the keyframe, not before it.

If you want to alternate a value between every other frame use the Math node and select Modulo with "2" as the second value... ;-)

@Samoth just in case I want to give anybody who watches my animation a seizure?

When keyframing binary values there is no need to include a "holding" keyframe as you have described before each change.  Blender knows to only switch the value at the keyframe since there is no way to interpolate a boolean.

In the above example I have visibility keyframes at frames 1, 15, 30, and 40.  Notice that I don't need keyframes at frames 14, 29, and 39 to make sure that it stays constant up until those frames.

I thought this whole time that it would "interpolate" it the best it could and change the value halfway between the last keyframe! I guess blender is smart...like usual. Thanks!

@markasoftware TBH, I did too until you asked and I tried it out!


text:
What's the most elegant way to cut shapes out of a mesh?
I'm trying to cut shapes out of a mesh, but I'm having trouble doing it, or at least doing it properly. I'm currently trying to model this flashlight:
The part I'm specifically having trouble with is the part near the green light, where there are cutouts from the cylinder. I'm not sure how to do those properly. The thing that first comes to mind is creating another object, using an array to copy it around the cylinder, and then using a boolean modifier in difference mode. This works, but it creates an ugly mesh, and it also doesn't seem very flexible, for when you need to do more complex stuff, and working on a mesh that indirectly affects the mesh you're actually trying to affect seems a bit weird. I've also tried doing things like knife project, but it's geometry isn't any better.
So, basically, what I'm asking is: Is there any way for me to do this while keeping my geometry clean?

Yes your initial array method will work. Here is the model of a circle. I have extruded it into a cylinder and delete the faces I don't need and apply an array modifier to get the below mesh. I have intentionally left out the last array object. With the mid-edge of the original mesh selected ...

Hit CtrlB to bevel the edge and you should achieve this...

Next with K I have added a cut using knife tool between the bevel like this ...

Now I will extrude downwards with the E to make a depth for the groove...

Before finalising the cut I will add a subdiv modifier. And the modifier stack looks like below. The object offset is an empty with a 22.5 degree rotation to create the array copies, rotating around the mesh's origin point.

Finalising those loop cuts in 4 locations shown here.
And now this is the mesh I have. From here on out you can either bake the normals of the highres mesh onto a low res mesh. Or clean up the highres mesh so that it's not too high a poly for efficiency sake. Hope it helps

And here's the Blend file for your reference.

Sorry for the late(ish) response. This fixes the specific issue that I was having for modeling this specific thing, but I was hoping for a more general solution...take an upvote

This is generally how it's done.

Well, what about a situation where the shape I'm cutting out isn't a beveled line? Would I just try to deform the mesh and then "intrude" it the same way you did here?

Isn't a beveled line? What do you mean isn't a beveled line a more descriptive image may help . My explaination works for the part you are trying to model. One problem per question is the goal here. If it's another question that is different from the original question please post a new question for the new problem you are facing currently.

How exactly did you do the array? Did you use an empty, or is there some way to do it without that?

As described I used an empty.

source: Stack Exchange

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

sort: votes


text:
Bulk renaming armature bones after already creating them?
I'm trying to create an animation rig with quite a few armature bones. I'm modeling a bug, which has a total of 14 legs, and each one of those legs has 5 armature bones. The legs are identical, except they are in different positions with different rotations, so to set up the armatures I simply created an armature for one leg and duplicated it to the other legs, rotating and repositioning it as needed. However, I named the front legs FrontLeg.L and FrontLeg.R. The other legs, since they're just duplicated, are, for example, FrontLeg.R.007, etc etc. I can easily rename the parent bone for each leg, but this becomes tedious very quickly to do this for all of the children as well.
Is there any easy way for me to rename the parent bone to, for example, 2ndFrontLeg.L and have all of the children automatically be assigned names 2ndFrontLeg.L.001, 2ndFrontLeg.L.002, etc, after they've already been created? I'm completely ok with using addons as well

I would simplify your model a bit (animating 4 legs is difficult enough, maybe 6 or 8 is reasonable if you have a bug or a spider but 14?) leaving less bones to name and then you could use the flip names option which flips names of half of your bones. But that does not answer your question.

there's a new answer! This feature is now built in Blender, just pick Edit → Batch Rename... from the menu.
Official docs: https://docs.blender.org/manual/en/latest/files/blend/rename.html

Open a text editor in Blender and paste the code below there.
Replace the text in "original" and "replacement" as needed.
Go to pose mode and select the parent of the new chain.
Press "Run Script" in the text editor.

Here's the code:
import bpy
original    = "FrontLeg"    # Original name that was duplicated to generate all legs
replacement = "2ndFrontLeg" # The new name you want for this particular leg's bone chain

parent = bpy.context.active_pose_bone
for b in [ parent ] + parent.children_recursive:
    b.name = replacement

Looks great! However, there's one small change to it that I would like: could you make it automatically change the number (e.g: .007) at the end of the name of each bone? So that it's like: 2ndFrontLeg.L.001, 2ndFrontLeg.L.002, etc instead of just keeping the digits, which often ends up with things like: 2ndFrontLeg.L.004, 2ndFrontLeg.002`, etc etc, not in order

@Markasoftware, updated the script to work as requested.

I think your original answer would have been more useful in my test case. How would you simply do a find and replace in all bones? @TLousky

You could always try to: for b in [ parent ] + parent.children_recursive: b.name = b.name.replace('something','somethingelse')

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 to execute python code after each stroke painted in image editor?
Is there any possibility for that? Modal operator seems to be not suitable for that

You can achieve this by using a scene update handler that monitors the state of the active image in the image editor.
For this technique to work you need to:

Create or open an image in the image editor window on the active screen.
Save your image to an external file once.
Also: the script will save any change to file immediately. If you don't care about that, this solution can work for you.

The example below illustrates how you can set a new random paintbrush color after every stroke.

import bpy, random

def run_if_img_changed( scene ):
    im = None
    # References the active image in the image editor
    for a in bpy.context.screen.areas:
        if a.type == 'IMAGE_EDITOR':
            for s in a.spaces:
                if s.type == 'IMAGE_EDITOR':
                    im = s.image
                    break

    if im and im.is_dirty:
        ## Replace the bit in this if clause with your code
        print( "Image changed!" )

        # Set paintbrush to random color
        bpy.data.brushes['TexDraw'].color =  [ random.random() for c in 'rgb' ]

        ## End of replaceable sample code

        # Save image so it will no longer be dirty
        im.save() # This line will crash the script if you haven't saved the image to a file yet

bpy.app.handlers.scene_update_post.append( run_if_img_changed )

Getting image by name is cumbersome.
(im = bpy.data.images['Untitled.001'])
Is there a way to obtain currently editing image?

@wilddev, You can reference any image there, this is simply the example I used above. This is the name of your image, which you can set in the image editor.

handler function receives just a scene, but not a context of image editor. I don't know how to receive such a context inside a handler function =(

@wilddev, updated to read image from image editor. Lemme know if works as expected.


text:
How to sample Image A with coordinates from image B, using compositing editor nodes?
I need an operation, mathematically written as
ImgOut[x,y] = A[ B[x,y].red , B[x,y].green ]
Is it possible to implement this with blender compositing editor nodes?

If the coords come from normals(?) you could decompose them via Converter nodes Seperate RGB?

@3pointedit They are actually already decomposed. How can this help?

Its not clear how you want to use the product as that may inform the type of nodes you need to use. If you want a mixed color result or a value result on seperate channels...

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


text:
Blender 2.80 displacement texture bug(?)
I thought I better seek help from others to make sure I'm not making a user error here before placing a bug report.
In using greyscale displacement maps (textures) in blender 2.80 I've noticed something seems to be going wrong with the way 2.80 reads the information in the image files.
As you can see image the comparisons below, 2.80 using the same 16bit tif displacement image results in what looks similar to bitdepth gradation banding lines/artefacts. 2.79 renders the displacement smoothly whereas 2.80 no matter what I do always has those ugly ridges/lines.
A bit about the setup:
1 plane,
gloss shader (nothing plugged into it, roughness at 0)
world hdri from HDRIhaven "greenwich park" 2k
displacement map from poliigon freebies "TilesRectangularMirrorGray001"
displacement map plugged straight into displacement output
(note: also tried in blender 2.80 plugging disp map into 'displacement' node then into displacement output, no improvement)
(note: tried both color and non-color options for image-file node, no help)
material set to "bump only" in 2.80
(note: also tried displacement+bump , displacement only in 2.80, including turning on experimental adaptive subivision, did not fix)

Note: 8bit 2.80 vs 2.79 appears similar in level of banding

It looks like you are using true displacement is 2.8 (due to what looks like an underlying mesh having been messed with), does applying a subdivide to the model change anything?

Unfortunately not, the effect is still present with high subdivisions + displacement & bump. The problem seems to be in the way 2.80 is using the 'bump' portion

I had this issue several times too, I figured out that it happens due to compression of the texture as many values will be set to the same to reduce space.


text:
Animated Color Ramp Not Showing in Viewport
I'm an experienced user and have stumbled upon an issue that I can't wrap my head around. I have a very simple node setup. A base material, to a color ramp to an output.

The position of white marker is animated using a driver that reads info from a baked f-curve. I can confirm that driver works properly and position value changes according to my curve.
My problem is that the method works properly if rendered, however for my game I need to use GLSL/Viewport and consequently what I see in viewport is what I get but the changes do not show in viewport. Changes only appear after I click on the marker in the color ramp.
Basically viewport updates only if colorramp marker is clicked by the user.
I was wondering if there is a workaround/script for this, that forces the viewport to update/refresh properly from frame to frame.
Thank you all in advance :)

Welcome to the site :) You might try using the experimental new depsgraph and see if that helps at all

In this forum https://blenderartists.org/forum/showthread.php?399511-Force-material-update-OpenGL-render-active-viewport you can found a script that helps to solve this problem. :D


text:
Increase Lines Width in Viewport
I know there is an option available in preferences to increase "Width Outline". However this only applies to active object.
Is there anyway, through code manipulation possibly, to increase Line Width for all empties, latices, and objects in viewport? I believe the default value is 1px.

@ScottMilner perhaps that one is a dupe of this one.

@batFINGER Well, that one is more recent and has up-to-date information, so according to meta, this one should be closed.

@ScottMilner cheers for the link which clears it up.  Twas a bit confusing, re "this question has been asked before in the future."/  .. hit the two in a row in review was like a cyclic closure... chose the wrong one. 8^(

The 'width outline' option found in themes adjusts the width of the outline drawn around selected objects. There is no option to adjust the width of lines when drawing objects in the 3dview. There is a pixel mode setting that will allow lines in the 3dview (and all other interface items) to be drawn at double width, this is intended for the Apple's retina displays. You may also want to adjust the DPI setting to control the interface outside the 3dview.
The other option involves altering blenders source code. I don't think there is one location to adjust the line size, you may have to adjust the drawing of each object type, you could setup a preference that is then used in each place. The code you would need to change should be contained within editors/space_view3d/.


text:
Fully defined objects - smart dimension (like solidworks)
I am coming from solidworks, and what I am looking for is something similar to the "smart dimension" tool. In blender I can control the dimensions by extruding, grabbing, and scaling by defined amounts, but if I want to change that dimension later, other dimensions are not locked. Basically, I have to have already designed the model in its entirety on paper before I begin. Changes to early dimensions force starting from scratch or scrapping the "fully defined" nature of the model.
I learned these techniques from Robert Burke's 2007 on using precesion modeling with blender. book:http://homepage.ntlworld.com/r.burke2/precision_modelling1.html
I am hoping that there might be a new tool or plugin that allows for a fully defined workflow?

Maybe you could illustrate your question with some images? What do you mean with "dimensions"? The edge lenght info in edit mode?


text:
Can i use scenes in VSE to group video tracks?
I am doing my first steps in Blender's VSE and i am trying to familiarise myself with the workflow.
I am trying to edit several video clips to produce a single output video and i would like to somehow group some of these clips together to apply common color correction, time manipulation etc and to unclutter the main timeline. For this i created a new scene (let's say scene2) by either Copy Settings or Full Copy, moved some of the clips from my main scene (let's say scene1) to it and then on the main scene i did Add > Scene... > Scene2. When i try to playback on the main timeline though, on the part of the Scene2 i either get a blank screen or a square 3D object.
What am i doing wrong? Is there a better way to achieve the same result?

If you add scene2, blender does not import the Video sequence but the 3D animation, hence the cube. You could export scene 2 in a movieclip and then import it in scene 1
You could group the clips (in scene1) by selecting the strips and then CTRL+G. ( ALT+G to ungroup)

How do you export the scene to a movieclip, by rendering to a new video? Isn't it too much of a hassle to do this every time? What if you would like to change something in a later phase, like the position or the color settings, you have to do it all over again?

MetaStrips look more promising though. Thanks!

An other option:
You could also download the blender gooseberry branch. https://builder.blender.org/download/
There you can make different scenes using the video sequence editor. Then you can work the way you discribed above. You can import the one scene into the other. Then if you click on the scene you imported in the sequence editor, you will see a cube, but in the properties panel under the tab scene you can check use sequence. and then you will see the movie files.

Thanks for letting me know this, i will download the gooseberry branch to try it. Is it stable for everyday use? Also, is there some summary of all the changes that are part of the branch so far?

@charis, you don't need the Gooseberry Branch any more - it's now supported in 2.77.


text:
Animation with text
I have animation with 3d models and text on same layer. It is possible to move text from x layer to layer which is rendering for a limited time? Rendering process take longer and I don't need text all the time.
Regards

Try using RenderLayers

Text is in this scenario no different than any other kind of Object (Mesh, Curve..). You can keyframe the hide render property. (think of that as the 'hide_from_render' property)

Toggle the camera icon on / off by clicking it. If you see the camera that means 'this object will be rendered'. If you see a circle covering the camera icon it means that Object will be ignored in the render.

Press I While over that icon to place a Key frame for the state you want it in.
Don't worry if you see the object in 3d viewport, it won't render unless the camera icon shows.
If you want to hide the object from view, place keyframes for the Eye icon. (But that's extra work if you don't need to)

It isn't possible to keyframe the layer the Object appears on.


text:
Random crash while rendering
I'm using Blender 2.75, 64 bits with two GTX-980.
I work with a script that render without issues with low resolutions (up to 480p). However, when I try to render with higher resolution the rendering process crash randomly with Error: EXCEPTION_ACCESS_VIOLATION. By randomly, I mean that sometimes it renders up to 10 images before crashing, and sometimes it crashes at the first one.
I've put two logs at the end (one successful and one failed) of the same frame being rendered at 720p.
How can I identify the source of this issue? I think that it has to do with some  performance preset, but I don't know what to look for.
Rendering successful
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Remaining:00:02.05 | Mem:1331.54M, Peak:1331.54M | Scene, RenderLayer | Path Tracing Tile 9/9
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Mem:1327.59M, Peak:1331.54M | Scene, RenderLayer | Finished
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Compositing
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Compositing | Determining resolution
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Compositing | Initializing execution
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 2-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 2-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 3-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 4-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 5-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 6-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M)
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 9-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 9-9
| Compositing | Tile 9-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Deinitializing execution
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) Sce: Scene Ve:0 Fa:0 La:0
Saved: D:\software\3dgenerator_blender\renderWrap\F_01_Original\Apt\lightNone\noPose\8febee5b-daa2-40de-8aac-754aeb1a486e.png
Time: 00:12.80 (Saving: 00:00.16)

Rendering failed
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Remaining:00:02.11 | Mem:1331.54M, Peak:1331.54M | Scene, RenderLayer | Path Tracing Tile 9/9
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Mem:1327.59M, Peak:1331.54M | Scene, RenderLayer | Finished
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Compositing
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Compositing | Determining resolution
Fra:244 Mem:209.85M (0.00M, Peak 404.40M) | Compositing | Initializing execution
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 1-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 2-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 5-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M)
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) | Compositing | Tile 9-9
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) Sce:  Ve:0 Fa:0 La:0
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) Sce:  Ve:0 Fa:0 La:0
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) Sce:  Ve:0 Fa:0 La:0
Fra:244 Mem:219.73M (0.00M, Peak 404.40M) Sce:  Ve:0 Fa:0 La:0
Error: EXCEPTION_ACCESS_VIOLATION

I had the same problem and I think it's a threading issue.
(AFAIK the render engines are written in C++, so it's not surprising considering threading and memory management in C++ are a PITA).
You should keep your CPU levels to below around 50% for the blender-app.exe process.
In my case, if I bring down the threads to a max of 4, the scripts run without problems (still using all cores).
Slows it down somewhat, but at least it keeps running...
Something like this in a script file:
cd C:\Program Files\Blender Foundation\Blender
blender -b "your_blender_file.blend" -t 4 -a
pause

Hope it works for you.


text:
Blender does not utilize full amount of VRAM
When trying to render my scene with my GTX 970 and cycles I get a cuda error saying that I was out of memory. However according to gpu-z I only got up to using 3228MB of VRAM, and according to blender my scene was using a little over 2GB, somewhere in the 2200MB range. Is there a work around, or a know reason for this?

Unless you have multiple graphics cards you are unlikely to be able to max out the memory use.  Some of the memory will be used by other processes and windows.  I've found it is always worth closing all other windows and any other unnecessary processes when I'm close to the limit.  They all use RAM which could affect your render but they all will likely have staked a claim on some VRAM too.  I don't know whether minimising the Blender program windows makes any difference but I do it anyway.  If you are on Windows I've also found that switching themes can help.  Current Windows versions and their UI effects are not a particularly efficient users of VRAM so dropping back to the Classic theme will probably help.  I've also read that changing font size to normal and switching off clear type and anti-aliasing can help although I've no evidence to support that.

I've forced every app using my discrete GPU to use the iGPU, including Windows system apps.  My GPU now shows 25% VRAM is free (before there was only ~3% free), yet Blender still refuses to use it.  I even shut down the Blender UI and rendered from the command line with all UI apps shut down, same thing: 25% unused VRAM.  Blender will even swap out whatever it is using to system RAM and pull in more to the VRAM, killing my render time (12 hours vs 18 minutes).  The whole time there is 20%-25% VRAM sitting idle according to Task Manager, Open Hardware Monitor, and AIDA64.  No way around it.

I think Windows may keep some in reserve, because if I open an app that can use the extra VRAM, the usage will spike to 95-97% while the app is open.  Maybe Linux can allow full VRAM usage for a single app...


text:
How to create UV and texture for egg shaped model
I've searched and toyed with this for quite some time. I have a penguin who's body is egg shaped and I'm trying to do the UV and texture for it. If I use projection from view then it comes out nearly OK except for a few areas (see image). The problem is that it seems no matter how I change the UV's vertices I can't fix the offending areas.
I'm hoping someone can help.
Thanks!

Front view looks fine

How many subsurf levels have you set? Try to increase susurf level.

Thanks for the suggestion. I don't want to use subsurf because it is an asset for a game.

Try to reproject your texture upon a catmull-clark subdivided version of the mesh with the subdivide UVs option disabled.
This way you should be able to have more faces (and so a higher projecting accuracy), while maintaining the same UV islands.
Before:

After:

In my testfile this process was able to mitigate the effect of the distortion.
Once reprojected the texture, you can obiuvsly delete the modifier and keep your vertex count untouched.

thanks, but that's really not making much of a difference. That edge should continuously bow out. The white are is also mostly egg-shaped. I've tried up to 6 subdivisions. Any further and Blender is unusable.This is way harder to do than I expected :(

Make a higher subsurfed model and bake the normals onto the low-poly model. That should smooth out those distortions for you and keep your vertex budget level.


text:
Texture changes between object and edit mode
Me again! I've been working on the texture for a model, but when I switched to edit mode to take a look at it, it got totally changed up. Does anyone know why this is happening? (And, if I export the model, which version will it have?)

My .blend file is here, if it helps!
http://www.pasteall.org/blend/38433

What modifiers do you have? Some may be disabled in Edit mode

I don't have any modifiers.

The model have a series of extra faces that you can see in object mode. Clean the extra faces on the mouth zone.

Cleaning up the extra faces fixed it, thanks! That said, I'm still really curious about why it did it in the first place.


text:
Node editor is very slow when editing video
I am using Blender to produce a 30 min. web cast weekly. Each episode includes multiple videos and still images that I composite primarily with the alpha-over node. I also use green screen, so there are a couple of keying nodes at play. This thirty min. web casts takes two full days to render. I have a top of the line AMD 8 core processor running with 8GB of ram and an 8gb video card. Can anyone suggest hardware upgrades or setting tweaks that may speed things up a bit?

A screenshot of your composite nodes would help. Do you include any 3d elements or just use blender's compositor? What render settings do you have. Are the source videos the same resolution as the final output?


text:
Save a soft body animation
i'm pretty new to blender so i'd like to know if it's possible to save an animation of a ball bouncing on a plane made with the soft body modifier. when save the animation in nla editor the ball remain still at the origin.
And if i press apply modifier it freeze the ball in just one position. thank you for the attention, goodbye

You mean caching?

Maybe the OP would like to record the soft body resulting behaviour as animation & deform, in a way similar to what is possible in the game engine, to f-curves so to be able to reuse (as is or after editing) that simulated behaviour?

The "blender game" mode (game engine) can record animations paths for objects, even as soft bodies, but it can be a bit different from the standard "soft bodies" you get in "blender render" mode.
A basic example:

open a standard blend file (cube)
change to "blender game" mode (pick it form the upper header list)
the menu at the left of the engine selection (which you just selected) now has a "game" item: expand it and activate the "record animation" flag
now select the cube
on the right object panels, go to the physics (bouncing ball icon)
choose "soft bodies" as physics type
press P
the cube falls
when the cube has fallen enough, stop the "game", pressing ESC
the cube is back to start position
now switch the viewport to f-curve (graph editor)
you see the f-curve recorded for the fallen cube:
now change the mode to "blender render" or "cycles render" and use that recorded animation as you wish...

you may have to experiment a bit to get desired behaviour for the soft body and other objects in the scene, but the "blender game" will record everything for you!
manual reference: http://www.blender.org/manual/game_engine/physics/introduction.html#recording-to-keyframes


text:
Reverse pose bone inherit scale via python
I have some animation fcurve data provided for the case of inherit scale unchecked for pose bones.
Example: Bone03 is a child of Bone02. Inherit scale is unchecked for Bone03. At frame 1, Bone02 is not scaled (i.e. Sx, Sy, Sz = 1.0000). At frame 30, Bone02 is scaled on Y with a factor of 2 (Sy = 2.0000; Sx, Sz = 1.0000).
Since inherit scale is not checked for Bone03, it is not affected by it's parent scaling at frame 30. This is the intended result.
Problem: I need to import the blend file in Jmonkey which scales the child regardless of it's setting in Blender. The animation hence appears scaled wrongly in Jmonkey. Basically, I need to check inherit scale on the child bone and then reverse the inherit scale operation on the child bone via a python script in Blender before loading it in Jmonkey.
I've tried to copy the matrix of the child pose bone (before setting use_inherit_scale to True on the child edit bone) and then reassign it to the child pose bone. The result looks like it ignores the reassign of the original matrix and scales the child anyway. Here's the code:
import bpy

obj = bpy.context.object
scene = bpy.context.scene
bpy.ops.object.mode_set(mode='POSE')
scene.frame_set(30.0)

pb = obj.pose.bones['Bone03']
start_matrix = pb.matrix.copy()  #copy the initial pose bone matrix
print(start_matrix)

bpy.ops.object.mode_set(mode='EDIT')
eb = obj.data.edit_bones['Bone03']
eb.use_inherit_scale = True

bpy.ops.object.mode_set(mode='POSE')
print(pb.matrix)
pb.matrix = start_matrix  #try to force reassign the start matrix

print(pb.matrix)

Here is a file with the problem demonstrated (I hope much clearer). When you open it the animation is correct (but with inherit scale unchecked). As soon as you run the script, Bone03 get's scaled wrongly.
The question: how can I force reassign the initial matrix to the pose bone, after programmatically setting use_inherit_scale = True on the edit bone?

Just a short draft. I might expand this answer later.
import bpy
from mathutils import Matrix, Vector

# for debugging purposes - visualize transforms
def create_empty(name, matrix):
    if name not in bpy.data.objects:
        empty = bpy.data.objects.new(name, None)
        scene.objects.link(empty)
    else:
        empty = bpy.data.objects[name]

    empty.empty_draw_type = "ARROWS"
    empty.empty_draw_size = 1.0
    empty.show_x_ray = True
    empty.show_name = True

    empty.matrix_basis = matrix

# ported from blenkernel/intern/armature.c to python
# --------------------------------------------------------------------
def get_mat_offs(bone):
    mat_offs = bone.matrix.to_4x4()
    mat_offs.translation = bone.head
    mat_offs.translation.y += bone.parent.length

    return mat_offs

def get_mat_rest(pose_bone, mat_pose_parent):
    bone = pose_bone.bone

    if pose_bone.parent:
        mat_offs = get_mat_offs(bone)

        # --------- rotscale
        if (not bone.use_inherit_rotation and
            not bone.use_inherit_scale):
            mat_rotscale = bone.parent.matrix_local * mat_offs

        elif not bone.use_inherit_rotation:
            mat_size = Matrix.Identity(4)
            for i in range(3):
                mat_size[i][i] = mat_pose_parent.col[i].magnitude
            mat_rotscale = mat_size * bone.parent.matrix_local * mat_offs

        elif not bone.use_inherit_scale:
            mat_rotscale = mat_pose_parent.normalized() * mat_offs

        else:
            mat_rotscale = mat_pose_parent * mat_offs

        # --------- location
        if not bone.use_local_location:
            mat_a = Matrix.Translation(
                mat_pose_parent * mat_offs.translation)

            mat_b = mat_pose_parent.copy()
            mat_b.translation = Vector()

            mat_loc = mat_a * mat_b

        elif (not bone.use_inherit_rotation or
              not bone.use_inherit_scale):
            mat_loc = mat_pose_parent * mat_offs

        else:
            mat_loc = mat_rotscale.copy()

    else:
        mat_rotscale = bone.matrix_local
        if not bone.use_local_location:
            mat_loc = Matrix.Translation(bone.matrix_local.translation)
        else:
            mat_loc = mat_rotscale.copy()

    return mat_rotscale, mat_loc

def get_mat_pose(pose_bone, mat_pose_parent=None, mat_basis=None):
    if pose_bone.parent and not mat_pose_parent:
        mat_pose_parent = pose_bone.parent.matrix
    if not mat_basis:
        mat_basis = pose_bone.matrix_basis

    mat_rotscale, mat_loc = get_mat_rest(pose_bone, mat_pose_parent)
    mat_pose = mat_rotscale * mat_basis
    mat_pose.translation = mat_loc * mat_basis.translation

    return mat_pose
# --------------------------------------------------------------------

def adjust_matrix(pose_bone, mat_parent_old, mat_parent_new, preview=True):
    mat_pose_old = get_mat_pose(pose_bone, mat_parent_old)
    mat_rotscale_old, mat_loc_old = get_mat_rest(pose_bone, mat_parent_old)
    pose_bone.bone.use_inherit_scale = True
    mat_rotscale_new, mat_loc_new = get_mat_rest(pose_bone, mat_parent_new)

    mat_fix_rotscale = mat_rotscale_new.inverted() * mat_rotscale_old
    mat_fix_loc = mat_loc_new.inverted() * mat_loc_old

    mat_basis_old = pose_bone.matrix_basis
    mat_basis_new = mat_fix_rotscale * mat_basis_old
    mat_basis_new.translation = mat_fix_loc * mat_basis_old.translation

    mat_pose_new = get_mat_pose(
        pose_bone,
        mat_parent_new,
        mat_basis_new)

    if preview:
        create_empty(pose_bone.name, mat_pose_new)
    else:
        pose_bone.matrix_basis = mat_basis_new

    return mat_pose_old, mat_pose_new

def apply_change(parent, mat_parent_old, mat_parent_new):
    for child in parent.children:
        mat_old, mat_new = adjust_matrix(
            child,
            mat_parent_old,
            mat_parent_new,
            preview=True
        )
        apply_change(child, mat_old, mat_new)

if __name__ == "__main__":
    scene = bpy.context.scene
    obj = bpy.data.objects['Armature']
    roots = [bone for bone in obj.pose.bones if not bone.parent]

    for root in roots:
        create_empty(root.name, root.matrix)
        apply_change(root, root.matrix, root.matrix)

    obj.update_tag({'DATA'})
    scene.update()

I've adapted the code to my file (Bone03 as Child and Bone02 as Parent), but the result is the same.

Updated the answer. Still a draft.

Another update. There seems to be a bug with assignments to matrix_basis and non-uniformly scaled bones. Somehow the rotation is not correctly extracted from the matrix.

Not a bug. The non-uniform scale causes deformations of the axes. To compensate for that the new matrix_basis may be non-orthogonal and can not be decomposed into loc, rot, scale. Thus you would have to export the matrices or adjust the scaling of the bones to uniform scaling.


text:
UV project from view: Can foreground items block projected image from proceeding?
Imagine a scene with a camera facing a background plane, with suzanne in between partially obscuring some of the background plane. I'd like to do a 'project from view' from the perspective of the camera and see a suzanne shaped hole in whatever image was projected onto the background.
Both meshes are a single object.
As I have my scene set up at the moment, the image being projected hits both the monkey and background.

I don't think so... But, you could try subtracting the Suzzane to the plane...


text:
How to have different origin for each object when separating a mesh by loose parts?
When applying separate by loose parts to a mesh, I end up with many objects, as expected. But they all share the same origin. If I move one object, they all follow.
I've tried unparenting, but there is no Parent relation between them. It's the first time I encounter this. Is this expected behavior or a bug? Or Am I doing something wrong?

When you switch back to Object Mode, you can set the 'Origin to Geometry'.
With all the objects still selected, int the 3D view port, Go to :
'Object' -> 'Transform' -> 'Origin to Geometry'
Then the origin will be centered on the meshes physical center.

Thx. Life saver. :)

@dval Thanks for a tip. I've been always placing the origins individually for each separated object. Haven't got idea, that such helpful option exists :).

@PaulGonet You're welcome. Someone may correct me... I think since 2.6x most editing options can now be applied to multiple objects. This is a 'newer' feature that hasn't always been available.


text:
How to break/cut a circle in geometry nodes
I have a circle and would like to cut/break it to get a start-end-point curve represeting the circle before.
Attention: I don't want to create a circle using a line! See above: I already have a circle and want to interrupt it.
Any ideas, how to do this?
When I use the curve ID and delete points, then the circle stays connected. But  this is not what I want.
What I have:

That looks like a Curve Primitive > Arc?

I'm not sure how feasible it is in your setup, but you could do a quick Curve to Mesh before the Delete Geometry and then a Mesh to Curve again after - this will interrupt the cyclical tendency of the spline and "replace" it already disconnected:

This perfect! Thank you Chris! I was about to get the solution myself, but didn't know the mesh trick...


text:
Geometry Nodes: Dynamic Bounding Boxes for Collection Instances?
I need "dynamic" bounding boxes for Collection instances. I need the changing size of the bounding box in the world while/if the object rotates. This is working well for single Objects, but not for Collection Instances.
How to achieve this, please?
May I have to rotate the collection object points?
See my screenshot:

I've found the answer. I have to realize all collection instances first, before rotating them...

Oh, you figured it out. Writing my answer took too long :D

The thing is, Blender treats the geometry from an Object Info node differently than the one from a Collection Info node - because you can decide if multiple objects in a collection should be manipulated together or separately. The Object Info node's Geometry output gives a mesh, while the Collection Info outputs instances by default.
So to make it work for the Collection Info node you have to use a Realize Instances node before the Transform node:

By the way, if the way the Transform on the Collection Info node works would have been the desired result, you could achieve that for the Object Info node as well if you go the opposite way, make an instance of the object. In this case you comfortably have a checkbox As Instance on the node:


text:
Geometry Nodes: Scale objects in collection based on curve segments
I've a question based on this thread: Geometry Nodes: How to scale and rotate instances based on segment length
I would like to do the same like in the mentioned thread, but instead of just scaling a single object. I would like to distribute and scale the collection content. I know how to distribute the collection content and know how to rotate it into the right direction to get this kind of fence. But I get crazy since hours because I don't know how to scale the individual objects inside my collection to get a nice result.
Here's a prepared file with a collection:

This is the current status. I would like to replace all the objects in the fence with the content of the collection. My problem are the different scales of the fence parts.

You have already calculated the length of the individual segments correctly.
Answered here: How to scale and rotate instances based on segment length?
Also, in this context, we already had the question of how to find out the length of an object within a collection.
Answered here: How to get a field with individual object sizes inside a collection?
This question is primarily about how these individual mechanisms can be combined into one, and you can solve this as follows:

Here, I first capture an integer value at each of the points where objects are to be instantiated. This is important because we need exactly the same value when instantiating to be able to read the corresponding object and its dimensions from the collection.
You can also use any other values here, so it doesn't have to happen via the Random Value node. If the node Instance on Points receives no input as Instance Index, the instances are simply numbered (i.e.: $0,1,2,0,1,2,...$), which is why you can actually also use this number sequence to query the dimensions of the individual instances (Tip: Math Node Modulo).
To calculate the dimensions, I use in this example as I said the answer from your previous question, which looks (slightly modified) like this here:

You can of course evaluate the lengths of the other axes in a similar way. The details of this have been discussed in detail in here.
This length can now be transferred comfortably with exactly this previously created integer value during instantiation.
(Blender 3.1+)


text:
How to seperate clothing from the rest of the model
Im very new to blender and am wondering whether there are any methods to seperate clothing (hair(particles), boots, gloves) from the rest of the model  as I am going to be animating my character and having him wearing a ghillie suit will make animating difficult.

Particles can't really be separate unless they are objects, whick you can apply. As for the rest just enter edit mode and press P to separate either one by one as desired or P > Loose Parts to automatically break your object into all separate chunks

It depends how they are attached. Upload the .blend?

I havent actually added the ghillie suit,boots,gloves etc. to the character yet. It is simply just a rigged makehuman character at the moment. I had to ask the question like this so that the question wouldn't be taken down for being subjective. I asked because I would like to know in advance. What Daurte Farrajoa Ramos said makes alot of sense and is the path I will go down.

There are two fundamental principles to 3D modeling. One is "don't model what can't be seen"; the other is "any part which needs to move independently of any other part needs to be a separate object  from every other part to which it moves in relation". Following these principles, your character will consist of multiple objects: a head, a separate jaw, likely separate eyes, a cap, a pair of hands, a pair of arms, a pair of feet, a pair of legs, and two or more objects  which, combined, make up the torso.
In fact, you will likely have multiple feet: perhaps a pair of combat boots, a pair of parade dress, and a pair of ghillie boots. You won't usually have bot bare feet and shod feet, because you can't usually see the feet through the shoes.


text:
Smoke-like transparent material
How do I make a material that looks like the surface surrounding the helical objects in the image below in Cycles? It looks like smoke on the edges, but is transparent in the middle. It is important that the helical object doesn`t get distorted like if it was placed inside a glass bubble. This image was made in Cinema4D.

Original image link

Mix with Fresnel
To make an undistorted see-through effect, I'll suggets to use a Transparent shader. It will basically just make the surface transparent, without any addictional effect.
The edges looks bright despite the very dim lighting, so I'll use an Emission shader to give them some light to show indipendenly from scene's lighting.
In order to make the faces whose normal are pointing toward the camera transparent, I would suggest to use a Fresnel node in conjunction with a Mix shader node. As said in the manual's page:

The resulting weight [of the Fresnel node] can be used for layering shaders with the Mix Shader node. It is dependent on the angle between the surface normal and the viewing direction.

The math node is used for achieve a better control of the appearence.

This is the basics of the shader. The appeareance could be obiuvsly be improved by adding, for example, a different palette to the Emission shader with the help of the Fresnel node (again!).
Here's one of the many possible shader acting in a scene similar to the one pictured in the question:


text:
When moving character vertex stretches (After weighting)
I am new with Blender and I just finished doing my mesh and weighting it, it is for a project I have to submit by the end of the week and still have one more character left to create and I really don't know what's that and how to fix it. So everything looks normal, but after I created a root bone and moved the object away, two vertices stretch and don't move from their place. I really really hope there's a way to fix that without having to start over :( Please let me know asap if you have any idea. Thank you!
And if you know how to fix it, please give me detailed instructions, cause this is my first project on Blender. Please! Thanks!

Also, does any of you know what exactly should I rotate in order to get this leg in pose mode (and all other modes) in the right position? In Edit mode it looks okay.. but only there..

Try moving your character into that second position, where you can see which vertices are being left behind.  Then:

Select the mesh.  Get into Edit Mode.
Select the vertex (make sure Armature deform is enabled to be seen in Viewport)

Hit N in the Viewport, and scroll down to the Vertex Properties and make sure Deform is selected.

From there, look for the bone (probably the name of a Forearm bone) that should be influencing that vertex, but isn't, and set the weight to 1.  Make sure to hit Normalize when your done.

Thank you so much! I think that fixed it! May I maybe ask one more question? One of the legs it deformed, I tried rotating only this bone and also this one and the one below, so either i am doing sth wrong, or just rotating in the wrong place..
I will update the first post with another image

Glad it helped Ani.  The above method works if its just a few vertices here and there that aren't behaving.  If you're having a bunch of vertices not behaving as expected, I strongly suggest jumping into weight-painting mode.  My personal tip: always paint with 'Add' mode, and always normalize when done.  'Subtract' mode is the devil in weight painting.

Ok, regarding the leg: try zeroing out the rotations in pose mode.  You may have also have weights that aren't normalize, try selecting the bones and then normalize.  Beyond that, I would post a .blend to http://blend-exchange.giantcowfilms.com/ and link to it in a separate question.

@cegaton I understand that, but believe me, If it wasn't urgent, I wouldn't be asking about it. I hate posting questions like that and If I have enough time to research and try stuff, posting anything in Q&A websites like Stack, is the last thing I would do.. after I tried everything and really have no idea what's going on. Thanks for the tip, no worries, no more different questions here.

authors: евгений таранчук


text:
Box with double bevel edges
Im trying to model the box of the amp shown. I bevel the edges of the box

When I try to cut the hole, I bevel again the edges to get the round curve marked as "painfull zone". And no way to get a decent result.
When I smooth the box, geometry gets ugly. Tried applying some faces flat, but never get the correct result.
Here is my mesh:

Can somebody point me the right way to get the correct result?
Thank you so much in advance.

Probably the same as this http://blender.stackexchange.com/questions/52842/cant-bevel-an-ngon/52845#52845

Following the steps you suggested I can get a better result, but inner bevel of the box is not correct because curve is too big.
You have to consider that outer bevel is big, very rounded corners and they are near of inner corners that should have a very small bevel. That is because Im going crazy.

How did you create your outer bevel?

I added a cube --> edit mode --> selected all edges --> bevel. Im yet fighting with this. None of the posted solutions worked for a correct result.

Basically you want to ensure you have:

face loops flowing around the edge (illustrated in black)
the bevel edges you have created should be continued to flow across the surface (illustrated in red)
and you should replace the n-gons/tris with a 5-pole that is sufficiently far from the edge that any distortion will be minimal (illustrated in blue).

Sorry I don't have time to do a full tutorial.  Hopefully the image will give you some ideas.

Well I have used what you suggested with a more or less nice result for the covers of the corners. I had to model the box of the amp with the errors. Fortunely they have been covered.
But dont know if my method was correct. I had to cut loops by hand. And I think they will be noticed in the final render.
If you know an automated method to do loops as you shown, will be helpfull.
Thanks.


text:
Extrude along normals problem
Im trying to extrude this edges along normals over Z axis. Median point selected and Z is pointing correctly as shown in this picture.

But as soon as I press E to extrude and Z Z to use normals restriction, normals Z axis changes to this:

So extrusion is not what expected.
What am I missing? Thanks in advance.

Just press E, it should automatically lock to gimbal Z axis.

Select the edge loop around the hole and fill it with F. Set the transformation orientation type to Normal and then extrude.

Answer by Paul Gonet in the comments. Thank you so much.
Select the edge loop around the hole and fill it with F. Set the transformation orientation type to Normal and then extrude. – Paul Gonet
That worked as expected. Thanks a lot, Paul Gonet.

Although I'm sure Paul doesn't mind, the general etiquette would be to allow Paul a chance to write up the answer himself (and get any points associated with the answer being accepted/upvoted).

Yes. I will wait for Paul to write the answer. And mark his answer as the solution.
I thought I could mark his comment but I was wrong.
So I will wait for his answer.

You have already written an answer, which you can accept, I was just mentioning it for in future.

@dogday feel free to accept you answer :)


text:
How can I find the selected metaball elements in Edit mode with Python?
If you have an active object you can find the currently selected sub elements; e. g. in an active mesh you can find the selected vertices while looping over them and check the property bpy.context.active_object.data.vertices[i].select.
In an active armature you can achieve the same with bpy.context.active_object.data.bones[i].select_head (or select_tail).
But for metaballs I cannot find a property
bpy.context.active_object.data.elements[i].select or something like that. How can I retrieve the selected element(s) in a metaball object?
Background: In Edit mode you can add additional metaballs to a metaball object. I want to move the selected elements via Python.

Well, beats me. Is it possible it isn't exposed in the python API?

That one's not easy. I checked the Outliner to get the path to the elements:

I haven't been able to find the full selection yet, but the active ball can be found and moved:
import bpy
bpy.data.metaballs["Mball"].elements[2].co.x += 0.1
bpy.context.active_object.data.elements.active.co.x += 0.1
bpy.data.metaballs["Mball"].elements.active.co.x += 0.1

I hope somebody can prove me wrong but it might not be exposed to the API. Metaballs don't get a lot of limelight. In which case it would be worth to find the right dev to implement it.
Only workaround I can see is to keep the metaballs separated, select them in object mode, manipulate them there(they still merge anyway) and use that selection and join them afterwards. Depends on how many you need to move.

The "active" command delivers only the first selected metaball in the list. Better than nothing, but the "grab" command is able to move all selected ones, even in edit mode. I hoped to have the same functionality in the Python API; seems I have to do without it ...

@frisee I fully agree it's not remotely ideal. But I see only two other choices: bribe a dev or learn to change the code and commit it.


text:
Align view in quadview mode
I want to align the 3D view like the menu item "View/Align View/Center Cursor and View All" does it, but with Python. If in "Scripting" layout this works fine with the following code:
import bpy
override = {}
override['window'] = bpy.context.window
override['scene' ] = bpy.context.scene
override['screen'] = bpy.context.screen
override['area'  ] = bpy.context.screen.areas[2]
override['region'] = bpy.context.screen.areas[2].regions[4]
bpy.ops.view3d.view_all(override, center = True)

But it does not work if the view is in quadview mode; only the view in the lower left corner is aligned then.
I tried to replace the region line by
override['region'] = bpy.context.screen.areas[2].space.active.region_quadviews[x]

(x = 0..3) but this fails because the region_quadviews[x] are of type RegionView3D instead of type Region. Is it possible to get four regions of type Region of a quadview?
Strange: Clicking on the menu item shows the same behaviour, i. e. only the lower left view is aligned; but using the shortcut (Shift-C) aligns the view the mousepointer is over - this is my goal.

import bpy
override = {}
override['window'] = bpy.context.window
override['scene' ] = bpy.context.scene
override['screen'] = bpy.context.screen
override['area'  ] = bpy.context.screen.areas[2]

for region in [r for r in bpy.context.screen.areas[2].regions if r.type == 'WINDOW']:
    override['region'] = region
    bpy.ops.view3d.view_all(override, center=True)

Thanks, it works. I combined this solution with this one link and can align the quadview quarter where the mousepointer is over. Perfect.

I want to solve same problem, but for Node Editor. "bpy.ops.node.view_all(override)" is not working


text:
Getting the active region
How can I get the active region (i. e. the region the mouse pointer is over and keystrokes are sent to) with the Python API?
Background:
I want to manipulate the view_matrix of the region the mouse pointer is over. In the "Scripting" screen I can get the matrix with
bpy.data.window_managers[0].windows[0].screen.areas[2].spaces[0].region_3d.view_matrix

or with
bpy.data.window_managers[0].windows[0].screen.areas[2].spaces[0].region_quadviews[x].view_matrix

if the SpaceView3D is in quad view mode. bpy.context does not help: My script runs in a timer started from the text editor, and its context is always "Scripting" therefore.
Getting the active region seemed to be a simple, common task to me, but I am stuck here. May be I am looking in the documentation's wrong area ...

Usually you call an operator and the context passed to the operator's execute or invoke method provides information about the current area, space, region etc... ->context

bpy.context.space_data is the current space, if you need a certain one, iterate over all areas in the current screen and test for the .type:
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        area.spaces.active.region_3d.view_matrix
        # you may want to break here

To figure out which region / quadview the mouse is over in a modal operator, compare the mouse coordinates with the region rectangle:
import bpy
import math

def get_view_orientation(space, view):

    if view.view_perspective == 'CAMERA':
        if space.camera.type == 'CAMERA':
            view_orientation = "Camera " + space.camera.data.type.capitalize()
        else:
            view_orientation = "Object as Camera"

    else:
        r = lambda x: round(x, 2)
        view_rot = view.view_matrix.to_euler()

        orientation_dict = {(0.0, 0.0, 0.0) : 'TOP',
                            (r(math.pi), 0.0, 0.0) : 'BOTTOM',
                            (r(-math.pi/2), 0.0, 0.0) : 'FRONT',
                            (r(math.pi/2), 0.0, r(-math.pi)) : 'BACK',
                            (r(-math.pi/2), r(math.pi/2), 0.0) : 'LEFT',
                            (r(-math.pi/2), r(-math.pi/2), 0.0) : 'RIGHT'}

        view_orientation =  orientation_dict.get(tuple(map(r, view_rot)), 'USER').capitalize()
        view_orientation += " " + view.view_perspective.capitalize()

    if space.local_view is not None:
        view_orientation += " (Local)"

    return view_orientation

def get_quadview_index(context, x, y):
    for area in context.screen.areas:
        if area.type != 'VIEW_3D':
            continue
        is_quadview = len(area.spaces.active.region_quadviews) == 0
        i = -1
        for region in area.regions:
            if region.type == 'WINDOW':
                i += 1
                if (x >= region.x and
                    y >= region.y and
                    x < region.width + region.x and
                    y < region.height + region.y):

                    return (area.spaces.active, None if is_quadview else i)
    return (None, None)

class ModalTimerOperator(bpy.types.Operator):
    """Operator which runs its self from a timer"""
    bl_idname = "wm.modal_timer_operator"
    bl_label = "Modal Timer Operator"

    _timer = None

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

        if event.type == 'TIMER':
            space, i = get_quadview_index(context, event.mouse_x, event.mouse_y)
            if space is not None:
                if i is None:
                    view = space.region_3d
                else:
                    view = space.region_quadviews[i]
                print(get_view_orientation(space, view))

        return {'PASS_THROUGH'}

    def execute(self, context):
        wm = context.window_manager
        self._timer = wm.event_timer_add(0.5, window=context.window)
        wm.modal_handler_add(self)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        wm = context.window_manager
        wm.event_timer_remove(self._timer)
        return {'FINISHED'}

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

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

if __name__ == "__main__":
    register()

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

Thank you for the quick response, bpy.context gives more data access than I thought. But your code does not tell me what I need to know because I get a view_matrix even if the mouse pointer is not over the region.Example:

(Sorry, the system kicked me out here is the example):
I am in "Scripting" layout and have the 3D view split into two. In this situation, as you said, I can access the two view_matrices with bpy.context.screen.areas[x].spaces.active.region_3d.view_matrix, setting x = 2 for the first and x = 6 for the second view. Both seem to be "active", but I need the one (and only the one) the mouse pointer is in.

You are right, the original context is captured in a modal operator and you can't immediately determine which quadview the mouse is over. It's possible if you utilize the mouse coordinates from the event object and the region properties x, y, width and height. See my updated answer for a nice example.

Thank you very much, CoDEmanX! I hoped there is a more efficient method to get the active region. Let me post my own code here I am using now. It delivers the active region of a 3D view even if it is split or in quad view mode, or None if the mouse pointer is not in such a region:
def getActiveViewportRegion(self):
    for area in bpy.context.screen.areas:
        if area.type == 'VIEW_3D':
            if (area.x <= self._mouseX < (area.x+area.width) and
                area.y <= self._mouseY < (area.y+area.height)):
                # Mouse is in area
                if len(area.spaces.active.region_quadviews) > 0:
                    # Area is quadview
                    header = next(r for r in area.regions if r.type == 'HEADER')

                    quad_w = area.width/2
                    quad_h = (area.height-header.height)/2        #  +-----------------+
                    quad_0_x = area.x                             #  | quad 1 | quad 3 |
                    quad_0_y = area.y + header.height             #  |--------+--------|
                    quad_1_x = area.x                             #  | quad 0 | quad 2 |
                    quad_1_y = area.y + quad_h + header.height    #  |-----------------|
                    quad_2_x = area.x + quad_w                    #  |     Header      |
                    quad_2_y = area.y + header.height             #  +-----------------+

                    if (quad_0_x <= self._mouseX < (quad_0_x+quad_w ) and
                        quad_0_y <= self._mouseY < (quad_0_y+quad_h)):
                        return = area.spaces.active.region_quadviews[0]

                    if (quad_1_x <= self._mouseX < (quad_1_x+quad_w ) and
                        quad_1_y <= self._mouseY < (quad_1_y+quad_h)):
                        return = area.spaces.active.region_quadviews[1]

                    if (quad_2_x <= self._mouseX < (quad_2_x+quad_w ) and
                        quad_2_y <= self._mouseY < (quad_2_y+quad_h)):
                        return = area.spaces.active.region_quadviews[2]

                    return = area.spaces.active.region_quadviews[3]
                else:
                    # Area is not quadview
                    return area.spaces.active.region_3d
    return None

self._mouseX and self._mouseY come from a ModalTimerOperator as in CoDEmanX's code.

It's kind of a design limitation, modal operators are supposed to run inside the invocation context and thus bpy.context.region does not refer to the active region. Not sure why you do all the math there, my code determines the quadview region the mouse is over with way less code and calculations?! (the nth region of type WINDOW in 3D View is the nth region_quadviews space)

Updated my code to use either region_3d or region_quadviews and honor active camera perspective type.

Thank you for the enhancements. Interesting your method for getting the header. Being new not only to Blender but Python as well I will check how these iterators are working ...


text:
How exactly does Blender 2.8 viewport draw outlines?
I'd like to understand the technique (in OpenGL) Blender 2.8 uses to draw it's outlines in the 3d View.
So we're clear, I'm talking about the ORANGE outline of the suzanne in the picture below. And specifically, the fact that the orange outline shows "x-ray" style through other objects, like the cube here. How do they do that?
If not for the transparent x-ray, my first guess would be that they use the "scale up backface draw" method.. Where the object is drawn normally, then drawn a second time in the solid orange color, but scaled up slightly and only drawing backfaces. However, this method would not cause x-ray reveal through other objects.
Two ways I can imagine to do the x-ray reveal are:

when drawing the outline pixels, check the data in a screen-space "object picking buffer", to see if the object-id matches the object ID you are outlining. If it does match, then follow normal Z-occlusion rules. If it doesn't match, then draw the outline pixels with a depth of Float.MinValue (aka, a very near-z value) so all outlines will stay in front of everything drawn after
use a separate full-screen "outline buffer", draw all outlines into this buffer, and then do a full screen-space pass to composite the outlines back over the top of the normal framebuffer

Method 1 seems much less costly, and I suspect Blender already has a screen space object-picking buffer... so I suspect this is the method it would use. Can anyone in the know confirm?


text:
Issue when Exporting Mesh to UnrealEd
Hello friends this is my first post here.. I just started my own project after tons of procrastinating, and after maybe 2 horus of Blender tutorials, i made a model. It's a submarine, i know it looks like a bomb but it's just the basic version, and it looks somewhat fine on Blender (and it's not finished yet).

Now This is how the imported mesh looks on Unreal.

How it looks on UnrealEd Now the problem comes when importing it to UnrealEd, it seems like it smooths out the edges of the Mesh. There msut be a problem when exporting right?
It looks ok if i uncheck the Apply Modifiers box, but it only renders half the submarine (Considering Mirror is a Blender modifier) and if i leave it checked it'll end up looking like pic 2. Even when selecting faces (which was the recommended option in the tutorial)
tl;dr Mesh looks ugly on unreal what should i do?

Oh my. After a some search i've come up with the answers.
Followed This and This which are basically the same answer. Worked like a charm.


text:
How to get uv_on_emitter for child particles?
I wonder if there is possibility to get uv_on_emitter for all particles including child particles?
My loop over particles look like this:
for pindex in range(0, num_parents + num_children):
    p_uv = partSystem.uv_on_emitter(mod, partSystem.particles[pindex])

When there are children enabled I got index out of range because partSystem.particles returns only parents, not the children.

children are in particle_systems['ParticleSystem'].child_particles.items()[x][1] which is a ChildParticle not sure where their location is.

The problem is that ChildParticle won't help me much as uv_on_emitter is expecting Particle type.

Heres what you do:
if pindex >= num_parents:
   particle = psys.particles[(pindex - num_parents) % num_parents]
else:
   particle = psys.particles[pindex]
st = psys.uv_on_emitter(psys_modifier, particle, pindex)

interesting, but could you please elaborate by editing your answer what and why you do here?

authors: Сергей Кирсанов


text:
How do I change the color of particles with lamps?
I want my particles to change colors with lamps, but when I shine a lamp on the particles, they are still white. I made the lamp color purple and increased the energy of the lamp, but it didn't work. Any ideas?

Maybe try using dupli objects instead of the default halos.

How can I do that? Sorry I'm still new to Blender.

I'll post an answer with pictures in a couple minutes.

Sorry it took me so long I had to say goodbye to some relatives that were leaving...

To make your particles "physical objects" make a mesh off scene that you want your particles to duplicate. Then, in the particle menu, scroll down to the "Render" panel and check the "Object" box. In the text entry box select you duplicate object and you're done!

Can I change the color of the particles with lamps without making them physical objects?

No. Objects that don't exist can't reflect light. A halo is just a visualization of the xyz coordinates that the particle is keeping track of.

Any time. . . .


text:
Movement of array along curve in BGE
I am new with Game Engine, and I have a problem with something similar to bike chain. During simple animation, I used array modifier to duplicate those single chain elements, and then I used curve modifier, so that this chain was moving on a path created by me. Seems that all of those arragements don't work in Game Engine at all. Could anyone give me a hand with developing this on-curve-movement in Game Engine?Thank you very much for any help! With regards:)

Curves are not supported in the BGE. Therefore this can't work.

Is there any other way to develop the same movement? For example some kind of script in python? My project is simmilar to chain/conveyor belt, so I assume that this kind of animation in game is not so rare. Please give me a hand with that, I got really stuck :( Thanks a lot

Do you specifically need geometry to move, or would a moving texture suffice? If a moving texture is enough, I would advise you to look into the AnimAll plugin.

If you could use Follow path constraint, making your objects move along that curve, then you might bake action after it's ready to the keyframes and delete the curve.

I specifically need geometry to move, i need something (rigid body for example)to be moved on that conveyor belt, that is why texture is now enough.(


text:
Project 3D Object on a plane
I have 3D Objects I want to convert to 2D Geometries by projecting onto a plane. Is that possible with Blender? If possible in an automatic way. An export to a Shapefile would be fine too.
For instance, I have a 3D building and I would like to get the 2D Geometry as if the Object were parallel projected on the ground plane (for instance the x-z-plane).
A box/cube would either become a rectangle or an hexagon depending on the rotation.

Place a plane on the axis you want (for instance x, z).
Add a shrinkwrap modifier to your mesh and set this plane as target object (mode = 'nearest surface point').

Of course you can also scale to zero along an axis... but the shrinkwrap allows to do it in a none destructive way and to project to any plane.

Does this require cleaning up the mesh afterwards (intersecting vertices, z-fighting, etc.), or is that handled in the modifier?

the shape is just flatten. For the rest, nothing changes about its faces or edges (so for instance, that does not calculate intersections).


text:
How to add textures to faces that are facing a certain direction
Basically I have a crude maze-like object, but I want the textures of the floor and walls to be different.  How would I go about placing a texture on all faces point north, etc.
Assume I am a beginner, please.

cycles, BI or BGE? and are you talking about one material, or different materials on the floors and walls?

Not entirely sure, my intention is to import it into Unity, so whichever accomplishes that? If I'm understanding the question at all, I apologize for my lack of knowledge right now--I will do more research later it's just all very confusing.  And they are all one material I believe.

If you have multiple materials assigned, you can use Shift+g to activate the Select Similar menu.  For selecting all of the floor area, using Normal works well.  You only have to select one face and all others that have a similar normal should be selected automatically by the tool.  There is a slider that controls a threshold value that you can adjust to change the angle overlap.
Once all the faces for that area are selected, you can select the appropriate material and press the Assign button.

For the textures, I used the Box setting which maps the texture from all directions if you add a Texture Coordinates node and set the Input for the texture to Object.

Here is a copy of the .blend file so you can have a closer look. :)

In Cycles you can make a node setup like this:

What's happening is the Geometry node is providing the object's normal data (information about the directions its faces are pointing) in the form of color values. The Separate XYZ node is taking that all in but only returning the values for the Z axis (up and down). That data is then being used to factor between the red and blue.
In this example the factor is mixing two shader nodes, but it could just as easily be color nodes or any node that can receive a factor input.
If you wanted to change the direction you could use X or Y outputs instead of Z.


text:
Is it possible to disable menu items in custom menus?
I want to disable and enable menu items (layout.operator) in my custom menu, the disabled ones should be displayed greyed. I managed to disable the whole menu with layout.enabled = False, but I failed to disable a single menu item.
Something similar what I want to achieve can be seen in the "Ui Menu" Python template with the entry "Hello world!", but this is a layout.label and not a layout.operator. Before I use this approach as workaround I'd like to know if there is a more easy way to dis- or enable single menu items.

You can implement operator.poll for your own operators. If the operators poll method returns false the operator will automatically be disabled in the UI.

Thanks, works perfectly! Will you write this as an answer?

As already said by pink vertex and Jerryno, a poll() classmethod should be added to the operator you add to the custom menu. The disabling (graying out) will be managed by Blender automatically:
import bpy

class SimpleOperator(bpy.types.Operator):
    bl_label = "Simple Operator"
    bl_idname = "wm.simple_operator"

    @classmethod
    def poll(cls, context):
        return len(context.selected_objects) % 2 == 0

    def execute(self, context):
        self.report({'INFO'}, "Simple Operator executed.")
        return {'FINISHED'}

class SimpleOperator2(bpy.types.Operator):
    bl_label = "Simple Operator 2"
    bl_idname = "wm.simple_operator2"

    @classmethod
    def poll(cls, context):
        return (context.object is not None and
                context.object.type == 'CAMERA')

    def execute(self, context):
        self.report({'INFO'}, "Simple Operator 2 executed.")
        return {'FINISHED'}

class SimpleCustomMenu(bpy.types.Menu):
    bl_label = "Simple Custom Menu"
    bl_idname = "OBJECT_MT_simple_custom_menu"

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

        layout.label("Enabled, if even number of objects selected", icon='INFO')
        layout.operator("wm.simple_operator")
        layout.separator()
        layout.label("Enabled, if active object is a camera", icon='INFO')
        layout.operator("wm.simple_operator2")

def register():
    bpy.utils.register_module(__name__)

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()

    # The menu can also be called from scripts
    bpy.ops.wm.call_menu(name=SimpleCustomMenu.bl_idname)

If you want specific GUI elements to be disabled, set corresponding row.enable or column.enable to False:
row = layout.row()
row.operator("something")
# maybe more row stuff here
row.enable = False

If you want this build in into the operator itself, include the poll method. This will grey it in the UI and also be safe when the user calls the operator from search (spacebar) for example!

I am not sure how these row commands could be integrated into CoDEmanX's SimpleCustomMenu above or into Blender's "Ui Menu" template I am derivating from. Sounds more they could be used in panels, but I am not familar with these yet. But anyway, I am happy with my new poll() method!


text:
Reading out all operators in a header's menu
How is it possible to read out the menus of a header and the operators in the menus with Python?
Background:
I have an external hardware with some configurable keys, and I want to trigger the operators in Blender's menus with the keys. In the hardware's GUI is a dialog to assign functions to the keys. In this dialog is a list of available functions, and I try to fill this list with all of Blender's menu items. If possible the list should show up in the same hierarchical structure (menus and submenus) as in Blender and reflecting the actual state Blender is in.

There's no straight-forward way to retrieve the contents of menus or other layout types.
If possible, create shortcuts in the User Preferences, but that might not be possible with external hardware keys. Or if that's sufficient for you, Right-click > Edit Source to see the layout code (mostly python-scripted).
It might be feasible to extract layout information somehow by hacking deep into the Blender internals with Python, see this to get an idea:
http://wiki.blender.org/index.php?title=Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Interface&oldid=226944#Overriding_Interface_Elements

The atttibutes "label", "menu" and "operator" of bpy.types.Header.layout seem to contain the information I am looking for. What I'd need is a list of all header objects currently defined. I hoped to get all header objects of a screen by looping over all areas and regions and searching for regions of type "Header". But it seems not to be possible to get the header object linked to a region. I will postpone the problem and perhaps come back later to it. Nevertheless, thank you for the answer.

If all you wanna know is what is there and not where, you can do bpy.types.Header.__subclasses__() to get all subclasses of Header, which are effectively all area headers regardless whether they are currently shown or not.

In my (limited) understanding of Python this gives me a list of all defined subclasses but not the concrete header objects I'd need to iterate over their contents. In any case, when assigning h=bpy.types.Header.__subclasses__()[0] e. g., I expected h to have access to h.bl_idname or h.layout; but it seems to have access only to the attributes of Header's base class bpy.types.bpy_struct and not to the attributes of bpy.types.Header.

You can't access the "header objects". Layouts are defined in Python and drawn by C code. The only way I can think of is to replace the UILayout type to hook into the layout drawing system. It might only give you the currently drawn elements however.

Perhaps I try to parse the files space*.py in the startup script folder; there are only few labels for the operators though - may be a look into the localisation files could help for this. But this is work for next year ...


text:
Is there a way to execute code before Blender is closing?
My add-on needs to do some clean-up action before it is ended. This is done in the unregister() function in __init__.py when the user unchecks the add-on in Blender's preferences dialog and works fine in this case. But if the user just closes Blender the unregister() function seems not to be called. How could I achieve this or force Blender to do some other action before closing? There is no handler list for the event "Blender is closing" in bpy.app.handlers as far as I can see.

There is indeed no handler for that event, nor is unregister called (only on actively unticking an add-on). This leaves you behind with one more option: Python's native deconstructor __del__. It might be called as Blender terminates.

No, the destructors are neither called when Blender terminates. But I think I have a workaround:
I have a timer running ("Operator Modal Timer" from the template list), and its cancel() function is called by Blender when terminating! To distinguish the various callers of the cancel() function I count the elements in the stack trace, given by traceback.format_stack(). I figured out the following:

1 element in the traceback list: cancel() is called because Blender is terminated.
3 elements in the traceback list: cancel() is called because a *.blend file is loaded.
5 elements in the traceback list: cancel() is called because my "stop timer" menu button is pressed by the user.
8 elements in the traceback list: cancel() is called because the add-on is unchecked in Blender's preferences dialog.

I am aware that counting on these values is very unsafe because they may change with each Blender version or even with the state Blender is in. But important for me is only the first case, and it seems to work for me that way - at least for the time being ...

Great find! One downside: F8 is not possible while a modal operator is running, you will have to end it before a script reload. Regarding counting the stacktrace entries: you can catch the .blend load event with an app handler, a click on "stop timer" in your own operator and addon unticking with code in unregister() - so actually no need to count at all - or am I overlooking something?

You are not quite right: Yes, the cases with 3, 5 or 8 elements in the traceback list do not matter (I have the other event handlers you propose already). But my handler for "Blender closing" must only be called in the case with 1 element in the list, not in the other cases; therefore I have to check this - and hope this value will not change with future versions.
With the F8 problem I have to live; my "stop timer" button allows to stop the timer.

I see, but if you can detect all 3 other events, can't you infer that all other events must be "Blender shutdown"?

Yes, this is possible, You can use Python's atexit module.
This can be used exactly as you would writing regular Python code (no Blender specifics are required.).
eg:
import atexit

def my_cleanup_code():
    print("cleaning up!")

atexit.register(my_cleanup_code)

Still works with current blender 2.82. No external dependencies needed, it's stable and works exactly as advertised.

Note: The Blender objects are already deleted at the time the function is executed. If you have some property (of a custom class) that is not automatically deleted by Blender (in my case it was something like self.batch_cached = batch_for_shader(...)), make sure you call atexit.register(...) with a function using directly the reference to the to property (here: self.batch_cached), since something like bpy.types.Object.my_custom_object is no longer available.

I think the better option is use  some handler event...
http://www.blender.org/api/blender_python_api_2_73_2/bpy.app.handlers.html?highlight=bpy.app.handlers#bpy.app.handlers.version_update
maybe you can "load" a new blender file before blender is closing.. then you can use the
bpy.app.handlers.load_post
on loading a new blend file (after)

bpy.app.handlers.load_pre
on loading a new blend file (before)

there is the moment to do something before or after blender change to another blender file :D
best


text:
Problem with matrix_parent_inverse of childs of bones
I am trying to move around objects by manipulating their transformation matrices with Python. If the objects are in a parent/child hierarchy you have to step down this hierarchy using the object's matrix_parent_inverse element. My code works fine with one exception: In case an object is a child of an armature's bone the child has a matrix_parent_inverse I do not understand.
Say, we have a cube as child of a cone as child of a cylinder, i. e. the hierarchy cube -> cone -> cylinder. bpy.data.objects["Cube"].matrix_parent_inverse gives me the inverse matrix of the cone at the time of parenting. Fine.
Now we have the same situation (at least in my opinion) when the cube is the child of a bone. The hierarchy is in this case cube -> bone -> armature. bpy.data.objects["Cube"].matrix_parent_inverse should give the same result as in the first situation but it does not. So my question is: What is the meaning of matrix_parent_inverse in this case or how can I get the correct one?
Sample code showing the different results (Blender 2.71):
import bpy

#------------------------------------------------------
# Make a parent hierarchy
# cube -> cone -> cylinder
# "->" means "is child of"
#------------------------------------------------------

# Delete the scene:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

# Create a cylinder at location (2, 3, 4):
bpy.ops.mesh.primitive_cylinder_add(location=(2, 3, 4))

# Create a cone and make it the cylinder's child at the same position:
bpy.ops.mesh.primitive_cone_add(location=(2, 3, 4))
bpy.context.scene.objects.active = bpy.data.objects["Cylinder"]
bpy.ops.object.parent_set(type='OBJECT')

# Create a cube at (0, 0, 0) and make it the cone's child:
bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
bpy.context.scene.objects.active = bpy.data.objects["Cone"]
bpy.ops.object.parent_set(type='OBJECT')

# Print the cube's parent inverse matrix:
print(bpy.data.objects["Cube"].matrix_parent_inverse)

#------------------------------------------------------
# Make a parent hierarchy
# cube -> bone -> armature
# "->" means "is child of"
#------------------------------------------------------

# Delete the scene:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

# Create an armature at (2, 3, 4), a bone is created automatically as child:
bpy.ops.object.armature_add(location=(2, 3, 4))

# Create a cube at (0, 0, 0) and make it the bone's child:
bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
bpy.context.scene.objects.active = bpy.data.objects["Armature"]
bpy.ops.object.mode_set(mode='POSE')
bpy.ops.object.parent_set(type='BONE')

# Print the cube's parent inverse matrix:
print(bpy.data.objects["Cube"].matrix_parent_inverse)

# => output:
#<Matrix 4x4 (1.0000,  0.0000, 0.0000, -2.0000)
#            (0.0000,  1.0000, 0.0000, -3.0000)
#            (0.0000,  0.0000, 1.0000, -4.0000)
#            (0.0000,  0.0000, 0.0000,  1.0000)>
#
#<Matrix 4x4 (1.0000,  0.0000, 0.0000, -2.0000)
#            (0.0000,  0.0000, 1.0000, -5.0000)
#            (0.0000, -1.0000, 0.0000,  3.0000)
#            (0.0000,  0.0000, 0.0000,  1.0000)>
#
# Both matrices should be the same but aren't.

Parenting to bones uses bone’s tip, not its root. Think this explains the difference?

No, I don't think so. This could have some effect in the matrix' last column (the translation part) only but not in the second and third column; there are some new rotation elements now ...

No, default rotation of bones is not the same as the one of mere object (just add a new object, a new armature, and compare new object's and new bone's matrices…).

Hm, I cannot confirm that: If I create an armature with bpy.ops.object.armature_add(location=(2, 3, 4)) as in my sample code above, switch into pose mode and print bpy.context.active_pose_bone.matrix_basis I get the identity matrix. There is no rotation component in the bone. The translation is in the armature's matrix of course as one should expect.

Yes, but this is based on 'bone space' as defined by rest pose (aka edit mode), do this in Object space and you’ll see: C.object.data.bones[0].matrix

Yes, you are right. Strange. I will check if using .data.bones[x].matrix_local in some way can solve my problem. Thanks for the hint.

Thanks to mont29's hint I have found a solution:
A bone seems to have two representations:

bpy.context.active_pose_bone.matrix_basis
<armature>.data.bones[x].matrix_local

Dependant on the context (pose mode/object mode) one sees the one or the other. There is a rotation by pi/2 around the x-axis and an offset of 1 in the z-axis between them. Here is the sample code from above again, the correction to make the second matrix equal to the first is added at the end.
import bpy
import mathutils
import math

#------------------------------------------------------
# Make a parent hierarchy
# cube -> cone -> cylinder
# "->" means "is child of"
#------------------------------------------------------

# Delete the scene:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

# Create a cylinder at location (2, 3, 4):
bpy.ops.mesh.primitive_cylinder_add(location=(2, 3, 4))

# Create a cone and make it the cylinder's child at the same position:
bpy.ops.mesh.primitive_cone_add(location=(2, 3, 4))
bpy.context.scene.objects.active = bpy.data.objects["Cylinder"]
bpy.ops.object.parent_set(type='OBJECT')

# Create a cube at (0, 0, 0) and make it the cone's child:
bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
bpy.context.scene.objects.active = bpy.data.objects["Cone"]
bpy.ops.object.parent_set(type='OBJECT')

# Print the cube's parent inverse matrix:
cmpi=bpy.data.objects["Cube"].matrix_parent_inverse
print("cmpi:")
print(cmpi)

#------------------------------------------------------
# Make a parent hierarchy
# cube -> bone -> armature
# "->" means "is child of"
#------------------------------------------------------

# Delete the scene:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

# Create an armature at (2, 3, 4), a bone is created automatically as child:
bpy.ops.object.armature_add(location=(2, 3, 4))

# Create a cube at (0, 0, 0) and make it the bone's child:
bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
bpy.context.scene.objects.active = bpy.data.objects["Armature"]
bpy.ops.object.mode_set(mode='POSE')
bpy.ops.object.parent_set(type='BONE')

# Print the cube's parent inverse matrix:
mpi=bpy.data.objects["Cube"].matrix_parent_inverse
print("mpi:")
print(mpi)

#------------------------------------------------------
# The correction to make the second matrix equal to
# the first
#------------------------------------------------------

ri=mathutils.Matrix.Rotation(math.pi/2, 4, 'X').inverted()
ti=mathutils.Matrix.Translation(mathutils.Vector((0,0,1))).inverted()
mpii=mpi.inverted()
mpiiriti=mpii*ri*ti
mpiiritii=mpiiriti.inverted()
print("mpiiritii:")
print(mpiiritii)

# Output (some formatting added by hand):
#
# cmpi:
# <Matrix 4x4 ( 1.0000,  0.0000,  0.0000, -2.0000)
#             ( 0.0000,  1.0000,  0.0000, -3.0000)
#             ( 0.0000,  0.0000,  1.0000, -4.0000)
#             ( 0.0000,  0.0000,  0.0000,  1.0000)>
# mpi:
# <Matrix 4x4 ( 1.0000,  0.0000,  0.0000, -2.0000)
#             ( 0.0000,  0.0000,  1.0000, -5.0000)
#             ( 0.0000, -1.0000,  0.0000,  3.0000)
#             ( 0.0000,  0.0000,  0.0000,  1.0000)>
# mpiiritii:
# <Matrix 4x4 ( 1.0000, -0.0000,  0.0000, -2.0000)
#             (-0.0000,  1.0000,  0.0000, -3.0000)
#             ( 0.0000, -0.0000,  1.0000, -4.0000)
#             (-0.0000,  0.0000, -0.0000,  1.0000)>


text:
How do I copy an object without copying the weights?
I have a man I am making clothes for.  when I copy his upper body to build a shirt the weight painting for the armature gets copied along with the object but I don't want it to and I can't seem to erase all the weight painting from the copied object.  I was wondering if I could either copy object without weights somehow, or remove all weights from a object somehow.  Either one would work, thanks!

You can delete that vertex group that was added when you created that vertex weights

Hey Isak, did Mr Zak's solution help?

I'm not seeing a new vertex group.  I duplicate the object, then separate it so it is it's own mesh.  The problem is it still has all the weights that the object it came from had.  I'm not seeing that it created a new vertex group, but I could be wrong, I'm relatively new to Blender.

I figured out the answer. I had to remove the armature modifier from the mesh. I found that out here, http://blenderartists.org/forum/archive/index.php/t-235499.html


text:
Why did my physics start working up after adding a face mask?
I am making a ninja, I added a hoodie and put a cloth modifier on it.  I put a collision modifier on the body and everything was working great.  I moved on to the next step and made a face mask, put the cloth modifier on it to, and now I am having problems.  The face mask wants to fall through the body even though it has a collision modifier on it.  It also goes through the hoodie. The hoodie has also started acting up, as in the ends of the sleeves want to get all twisted and spiky when I start the simulation. I have pinned the hoodie and the mask.

Ensure the objects are all on the same layer.

I just checked and everything is on the same layer except the custom shapes I made for the bones.

It depends, usually caused by intersection. If it doesn't, you really need to upload your problematic file here to get first aid quickly. You can use http://www.pasteall.org/blend.

@LeonCheung The preferred upload site is now Blend-exchange, see: http://meta.blender.stackexchange.com/questions/297/can-we-have-a-service-for-uploading-blendfiles/629#629

blend-exchange .com .org .somethingelse?

http://blend-exchange.giantcowfilms.com/

I had a week off, so this comment is a little delayed, but I think I figured it out.  I changed the outer and inner of the body, and the distance and repel of the cloth along with a bunch of other tweaks and that fixed most the problem, then I fixed a couple areas where the clothes where to close and that fixed more of the problem.  still having miner issues, but I think I'm on the right track.


text:
Why is my sub-surf modifier acting up?
The sub-surf modifier is causing a weird indent around the end of my sleeve right next to where I have the sleeve thicken a little and I was wondering why it was causing that and what I can do to fix it?

looks like flipped normals in that area

see this answer: http://blender.stackexchange.com/questions/12165/make-all-of-the-faces-flip-to-the-right-direction

It was my normals on hidden geometry.  I had tried flipping the normals automatically and manually earlier and it didn't help, but after reading your comments I decided to try again and I found some hidden faces I didn't realize had been created and they were backwards.  THANKS!!


text:
animating a body and having it effect cloth
I have a body I've created and put clothes on him.  I gave them a cloth modifier and him a collision modifier.  When I simulate the cloth it falls on the body and reacts like cloth, however if I animate the body, it goes through the cloth is there something that I need to do to make the cloth keep reacting to the body as it is animated?

You could try pinning the mesh and make a parent relation to your main body, it will then follow the body you modeled, take a look at this explanation on how it works:
https://docs.blender.org/manual/en/dev/physics/cloth/settings/cloth_settings.html#cloth
Have a nice day.


text:
How should I design the jaw for rigify pitchipoy?
I decided to try using the Rigify (Pitchipoy) Add-on and watched a tutorial on how to set it up.  When they where working on the face they parented the jaw without weight paints, just normal parent and it looked like the jaw was 2 separate objects from the rest of the mesh, the upper and lower jaws each their own.  I was wondering how I should model the jaws for this.  Should I make separate meshes for the upper and lower jaws and parent them to the mesh and to the armature?  If so, how do I make it so when the character opens his mouth and jaw it doesn't saperate and you see the inside of the back of the head?  Basically, how do you model the inside of the mouth for this rigify (pitchipoy) add-on?

When rigging you need to be clear about what you want to achieve, because every little function takes time to accommodate for. Which also means that I cannot give you the perfect answer unless you describe your character more clearly. If you want a character with a normal organic jaw, then skip the following paragraph.
The only reason you would parent something without weight paints is if you want a ridged object attached. If this character had an iron jaw for example, it might make sense. I'm not sure if pitchipoy is built for that, but if you were to attach it to just one bone you could probably achieve a ridged effect. However, that would make some mesh items harder to track down. So i'd recommend a ridged bind (flood the influence to one bone) that is IF you want a ridged jaw.
If you want a normal organic jaw, then ignore your tutorial and find a better one because organic meshes generally require weight binding. I'd follow the official video for that: https://www.youtube.com/watch?v=-dwCXMc2V0U
The only thing i'd advise making into separate geometry is the teeth and tongue. That's just so that it's easier and more clean of a job when weight painting. Teeth can have ridged weighting, tongue can have auto weights. For the mouth, it's just a concave section of geometry, and of course attached to the rest of the surround mesh. You will need to ensure that the weights do not collapse the geo into the teeth and tongue when the character open's it's mouth.


text:
animating a marshmallow burning
I am trying to animate a marshmallow burning in a flame.  I am working on the flame right now and am about to start trying to animate it and am wondering how to animate color changes.  The marshmallow is going to start white and I want it to change to a golden brown color, then catch on fire and change black.  I'm new to blender and have done a couple little animations but those have all kept everything the same color, and I was wondering if it is possible to fade from one node to another somehow.

you can make keyframes  in the nodes for the color. So if you are at the beginning of your timeline you can set the color to white and hit I to insert a keyframe. Then some frames later you can change that color to golden brown and hit I to insert a keyframe. Maybe you then have to change the interpolation mode (T) in the graph editor.

Thanks!  I didn't know you could do that for nodes too.  I knew you could do it for location, rotation and scale, but didn't know you could for nodes, thanks!

@gladys This didn't work for me. Does this keyframe rule still stand in Blender 2.28? If not, is there another way to do this?


text:
Select vertices of mesh in python
What is the python way to select vertices of a mesh?
I've tried:
for vert in obj.data.vertices:
    vert.select = True

I ran the above code in edit mode, but the vertices didn't turn yellow.

related : http://blenderartists.org/forum/archive/index.php/t-200305.html

import bpy,bmesh

ob   = bpy.data.objects['Cube']
mesh = bmesh.from_edit_mesh(ob.data)
for v in mesh.verts:
    v.select = True

# trigger viewport update
bpy.context.scene.objects.active = bpy.context.scene.objects.active

Docs

What's the need for the ob variable?

I believe it's just so you don't have to keep typing bpy.data.objects['Cube'], for instance, where it's accessed again in bmesh.from_edit_mesh(ob.data)

thanks for this simple example. arent we suppose to free the bmesh after ?

When trying this in Blender 2.91 it complains that "The mesh must be in editmode"..

@user299831 bmesh.from_edit_mesh requires you being in edit mode for the object initially.


text:
Alphanumeric Keyboard input not working on downloaded .blend file
I just downloaded a .Blend file and the number and letter hotkeys are not working.  Things like the tab key still work.  I open other files that where already on my laptop and everything works just fine.  The file I downloaded is from my other computer and it works just fine on that computer with all the key input working but for some reason not when transferred. I have downloaded two versions of the same file, one with everything packed, and one just the file before packing.  Both files have the exact same problem.
I am using version 2.78.
my laptop should be fine, i7 processor, 12G ram, 64 bit operating system.

Here it is http://pasteall.org/blend/index.php?id=44061