Blender to Hammer/Source SDK I'm desperatly trying to figure out on how to export a 3D Model with it's texture into the Hammer Map Editor (Source SDK) for Garry's Mod. So far I managed to make models and to have them in there but I am struggling a lot to figure out on how to actually put on the texture.
I followed the instructions of this video

Sadly I only get the model out since he does not explain anything on how to get that texture over. Even if I follow all his steps step-by-step, I just cannot get the texture over. Then I tried this. I saved the texture file as png, used VTF-Editor or viewer and turned the png into a vtf file. Put it in a folder and then all I have is a texture I can apply to my blocks, but it's not attached to the model like it is with all the other things.

Next I also tried using the hlmv tool to check on the model but all I guess is the pink and black checker texture and the message that the texture cannot be found.

I'm slowly losing my mind over this since I have tried so many things. Apparently when some things have a _ in their name the texture also just stays blank and when I remove it it starts working again for the texture alone.

Do we have anyone here who could please please show me how this works or tell me what the steps are.

Here are the steps I took.

Create a simple model in Blender
Giving it a UV model/texture
Exporting it via the Source Tool plugin
creating the QC-File and moving both onto the Studiomdl.BAT-file to create the model for Blender
Save the UV-thing as png
Open the png in VTF-Editor and save as VTF
Create a VMT File refering to the VTF file and put them inside a subfolder in the materials folder
Opening hammer or hlmv tool and check if the texture is applied
Losing my mind since yet another attempt did not work out. :C

STUDIOMDL.BAT file:

"C:\Program Files (x86)\Steam\SteamApps\common\Garrys Mod\bin\studiomdl" -nop4 -game "C:\Program Files (x86)\Steam\SteamApps\common\Garrys Mod\Gmod" %1
pause

QC file:

$modelname Varmints_Models/pumpkin1.mdl
$model "Body" "pumpkin1.smd"

$staticprop
$cdmaterials "models/Varmints_Models/"
$surfaceprop "pumpkin1"

$sequence "idle" "pumpkin1.smd"
$collisionmodel "pumpkin1.smd" { $concave }

VMT File Code:

VertexLitGeneric
{
  $basetexture "Varmints_Models/Pumpkin1"
}

Solved the problem. It was a basic issue related to the texture being in the wrong path.

Here a video / Highlight I made from a past stream. So feel free to watch.

Youtube Link

It was mostly on the fly and serves as a reminder for me and others in case someone needs help with this. I might do a more detailed video on this.


How to keyframe a shapekey I am trying to animate a simple scene to test the shape key I added to the object but I tried to keyframe the shape key but I couldn't.

When I keyframe the object after changing the shape key then I go to the next frame and change the shape key to what I want and play the scene the object doesn't change at all

All the tutorials I found were for blender 2.4 which is i guess outdated

How can I keyframe a shapekey?

Just by going by the description of your process for inserting keyframes it sounds like you are only creating 1 keyframe.

The process to animate a property is to:

Set the value of the property (in this case the 'Value' property of the shapekey)
Insert a keyframe by pressing I with the cursor over the Value property.
Move to a different frame in the timeline.
Set the property to a new value.
Insert a second keyframe on the property.

Keyframes have to be inserted at every point in the timeline where you want the property to change to a specific value.


Cycles material for VR + photo-realism Is there a way to export materials applied to a mesh in cycles, to any game engine? I tried using Unity, despite the accurate color allotment, the render appears to be much cartoonistic. Is there any way you can add photo-realism for creating an application for VR, alongside the support for interaction with the objects in scene?

Cycles and Unity render method are totally different, you can't expect a Cycles material to look the same in Unity. But you can try a few things.

Baking

Baking is a tool that allows to "convert" your material into a texture.  Doc

The advantage is that the (costly) render is done only once, and the realtime engine only have to display a texture (cheap).

The disadvantage is that most material effects can't really be baked, because they are view dependent (ie. reflections).

Lighting can be baked if you don't need dynamic lighting (ie a light that move or change intensity). You can do it with Cycles, but it's certainly easier to do it in Unity Doc

PBR workflow

Physically Based Rendering (PBR) is a workflow that is supported by either Cycles (with the Principled shader) and Unity (with the Standard shader), and many modern game engine. It won't make the Unity shader look better (it's already the default shader), but at least it allow to have a relatively similar result while you are working on your object in Blender.

Game engine side

I won't be really specific cause I'm not an expert (and that's not the place), but a lot of things can be done to boost up a Unity (or UE4) render.
I mentioned light baking. You can also use reflection probes or even Screen Space Reflection to get better looking reflections. Ambient occlusion is a great way to increase realism.


Problems with multiple UNION in Blender I am trying to combine many objects (in the order of hundreds) in BLENDER by the UNION operation (boolean modifyer, union). Correspondingly I wrote a small script that cycles through the objects, combining one after the other with the alwyays growing first object. This script works quite well for a few objects and operations (that I can also verify by hand). If their number rises, however, I get funny results. Usually several objects are missing from the growing "all-union-object". I assume that the UNION-function at some place messes up (as described in the www), and that all subsequent UNION-operations suffer from this. Is there any Modifier (or other way) that I could treat the single objects with in order that this UNION works? I have tested so far the REMESH and TRIANGULATE modifiers and also have scaled the single objects by different numbers in order to get rid of identical faces that might exist among the objects. Unfortunately, all this seems to change only the ultimate output and the appearance after combining a few objects. Cycling through the larger list of objects, however, always gives problems.
Any help is highly appreciated.

To the background: From another program I get initially in VRML/WRL many different spheres and cylinders that in part are identical and in part overlap. I cannot change this behavior and would like to have in the end one single entity (or object) like the UNION of all those little objects or the outer surface encompassing all those little objects. Importing to BLENDER (which works as expected) and combining all little objects by UNION (my question) would solve the problem (at least in theory if there were not the problem I am asking here ...). I am certainly not limited to this approach, so maybe there is also another one that would circumvent this issue with the multiple UNION in BLENDER ...

Join all the objects you want to unite using Ctrl+J
Create a new cube that contains all the joined objects inside
Use the Boolean Modifier on the Cube with Carve Solver and Intersect Operation


What do you do if you dont have a numpad imtrying to follow a tutorial on youtube but I have a laptop, and it doesent have a numpad, please help whats a good alternative

On a mac, you can use the Funtion key (fn) + U or I or O or j or k or L or M.. please check this image:


Create a stretchy line between two objects? So I want to create this stretchy rope effect as seen in this video.

I want to use either soft body or cloth physics, so I can bounce objects off of them. And I also want it to be connected to two points that move around.

Theres a similar post here, but I can't get it to hook onto both objects. It will either hook onto one or the other, but not both.

I couldn't get it to work with a curve as suggested by Greg Zaal, as you said the curve doesn't seem to want to stick to multiple hooks at once..

However it works fine for me using a mesh as explained in my previous answer, and it still runs realtime at 24 fps for me:

Example .blend


How to connect the vertices of two separate objects? While I was modelling a bird I ended up in a dead end and I do not know how to get out. I created the eyes of my bird as two separate objects using the mirror modifier, but now I can no longer connect the eyes vertices with those of the rest of the face because I have two different objects.

If I join the eyes vertices with the face/body vertices using Ctrl+J I will lose the mirror modifier, but I don't want to loose the mirror modifier for the eyes.  So I don't see a way out from this situation.

Could you not work with one eye and your faced joined up and mirror afterwards?.

Highlight the eye vertices in edit mode with  with C or B then separate by selection with P and apply the mirror to new object creating your second eye. As long as it lines up nice it would get you your mirror option back.


What's causing these artefacts when rendering my baked normal maps? I'm trying to bake normal maps for my first hi poly to lo poly sculpt and things are coming out wonky.

I made the low poly mesh by remeshing it in Instant Remesh, and then decimating it further using a Decimate Mod in Blender. It's not pretty topology but it was a fast way to do things and I've seen similar things done online etc, and I just plan on using this as a static character sculpt.

The normal maps are coming out looking weird once I apply them to the Lo Poly model.

Here's some pictures:

Also I have a thread on Blender Artists I started asking for help that also includes a blend file for download.

https://blenderartists.org/forum/showthread.php?435940-Baking-normal-maps-for-the-first-time-and-things-are-looking-funky-on-the-lo-poly-out

I'm pretty sure that weird artifacts on your bake were caused by the bad topology of low poly mesh. I 've made a really quick and dirty retopology of the model (it's still, like your previous low poly model, around 50 000 verts). I 've also really quickly unwrapped that mesh and baked the texture.

Here are the results and as you can see there are still some artifacts around UV seams. I'm sure you can do it better than I did if you invest some time in making a good mesh and a UV map.

the normal map bake:

Look in the .BLEND file for more information. I removed the high poly model from it because of the size but you already have it, so I guess that isn't a problem.


How to toggle the menu bar back? I hit some hot key that I'm unsure of and now the grey main menu bar at the top of the screen is gone and I don't know how to get it back.

edit: It's the bar with File, Render, Window, and Help tabs.

Late answer, but menu bar that @so_confused was looking for is just another Blender view/panel/window, just like the Properties panel or the 3D View port. You just need to add a window/panel of type "Info" and position it where you want it (default location is at the top). It will likely show the console output at the top, which you can just hide by dragging the bar edge up to cover the console.

For those who've lost the icon/dropdown altogether, you need to pull up the hidden bar from the bottom of the panel. Here's a sample video to illustrate: https://youtu.be/uB7F4O3Ju5o


'LIB ERROR: object lost from scene' error when opening file When I tried to load the attached blend-file a few minutes after saving it, I got the message 'LIB ERROR: object lost from scene', and I realized that a tunnel I had made around the road was lost!

The mesh object that was lost was a cylinder named 'TUNNEL'. Like the other mesh objects ('ROAD', 'SIDEWALK LEFT' and 'SIDEWALK RIGHT') it had an array followed by a curve modifier, that made it follow the 'ALIGNMENT' path.

I checked the last Quit.blend, it had the same problem. Too, with the last autosave.

I am, once again, completely baffled. Can anyone make heads or tails out of it?

I can't say why this has happened, but your tunnel is still in the file.

Make a duplicate of the 'ROAD' object, go to the duplicate 'ROAD's Data panel, and then select the data that has a '0' next to it:

This should assign the mesh datablock back to an object and your duplicate road should now be your tunnel. The '0' next to the mesh datablock meant that the mesh wasn't being used (as it wasn't assigned to any object).

From what I've read about the error you got it refers to objects that were linked from other files, and then the object in the original file has been renamed, breaking the link, meaning blender is unable to find and load the object.

However, there are some reports of this happening without any renaming, which if you are able to reproduce it, should be reported as a bug report here (or added to that bug report I linked to).


Why does this boolean intersection create holes? Here's a screen recording of me trying to create the intersection
I'm hoping clip the terrain block mesh to the border map for 3d printing, but the result is missing all but the southern side. I've recalculated the normals and verified both meshes.
I'm not sure why it's happening here, but if there's another way to fill the side holes despite the complex shape, that would work too.
Here's the blender file if it helps (only the meshes near the origin are relevant)

I have similar issues with blender 2.8 boolean modifier, but "fast carve" free add_on works fine so far. It could be a glitch in controls / settings for me, not sure anyone will have another answer unless your file is wrong some how.


Sverchok The grease pencil is moving but not the polyline visual I'm very new to sverchok addon, and I want to use it in a really easy way.
But now I have a big problem:
I've parented my grease pencil layer to an moving empty, but the polyline visual effect of sverchok doesn't move with the empty. Is there a solution to this ?

https://gist.github.com/nortikin/c8716923f5d87773b25d417f1610d6dc
this is applying of matrix (4-th node from the left side)
It is simple one node


Cell Fracture not work why I get a cube with my model ?

model:

and result:

Thanks

Possibly because your model has non-manifold edges or other similar issues which prevent the Cell Fracture add-on to work properly. You can check for non-manifold edges in the model to be fractured by going in Edit Mode, activate the Edge Select Mode then deselect all (A) and type Ctrl+Shift+Alt+M.

To experiment it load Suzanne and try to cell fracture it; it won't work because of the previously described problem. Now, follow the steps above and you'll see where the problems are. When you have corrected them, try again the Cell Fracture and it should work fine. You may also search for video tutorials online on Cell Fracture for more information on its usage.


How to create wireframe fade off effect like this? Can this be done with freestyle lines alone? or do I have to render separate layers and do it in the compositor?

Various aspects of a Freestyle Line Style can be given modifiers, including the Alpha of the stroke.
The modifiers available to Alpha include Distance From Object. (In this example, the blue empty):

Which, with settings like this:

Can get a result like this:


Sculpture UV & Paint Issue I'll start this off by saying I'm new to this. I've tried to look this up, but I can't seem to figure out exactly what the problem is.

So, I made a sculpture watching a tutorial, and it turned out pretty cool! Being excited, I was hoping to try and paint some colors onto it. However, when I go to the UV Editor or the Texture Paint, only a couple of small patches are allowing the selection.

It has a high level of detail, but I'm not sure if that could be the issue. There's two patches on top and one underneath. Everything I have found thus far seems to either see all or nothing.

I'm sure this is something that I probably messed up to trying to move forward too quickly, but I appreciate any help in advance!

Thanks!

There is another way to quickly do the shading without the need of retopology and UV unwraping if are not going to animate the model. You can use the texture cordinate node to change the cordination from UV to project or other ways... then using some procedural or seemles textures and mix them together with a balck and white mask as a factor instead of texture painting. Highly recommend to watch the "Materials Made Easy - Non Destructive Shading in Blender" by Zacarist Reinhardt in Blender's YouTube channel from Blender Con 2018. (Sorry having internet problem I couldn't get you a link)


Making a shadeless card How do you make a shadeless billboard/card sort of material (with working alpha) in Blender Cycles? I just need to make the image/movie file show up shadelessly on a flat plane, specifically with an effect from the alpha channel.

Emission Shader + Alpha masking

Shadeless material in cycles can be obtained by using the Emission shader. For further instruction on how to handle all the interactions with other objects in the scene and dealing with shadow casting, I'll suggest to read:
Read Node for setting render colour, regardless of lighting

The alpha of the image can be used to control the shading property of the object by using as an input of a Mix Shader that mix the Emission shader and a trasparent shader.

Here's a possible node setup.


Two armatures. Two animations. Combine into one armature with both animations intact? Like the title says. I have two bones which each belong to different armatures. For exporting purposes, I need to have both bones in the same armature. However, when I join the armatures, one animation is lost. Pasting keyframes does not attribute to individual bones so that messes everything up. Help?

Thanks

Whoah I had to paste together a bunch of answers online but heres a start to doing just this:

create a new bone in the armature and use bone constraint to copy whatever attribute you need from the other armature bone. Then in pose mode, do pose -> animation -> bake action and THEN select

only selected
visual keying
clear constraints
overwrite current action - thats the one that missing from most answers online


Is lighting needed for a 3D model in blender if you are going to import it into unity? I'm making a 3D character in blender who has a hood over his head and I positioned the light in blender so you wouldn't be able to see his face because of the shadow of the hoodie, if I import this model into unity will the light effect that I used in blender be removed off the model.

depends on how you import it. you could import the blend file, that includes the lights, or you could export the model as an FBX.
either way, if you only place the model in the scene, the light won't be included, except if you place the entire blend file in the scene.
or you could parent the light to the model... if you want it to be included, but i recommend using the lighting from unity itself


i have a problem with my lasso tool i was watching a tutorial and making my first project (i'm new), and I've encountered this problem, my lasso tool keeps getting messed up and i don't know how to fix it, it is supposed that when i select something the tool looks like a square

but it looks like this when i try to use it

.

please help me as i am new to blender and its really bugging me how its changing every time
, i am not sure if i have pressed any button which is a shortcut to change a setting or something like that.

thank you.

The selection tool can be changed by

locating the tool bar in the top-left of the 3D Viewport (T if it is hidden)
long pressing on the selection tool icon (usually the arrow with the selection tool)
choosing the proper selection tool from the appearing menu


Vertex slide past edge limit? The first Vertex Slide tool took an additional click, but you could push the vertex beyond the end of the edge. Is there a setting or method to achieve that with 2.68?

The old method of placing the cursor at the opposite vertex and scale away from it is wonderfully nostalgic, but a bit time consuming.

Yes, by using the Clamp setting.

Access by holding Alt, or toggle with C. This allows you to slide past the (0-1) limit and also prevents switching to slide along other edges then the ones currently selected.

This information is available in the header text during vertex slide.


Emission Peculiarity I have a Sci-Fi city model. It's entirely square and therefore very modular.
It has been multiplied many times to give me enough background for a fast dogfight between two craft. To try to disguise the obvious repetition I want to make the lights of each city section a different colour from each other. The emission node of the copied first section is controlling the colour of every duplicated section, however. Adding an emission to each individual section isn't working - the node setup of the original section overrides all the others.
This is where my inexperience is being exposed - but hey, it's why we have help forums!
Naturally, a fix for this one will be splendid!
Many thanks.

There are two nodes that can be used to generate a random number within your node group.

Object Info -> Random generates a random number between 0 and 1 for each individual object.
Geometry -> Random Per Island does the same for each disjointed piece of mesh within an object.  So this one can be used with Array modifier, for example.

You can use these random values for many purposes.  You can basically seed your textures by changing the position of the texture in coordinate space, or drive the W value of a 4d texture.  You can also use a color ramp to define a range of colors to choose from.

The Math -> Multiply node can be used to effectively modify the range of the output.  E.g. multiplying by 20 gives you a random number between 0 and 20.


Create gridlines in Python I'm making my own Python routines that distort space. I would like to visualise the effect of this distortion. To this end I want to create {x,y,z} aligned gridlines, so that I can observe the effect of the transformation on them.

So an x-aligned gridline would be say 1000 points between x=-50 and x=+50 with y=z=0, and the points would be joined to one another by line segments.

How could I create such a gridline using Python?

I found resources such as:

Scripts/Cookbook/Code_snippets/Three_ways_to_create_objects
askubuntu.com/..../how-to-make-a-mesh-by-using-python-script-on-blender
stackoverflow.com/.../how-to-create-a-simple-mesh-in-blender

but in each case it creates primitives from verts+faces, not verts+edges

You can create a grid primitive and remove the faces:
import bpy
import bmesh

sce = bpy.context.scene

me = bpy.data.meshes.new("Grid")
bm = bmesh.new()
bmesh.ops.create_grid(bm, x_segments=32, y_segments=32, size=50)
bmesh.ops.delete(bm, geom=bm.faces, context=3)
bm.to_mesh(me)

ob = bpy.data.objects.new("Grid", me)
sce.objects.link(ob)
sce.update()

This will give you a grid at origin, dimension x/y 100 and with 1024 vertices.

from_pydata():

it creates primitives from verts+faces, not verts+edges

You can either pass two sequences for verts and faces, or you give it verts and edges - it should work the same.


Why does my texture image look compressed in the z direction on the side of this cylinder, but look perfect on the top? I have UV unwrapped my cylinder, and applied all transformations to the object, but I still get distortion on the side wall of my cylinder when I apply a texture image. I thought maybe this was simply because the cylinder's polygons are not actually square, so I tried scaling them in the UV editor but it didn't seem to do anything. I scaled them in the z direction in the scene as well just to see what would happen, but it made no difference. I also messed with the shader options. Changing my texture image mapping to Box helped a lot, before I did that the stretching/compression was much worse. I'm probably missing something rather simple, any help would be appreciated. I know there are other threads about this as well and I read through them and tried the suggested solutions but was unsuccessful.

Although I don't totally understand it, the solution seemed to be to change the texture coordinate to object, and select my cylinder as the target. :)


Duplicating uv vertices? I downloaded an already made model

while i was adjusting the model, and removing doubles a hole appeared on the mesh

when i tried to fill the hole i expected something like the right side of the picture, but got this

is there a way i can add a vertex like the right side of the picture?

In the UV editor:

Select all and Pin all UV coordinates
Select the UV faces that you have added
Reset UVs and Unpin them
Unwrap
Select all and Unpin


Automatic Weight problem I want to parent my character's pants to the armature, by pressing ctrl + P -> with automatic weights, but there's a problem with the pants after doing so...
What I tried so far:
Removed doubles
Recalculate normals
clear sharp
and also by manually painting weights, but when I brush weights, it still producing same results.
By the way I'm using blender 6.77a

Here's pictures

Can someone tell me what's wrong?Thanks!

Earlier, there was a question like this. You should try to rearrange the modifier stack, I'm pretty sure that's the problem. (or give us a screenshot of the stack if you are not sure how it should go)


How to make smooth transition lower and higher to flat How to make this kind of transition?

From lower and higher to flat surface smooth without creasing or pinching? I triedy to merge the end but I get deformations.

The answer to this problem is infallible, albeit extremely tedious: the thorough study of topology.

I'd recommend you start with this blog, a valuable resource.

For this specific situation, two basic rules apply.

quads should be as square as possible
quads should be evenly sized
quads should be evenly distributed

Everything else will produce pinching, which you want but only at the sharp ridge. At that position I will use some rectangles.

Use a (shiny, reflective) matcap with lots of details for previewing.

My topology suggestion is not perfect, at extreme angles the reflections show the disturbance in the underlying structure. It should be improved.


how do I copy fluid physics from one object to several How do I copy fluid obstacle properties to other objects.  I see that we can copy from active with ridgid body tools but this does not exist for fluid.
Right ?

An option that is available for many settings, not just fluid settings, is to right click  on the value and choose Copy To Selected. This will copy the value from the active object to all selected objects.


Cycles Render shows black screen I'm using Blender 2.92, and Cycles Render, and it rendered how it should, however after adding a fluid simulation, whenever I try to render an image, by pressing F12, it just produces a black screen, as seen below, however I can see my model rendered normaly as seen in the bottom picture, I have already tried changing the post-processing composition and sequencer options, I have also made sure to disable composition nodes and made sure that my nodes output what they should, and the camera is looking the way it should, I'm quite new so this is probably an easy fix that I missed; here are some things that may be important:

I'm only able to use my CPU for rendering currently.
My operating system is linux Arch.

Here is my blend file and everything it uses:
https://drive.google.com/file/d/1wnQ0gd-WJ30Zn52l_liXEngOIPrpIWry/view?usp=sharing

you disabled your whole collection for rendering. Enable it again and all will be fine.


Why do I get a "Permission Denied" error when importing an obj file? I'm extremely new to Blender. I literally just downloaded it, I was trying to import a .obj file however when I try I get the error message you see in the title. Any way to get around this? please help. Thanks.
I have the steam version.

You are getting this error because your user doesn't have permission to read the file. In your specific case, there dosen't seem to be a problem with the permissions of the file itself but rather with its containing directory.

To view or change permissions, right-click the file in Windows Explorer, click Properties, click the Security tab, and select your username in the "Group or user names" pane.
One workaround that doesn't involve fiddling with permissions is to copy the file to somewhere else with Windows explorer.


Render depth maps with world-space z distance with respect the camera I am trying to write the depth map of a scene in a 16-bit PNG, without any sort of normalization. I would like to pixels of such depth image to be set to the distance with respect to the camera, and of course the far clip plane value if no object present.

I tried with the following node setup, but I get values up in the PNG pixels which do not make any sense, in the range of [3100,65000] while my object is located rougly at 1 meter from the camera. Near and far clipping plans are 1cm and 10m respectively. I guess they are suffering some sort of normalization, but I cannot figure it out.

Thanks

Short Answer

If you are looking for accuracy, Do not save the Z pass as PNG or any other display referred format. OpenEXR is the only format that will allow you to use the linear information from the Z pass.

The only way to get a Z depth pass without distortion is by avoiding any kind of processing except [proper] inversion or normalization. Just plug the Z information to a file output node, and save as OpenEXR.

Long Answer

First let's separate the apples from the oranges:

The Z pass should not be thought of as an image, since its values do not fall into the parameters set for most image formats.

What is the Z pass then?

The Z pass is the absolute distance from the camera to objects in the scene for every given pixel on the image. The camera is the 0 on the scale and the units used for its values are the working units set for the scene (blender units, meters, cm, inches, etc). The minimum and maximum value are clipped according to the camera's start and end clip distances.

The Z depth values work in a linear scale, meaning that 6 will be twice as far than 3 and one half of 3 will always be 1.5
The Z pass is not meant to be viewed.

The main issue is that Z depth information, will generate values larger than 1 and image formats cannot deal with values larger than 1 (where 0 is black, and 1 is white)
What happens when you normalize the Z pass?

The minimum and maximum values are set as 0 and 1 respectively and all other values are spread in a linear scale in between.

The real effect of doing this is that the scale is both compressed and offset from the real values. The values for absolute distance are converted in relative values and from then on you have to do conversions to find what the real values are.
What happens when you invert the Z pass?

The maximum value is set to 0 and the minimum value is set to the maximum value. All other numbers in between are also inverted. Inversion is a reversible (invertible) operation (source)
Why do people normalize the Z pass then?

Because the information contained can then be viewed as an image, since it has values from  0 to 1 that can then be expressed as an image. Normalize only when  you want to make sure that the Z pass is working, or to use it on programs that cannot deal with the Z channel properly and need the information as an image in grayscale.
So why not PNGs or other formats?

Normalizing the image to make it fit on a 0 to 1 scale is really not the problem (because even though normalizing has moved the values for the scale, it has kept the values linear). But when you save as an image format you are re-mapping those values yet again to a very limited number of values. Saving to an 8bit format will result in 255 possible values, greatly reducing the precision of the information. Even on 16 bit where you can have a much larger different gradations from black to white (4096) you might find that values that are close together are no longer represented.

But the main reason not to use display referred formats like PNG is that those formats presume to be encoding values in sRGB, that is not a linear format anymore, but has a transfortmation curve in which 3+3 might not equal 6 anymore... The values will have been re-mapped yet again to a point that will not reflect the proper scale of the distances represented on the Z depth information.
How is OpenEXR different?

OpenEXR is a format that has been designed to store linear data and has no issues with values larger than 1. The information suffers no distortion and is as precise as when you rendered your scene in the first place.


UV - sharp edge and uv seams overlapping how can i disable sharp edges when adding uv seams because this is really confusing and annoying unlike in 3ds max when you are in unwrap editor automatically all of your selection is only for unwrap unlike in blender everything is there so it was confusing when you export it you thought that everything has its seams but eventually you know when baked there was error.

my eyes doubled sharp and seams at the same time, my works double because of this overlapping i always need to remove the sharp just to check if my uv seams are really applied on the mesh.  I hope you can help me for this its really frustrating an an-innovative. I shift from 3ds max because of blender is free but I might go back to 3ds max because its not really that nice to have this very simple yet it makes complicated.

When you are in edit mode you press N. Then search for the box called Mesh Display under Overlays you can uncheck the options you want to hide.


Bevel modifier stops to work for diagonal faces Here the bevel modifier works well:

But moving the selected edge, which would perfectly work for a non-beveled shape, makes the bevel progressively enlarge one of its curves, even if the mathematics say that the enlargement should be much smaller:

The object is symmetric towards a YZ plane. The bevel has options loop slide/angle/arc/shape/grid fill. With other options, as far as I tested, it works similarly or worse.

Is it possible to have the shape well-beveled in Blender 2.82?

Welcome to Blender Stack Exchange!

There are a couple of things to try here.

First, select everything in edit mode and press ShiftN to recalculate the normals. Sometimes Blender gets the direction the vertices are facing confused, and this causes issue with beveling.

Second, try and get rid of the 'ngons', aka faces with more than 4 vertices. Beveling ngons is always a bit risky, and when you start moving things around it's not uncommon to see issues pop up. Insetting the ngons with I is a possible way to get some nice quads along the edge of your bevel.


Sverchok Vector Interpolation Example Hey I'm super new to sverchok! So I'm trying to learn how you take two lines and interpolate them into a plane like they do in the example within the sverchok docs (https://sverchok.readthedocs.io/en/latest/nodes/vector/interpolation_mk3.html). However, the views of the node systems aren't entirely present in the pics and I can't seem to replicate the final plane. I can get the sine output, that much is easy enough. If somebody could show me how the second part of the example is done I'll send them a virtual kiss.
Thanks

on this picture there are two nodes with UV parameters


Help with rough Shading in blender I'm trying to make a shading in blender 2.8 that looks like the handle of the Glock
like in the picture


Mesh Bisect Algorithm: How does it actually work? So Ive been writing some C# algorithms for bisecting a mesh in Unity but I had a hard time finding any information on the best way to do this.  I love blender's mesh bisect tool and this is basically exactly what I want to implement in C#.  Im wondering if anyone knows how blenders algorithm works in terms of performing the cut (projecting the vertices, reconnecting edges and rectifying the new triangle normals), filling in the created holes with new faces and preserving the UVs as well as mapping the newly created UVs.  Not sure if blender's script for this is available but if anyone can even outline the process in pseudocode id really really appreciate it!  Im particularly interested in how it handles concave meshes and how it deals with filling multiple holes (such as bisecting a torus) as my current algorithm can handle convex meshes only.

Thanks guys!

As you might have heard, blender is open source software, which means the full source code is public. You can download the source code for example from blender's official download page. (Link on the same page above source download leads to info about setting up dev environment and such, if you have more interest on project)

For particular file inside the project, bisect tool is found under source / blender / bmesh / tools / bmesh_bisect_plane.c/h.


How to unlink / remove an object from a scene? There is an object shared between Blender scenes. So the same object appears more than one scenes (see below).
Is there a way to unlink the object from a specific scene? In my case I would like to remove the Cube.001 from Scene.001.

There is Make Links - Object To Scene command and we can use it to add objects to another scene (see below). So I search for kind of an opposite action.

While the active scene is Scene.001 select Cube.001 and press X. You can also right-click   on the object in the outliner and choose Delete.

Deleting an object only applies to the current scene, any other "copies" in other scenes will still remain there.

You can link the object back to Scene.001 by selecting it in Scene and pressing ⎈ CtrlL->Objects to Scene->Scene.001

You can also remove the object using python, you can type the following into blender's python console or paste it into blender's text editor and click run script. Changing unlink to link will let you replace the object back into Scene.001.

bpy.data.scenes['Scene.001'].objects.unlink(bpy.data.objects['Cube.001'])


How can I reset all custom properties into a "Redo Panel"? I have a "Redo Panel" with some custom properties and an operator at the end, from which I want to reset all custom properties at their default values. How can I do that?
Here is an example of my code:
class FU3DM_OT_ModelPrefs(bpy.types.Operator):
    bl_idname = "fu3dm.model_prefs"
    bl_label = "Model"
    bl_description = "Blah blah blah"
    bl_options = {'REGISTER','UNDO'}

    gender : bpy.props.EnumProperty(name="Gender", description="Choose model's gender", items= [('OP1', "Male", ""), ('OP2', "Female", "")], default='OP1')
    head_male : bpy.props.EnumProperty(name="Head", description="Choose model's head", items= [('OP1', "Generic Male", ""), ('OP2', "Male", "")], default='OP2')
    head_female : bpy.props.EnumProperty(name="Head", description="Choose model's head", items= [('OP1', "Generic Female", ""), ('OP2', "Female", "")], default='OP2')
    eyes_color : bpy.props.IntProperty(name="Eyes Color", description="Choose model's eyes color", min=1, max=10, default=1)
    skin_color : bpy.props.IntProperty(name="Skin Color", description="Choose model's skin color", min=1, max=10, default=1)
    models_show : bpy.props.BoolProperty(name="Show Model", description="Show or hide models", default=1)

    class FU3DM_OT_ResetAll(bpy.types.Operator):
        bl_idname = "fu3dm.reset_all"
        bl_label = "Reset"
        bl_description = "Blah blah blah"
        bl_options = {'REGISTER', 'UNDO'}

        def execute(self, context):
            # ???
            return {"FINISHED"}

    def draw(self, context):
        layout = self.layout
        # ...
        row = layout.row()
        row.operator('fu3dm.reset_all')
        # ...

    def execute(self, context):
        # ...
        return {"FINISHED"}

Ditch your operator and use the one designed for this.
As a suggestion, add imports and register etc to question code, to make a minimal run-able example.  This would only be a couple of lines and is appreciated by those answering not to have to do this themselves. (It adds up)
There is no need to re-invent the wheel and write a new nested operator to reset the defaults of another. Simply use the one designed to do this.

bpy.ops.wm.operator_defaults()
Set the active operator to its default values

eg in the layout of the operator to restore defaults.
layout.operator("wm.operator_defaults")

Would strongly consider looking at the 'PRESETS' system for operators, or using addon preferences to set and save preferences.  Reset to defaults and settings prior are lost. Blender will start with the defaults.
As mentioned in comments the reset single or all to defaults is available via context menu (right click over property).
To have an operator always invoke with defaults see Force a Blender operator to always start with default values


Green screen transparent layer questions video editing I have two (newbie) questions:

1)I have made a green screen video transparent in the compositing-tool. But when I am rendering this image (without a background image) and I am trying to place this in the normal video editing tool, it is not transparent. Did I do something wrong? Can I only render a green screen video with a background image? Or are there settings to do this?

2)I have downloaded a green screen video with smoke. But this smoke is too white, it would like to have the opacity 50% or something. Is that possible?

Thank you

Try exporting with ffmpeg, using RGBA(A for alpha), Container: Quicktime and Codec: PNG.


Semi-realistic skin texture I'm working on a human model, and so far I'hv been using a single color for the skin texture, which obviously doesn't look realistic at all... Anyone having some tips or tricks to make a realistic - or just semi-realistic (animation-style-realistic - skin texture? Or maybe you know a place, where I can download a texture-picture big enough (Very high definition) to cover a whole body.

Welcome to the Blender community. If we want to make a texture that is high enough resolution to work on a body, we would usually use either Substance Painter or Substance Designer, or if you're really in a rush Bitmap2Material. Algorithmic software is, far and away, the best stuff on the market, and you can even get it free if you are a student.

For your purpose, there are two strategies I would consider.

One, you could import your completed model into substance painter and build/use the default smart material to create a convincing skin shader. You will be able to change things like the color, subsurface color, normal intensity, etc, without having to make your own smart material. Be sure to bake out a world position normal and set the projection mode to tri-planar mapping to avoid seams.

The advantages to this approach is that there will be no seams on your mesh, but you will have to be certain the geometry is final, and this step will have to be repeated if you change your model or your unwrap.

Or, you could use noise maps and seamless mathematical functions with Substance Designer to create a seamless texture with whatever resolution you want and map it onto your model with seams.

Every time, professionals will choose the first strategy.

As of now, there is no way to do what you described in Blender.


How would I fade out the edges of a plane, in Cycles? So, I have a render I am working on. It has an ocean plane, and then since I don't want really long render times, there is a regular plane that extends out to 10km. I want this plane to fade out to transparent near the end so I have a nice transition to the horizon (sky texture)

How would I set up the nodes so I can get the edges of the plane to gradually fade out?

You would just mix the main shader with a Transparent shader using a mix factor driven by a gradient texture.

Here's a slight expanded version with an ocean plane and adding a Dif/Glos shader to the ocean surface before blending in the transparency.


Modeling a crease on a helmet I'm modeling a helmet from a 2D image but can't figure out which way to go about making this crease. I started with a UV sphere and mirrored it then started to drag faces to create the general shape which worked great but as soon as I started on this crease I got stuck.  Any suggestions on if I should start from a different object or how a more experienced modeler might go about doing this would be greatly appreciated.

You want an edge loop to follow that crease. Something like this:


If each cube here represents a pixel, what is the fastest way to change its color so it looks exactly like the 2d image? Hi people, my goal here is to read the 2D images pixel intensity and transfer those values to the corresponding cubes I made in Blender. The image is 28px by 28px.

My first question is if I already extracted the pixel values from the 2D image how can proceed and transfer its value to the cubes? For each cube, I should first create a texture correct? Then I can simply write a loop to copy over each corresponding value to replace the texture color?

Second question would be can I set the color for each cube in blender to only gray scale? Its will be much easier that way.

The third question is, is there something faster like grouping all texture values into a matrix, then set all the values to 1s, finally we just do a matrix multiplication to change all the values at once? If I read the image with Pillow and numpy I can get an array back so I don't have to loop 28x28 times.

Can someone give me some advice? I am currently using Blender 2.8 and would like to run this in realtime with Eevee.

For a better idea on what I am trying to do in Blender please check out this video.

https://youtu.be/3JQ3hYko51Y?t=15

I am basically going to do the same thing but visualizing a different network structure.

This is the fastest way:
1. add a cube
2. add two array modifiers to x and y axis and apply them
3. go to edit mode, use orthagonic view (num5), hit "u" and select "projection from view (boundary)"
4. hit "p" select "by loose parts"
5. go back to object mode, select everything and hit ctrl+shift+alt+c and select "origin to center of mass"


Animation of several objects depend on main object I would like to animate a clothed human model. The human geometry is rigged, but I dont know how to add additional objects to the human rig.

I want the t-shirts and pants movement to follow the human's poses.

It is possible to parent multiple objects to the same armature. Simply repeat whichever method you used to parent the human to the rig on the clothing.

For example: Select the clothing and then shift select the rig and press "Ctrl + P" and then select "Armature Deform with Automatic Weights".


Weight painting. Should this be happening? I was making an animation of the folding of a paper plane. The weight paint seemed like it was deforming the mesh uniformly, despite the fact that there was a gradient in the weight paint. To model this, I created a simpler version of the effect I want to achieve with a plane and a single bone. The weight paint does the same in this case as well:
The plane with its weight paint before transformation.

The same plane with the bone moved along the Z axis.

I thought the bone was supposed to alter the shape of the plane more gradually. Wasn't it supposed to form more of a domelike mesh?
Am I doing something wrong, or did I misunderstood the purpose of the weight paint?

The .blend file.

The difference between weights happens when a vertex is assigned to at least two bones, because Blender normalizes the values: in your example every weight is compared with zero weight on any other bone, resulting in full strenght for every vertex.
If you create a new bone and assign her an equal weight to all the vertices, move only the first bone and you'll see the gradient expected.


Smooshing faces against each other: Making features coplanar, while preserving surrounding geometry How can I make the base of the pyramid coplanar to (smooshed up against, so they are flat against each other) the slanted face of the wedge (pictured below)?

The objects and their origins need to stay the same.
If all of the pictured geometry were part of one object, and #1 was not a requirement, how could this be achieved? (If this were a mesh level transformation instead of an object level transformation)

Multiple objects:

For this you can use custom transform orientations again:

Select the face and press ⎈ Ctrl⎇ AltSpace:

In object mode, select the object you wish to align and press Align to transform orientation in 3D view > Header > Object > Transform:

Once the object is aligned, use transform snapping with face as the snapping element.

If the bottom of the spike thing is already the closest face to the target, then closest should be fine as the snapping target. If not, use the 3D cursor trick as explained here.

I think you should be able to use transform snapping for rotation too, but for no apparent reason there is an inexplicable gap when snapping without a pre-aligned model..

I've reported this as a bug.

Single mesh:

A similar approach to this can be used:

A custom transform orientation aligned to the target face will help too.


uv_textures.active.data[0].uv equivalent in Blender 2.7? I'm trying to update a 3rd party addon from Blender 2.6 to 2.7, as the author won't do it.
The only problem I have is here:

ActiveUV = BMesh.data.uv_textures.active
for iFace, BFace in enumerate( BMesh.data.polygons ):
    FaceUVs = []

    if ActiveUV != None:
        for UV in ActiveUV.data[iFace].uv:
            FaceUVs.append( [UV[0], UV[1]] )

And I have this error message:

  'MeshTexturePoly' object has no attribute 'uv'

I've tried with:

BMesh.data.tessface_uv_textures.active

But it returns 'None'

And with:

BMesh.data.uv_layers.active

But It doesn't seem to be the right one.

Ok, I've found a solution, maybe not the optimum one, but it works:

for iFace, BFace in enumerate( BMesh.data.polygons ):
    FaceUVs = []

    for i in BFace.loop_indices: # <-- python Range object with the proper indices already set.
        l = BMesh.data.loops[i] # The loop entry this polygon point refers to.
        for j,ul in enumerate(BMesh.data.uv_layers):
            FaceUVs.append( [ul.data[l.index].uv[0], ul.data[l.index].uv[1]] )


How to activate an action after another action happens I made a camera action using Blender Game engine and set it to run at the beginning of the game now I want to activate another action after this action is done

In the Action Actuator you can set a property which reflects the current action frame. You can then check its value and start the second action when the end frame of the first one is reached.


Problem with planes intersecting in veiwport Using Cycles in Material Preview mode and planes that intersect each other display oddly - one plane displays fully and ignores the fact part of the other plane should be showing. Better explained in the image below.

How do I get them to act how they do in Solid view where they appear how I would expect them to:

Couldn't find an existing question for this, expect it's something obvious I'm missing.

This looks like an "alpha clipping"  issue.

Your planes look like they have an image texture applied to them. If this is correct and the image has an alpha channel (for transparency) then try setting the Material Properties > Viewport Display > Blend mode to Opaque.

Example Plane textured with an Image with an Alpha channel:

Or even better Open the image in Gimp or Photoshop and remove the Alpha Channel ( Gimp : Layer > Transparency > Remove Alpha Channel

Edit to add a couple more screenshots after Hienronymous's comment.

The Show Backface option is not available when Blend Mode is set to Opaque but there when Blend Mode is set to the default Alpha Blend
Which (probably) makes sense since the two seem to preform similar functions.

The Blend Mode  Opaque "Renders surface without transparency" and with Show Backface deselected "avoids transparency sorting problems".


How to get the length of an mp4 video inside a node? Work with python in blender 2.8 , i try to find a command for get the lenght of an video inside at image node.

ob = bpy.context.active_object
nodes = ob.active_material.node_tree.nodes

    for n in nodes:
        if n.name == "Image Texture":
            if n.image:
                video = n.image
                ##print(video.lenght)##

The length of a video file is stored in the frame_duration property.

num_frames = n.image.frame_duration

If you wanted duration in time, divide the frames by the fps property.

seconds = num_frames / n.image.fps


Generating 1000s of objects are really slow, how to optimize it? I am making this BPY script that basically generate boxes based on Vox file format for Magica Voxel.

With my script, I am reading the position of each voxel and generate a Cube, as the number increases, over 2000 Blender started to become really slow.... I am only generating 8000 objects here, but possibly more.

I know the fact that Blender cannot have too many objects in the scene.

For what I am doing, what would be the best options? In reality, I could probably try generating a single mesh with point positions, for which I can use Dupli Verts for instancing the Box.

But is there other technique?

Is it much more efficient for Blender to have 10000 empty or objects under a single object?

I figured out that generating lots of objects is not the way to go. Instead we should always think of ways to merge the objects into a single object, however still having all the data and values needed.

In case of VOXEL and Magica Voxel or Drububu, my solution is to deal with Position, Color, to represent a Box of Voxel, and instance it thousands of times, however to always keep everything as a single object.


How do I create 2 Edge Loops adjacent to selected Edge Loop? I'd like to know if there are any techniques or addons available for creating adjacent edge loops in a mesh based on a selected edge loop. The functionality would be similar to the Offset Edge Loop Tool in Maya.

The goal would be to find a way to do this programmatically from python, and not interactively by hand.

'Beveling' should achieve what you want. Select the edges you want to add other edges around and press Ctrl+B to bevel:

Increase the 'bevel segments' by either scrolling the mouse wheel up while bevelling or change it in the toolbar (T) after beveling to keep the original edge.

As to how you would do this programmatically you might start with this:

bpy.ops.mesh.bevel(offset=0.5, segments=2, vertex_only=False)

(Though it might be better to try and find an alternative to bpy.ops.., see this)


Why can't I subdivide? Sometimes, when I add a face with the "F" key in Blender, I'm unable to subdivide that face further. For example, observe the following video:

https://www.youtube.com/watch?v=T9UkpsXGVd8&feature=youtu.be

Why am I unable to subdivide that face? What should I do to be able to subdivide it? I'm using Blender 2.81.

Blender is subdividing the edges on the outer edge of the face, but it isn't filling in the grid tiles for you.

If you want to fill in the top face with a grid using the subdivided vertices, first delete the top face. Then select the top edge loop, and press Ctrl+F then select Grid Fill.


Brightness varies between texture image and UV or edit mode I'm facing a problem I'm currently not able to solve on my own. I created a sign with blender and wanted to texture it. As you can see in the following picture the brightness of the object within UV or edit mode is much lesser than within the preview of the image of the texture.

I tried to reproduce this problem on another project but without success. So obviously I did a mistake somewhere I can't find. May some of you guys know why my object is much darker than the brush looks like?

Cheers

It looks like you completely baked your textures before you set up any (or enough) lighting. Therefore the texture (in its normal form, as seen in your red "texture image" box) was evaluated in the dimly lit scene you use. Then you used that as the material texture, which is also why the same darker texture is visible in the "textured view". To solve this you could bake again but after setting up some lighting or just bake with different settings for example only bake "textures" (without shading) Make sure you only bake "textures" https://docs.blender.org/manual/en/latest/render/blender_render/bake.html

If this doesn't solve your problem maybe look for a wrong node in your material setup or provide your .blend file, since there might be other problems with the same symptoms.

Happy Blending! :)


How can I make fire in BGE? I've seen a lot of tutorials with fire in Blender Game Engine and how they have particles. They're great and all, but when I go ahead and try to make it this is what it says.

I can't use particles, and there are absolutely no tutorials for fire in Blender Game Engine for 2.79 (my version), and none from 2016 - 2017. I really need help.

Blender

Blender particles are not supported by the BGE. Due to the complexity and inefficiency they will not be supported in the near future (at least not in a way that they can be useful in a game).

BGE Particles

Particles in the BGE are ordinary objects. They are nothing special. All you do is you dynamically create a lot of them.

A simple way is to use the Object Actuator in Add Object mode. When activated the actuator will add a copy of the referred object.

To get flames, sparks and smoke you add different objects. Each object can animate over time (position, location, material). This all together can create the illusion of fire.

Due to the complexity of that topic I do not want to go into much detail here.

I suggest to search for BGE fire tutorials. There should be plenty out there.

Pre-rendered textures

An alternative / additional way is to use textures with pre-rendered and animated flames.


Baking a normal map from a sharp edged model to an identical smooth model I'm in the process of making a video game, and I currently have some low-poly models that have sharp edges where necessary to make them look good acceptable.

For a shader I'm trying to implement, it's absolutely necessary to remove all sharp edges. I still want it to LOOK like I have sharp edges, so I turned to normal mapping. Basically, I want my model to have soft edges, and bake a normal map to it with hard edges. I've tried this by doing the following:

I duplicated my model
I moved the duplicate to another layer (on the exact same location)
I set all the edges of the duplicate to "Smooth"
I selected the Original model, and then shift-selected the duplicate. They were both selected, with the smooth duplicate being the active object
I clicked "bake" (before going through all these steps, I created an image, and set my baking settings like so (I've set both the distance and bias to different values just to try it out, but nothing seemed to work):

These are the steps that I went through, and I expected to see a normal map that shows hard edges at multiple places, including the collar of the model.
However, the entire normal map is one color, which leads me to believe hard edges may not be baked:

I've seen plenty of tutorials, but all that I found is about baking a sculpted model onto a low poly model. Because these models are actually identical, I wonder if what I'm trying to do is even possible. Can anyone tell me what I'm doing wrong?

Alright, I made a big mistake. I copied the workflow from a tutorial I found, but as it turns out, it's not exactly a good idea to put the meshes on different layers.

I moved the meshes to the same layer, and got result that perfectly matched my expectations.

Let's hope this helps someone in the future.


How is convergance plane distance used in side-by-side stereo 3D? I found that the convergence plane distance is extremely important to Anaglyph 3D rendering, in terms of how the result looks.  However, I created this blend file at pasteall in order test it for google cardboard, and I rendered the file in side-by-side mode (be warned it will still preview in anaglyph mode) and it appears to have very very little effect on the result.

As you can see there are keyframes placed on the plane; render it as a video with blender render.

How, exactly, and I supposed to use this plane for normal color side-by-side rendering?  Thanks in advance.

From what I know now, the convergence plane distance is the distance between the projector and the image being projected as written in blender. In fact for the anaglyph preview you can change it by clicking on the window tab/3d view and select side-by-side.

This setting seems to be used if you have some headset display. If you type the N key and go to Stereoscopy you can choose Left/Right or 3D that shows both. Now the interocular distance is the actual distance between the cameras as shown in the print screen.

Blue and red represents both cameras and the darker rectangle is the convergence plane distance

A setting that Blender suggest is the convergence plane distance/30 for the interocular distance.

Source: http://blender.org/manual/fr/render/workflows/multiview/usage.html


Help on Themes. Unable to change color of attached section I just started learning blender yesterday. I was customizing the themes but I am unsure as to what section is the following (with the dark gray background and black text). I am unable to read my layer names clearly.
Thanks!

The Dope Sheet > Channels (ThemeDopeSheet.channels) option modifies the background for the channel entries.

The text for the unselected channels is defined by Dope Sheet > Theme Space List > Source List Text (ThemeSpaceListGeneric.list_text).


Why are these buttons performing the same operation? I'm writing a simple script that will help me use Blender better.
One script sets everything up that's needed for retopology. The second just makes a hexagon and fan fills its face.

Individually, I can get these scripts to function correctly, but when I add them both together, or when I add them as separate scripts, the one that executes first will be the operation that both buttons will be caused to execute.

bl_info = {
    "name": "Dope Tools",
    "author": "Digital Dope",
    "version": (1, 0),
    "blender": (2, 79, 0),
    "location": "View3D > Add > Mesh > New Object",
    "description": "Adds several features to blender that I need",
    "warning": "",
    "wiki_url": "",
    "category": "Add Mesh",
    }

import bpy
from bpy.types import Operator
from bpy.props import FloatVectorProperty
from bpy_extras.object_utils import AddObjectHelper, object_data_add
from mathutils import Vector

class AddRetopoSU(Operator, AddObjectHelper):
    """Create a new Mesh Object"""
    bl_idname = "mesh.add_object"
    bl_label = "Add Mesh Object"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.ops.mesh.primitive_plane_add(radius=1, view_align=False, enter_editmode=False, location=(0, 0, 0), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))
        bpy.ops.transform.rotate(value=1.5708, axis=(1, 0, 0), constraint_axis=(True, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
        bpy.ops.transform.resize(value=(0.1, 0.1, 0.1), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
        bpy.ops.object.modifier_add(type='MIRROR')
        bpy.ops.object.modifier_add(type='SHRINKWRAP')
        bpy.ops.object.modifier_add(type='SUBSURF')
        bpy.context.object.modifiers["Mirror"].use_clip = True
        bpy.context.object.modifiers["Mirror"].show_on_cage = True
        bpy.context.object.modifiers["Subsurf"].show_on_cage = True
        bpy.ops.object.editmode_toggle()
        bpy.ops.transform.translate(value=(-0.100995, 0, 0), constraint_axis=(True, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1, release_confirm=True, use_accurate=False)
        bpy.context.scene.tool_settings.use_snap = True
        bpy.context.scene.tool_settings.snap_element = 'VERTEX'
        bpy.context.scene.tool_settings.use_snap_align_rotation = True
        bpy.context.object.show_all_edges = True
        return {'FINISHED'}

def add_object_button(self, context):
    self.layout.operator(
        AddRetopoSU.bl_idname,
        text="Add Retopo",
        icon='MOD_SHRINKWRAP')

class AddHex(Operator, AddObjectHelper):
    bl_idname = "mesh.add_object"
    bl_label = "Add Hexagon"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.ops.mesh.primitive_circle_add(vertices=5, radius=1, fill_type='TRIFAN', view_align=False, enter_editmode=False, location=(0, 0, 0))
        return {'FINISHED'}

def add_Hex_button(self, context):
    self.layout.operator(
        AddHex.bl_idname,
        text="Add Hexagon",
        icon='MESH_ICOSPHERE')

def register():
    bpy.utils.register_class(AddHex)
    bpy.types.INFO_MT_mesh_add.prepend(add_Hex_button)
    bpy.utils.register_class(AddRetopoSU)
    bpy.types.INFO_MT_mesh_add.prepend(add_object_button)

def unregister():
    bpy.utils.unregister_class(AddHex)
    bpy.types.INFO_MT_mesh_add.remove(add_Hex_button)
    bpy.utils.unregister_class(AddRetopoSU)
    bpy.types.INFO_MT_mesh_add.remove(add_object_button)

if __name__ == "__main__":
    register()

Give it a unique bl_idname

Both operators have the same bl_idname = "mesh.add_object". When you register you are effectively overriding the first with the second.

Give it a name like

bl_idname = "mesh.add_retopo"

and call it in code with

bpy.ops.mesh.add_retopo()

or use its, now unique id in the UI layout.

layout.operator("mesh.add_retopo")

Links.

Why does operators bl_idname have to contain 1 dot?


Can't enable an addon I have installed an addon Space engineers modding addon, but cannot check the box to enable it. I get this error on the console:

fake_module: addon missing 'bl_info' gives bad performance!: 'C:\\Users\\Besitzer\\AppData\\Roaming\\Blender Foundation\\Blender\\2.66\\scripts\\addons\\install.py'
Error reading file as UTF-8: C:\Users\Besitzer\AppData\Roaming\Blender Foundation\Blender\2.66\scripts\addons\release_scripts_wings_import.py 'utf-8' codec can't decode byte 0xc4 in position 26: invalid continuation byte
Traceback (most recent call last):
  File "D:\Programme\blender-2.66a-windows64\2.66\scripts\modules\addon_utils.py", line 269, in enable
    mod = __import__(module_name)
  File "C:\Users\Besitzer\AppData\Roaming\Blender Foundation\Blender\2.66\scripts\addons\space_engineers\__init__.py", line 25, in <module>
    if not reload('utils'): from . import utils
  File "C:\Users\Besitzer\AppData\Roaming\Blender Foundation\Blender\2.66\scripts\addons\space_engineers\__init__.py", line 20, in reload
    importlib.reload(modules[module_name])
AttributeError: 'module' object has no attribute 'reload'

this part of the error message appears multible times in the console:

fake_module: addon missing 'bl_info' gives bad performance!: 'C:\\Users\\Besitzer\\AppData\\Roaming\\Blender Foundation\\Blender\\2.66\\scripts\\addons\\install.py'
Error reading file as UTF-8: C:\Users\Besitzer\AppData\Roaming\Blender Foundation\Blender\2.66\scripts\addons\release_scripts_wings_import.py 'utf-8' codec can't decode byte 0xc4 in position 26: invalid continuation byte

Anyone knows how to fix this?

Looking at your Console log, it seems pretty obvious that you are using Blender 2.66. The addon (as stated on the SE Block Tools homepage) needs Blender 2.75 or later.


What Free 2D CAD programs can export to Blender? I find it very difficult to use curves in blender. I used to use Corel Draw X4 but it does not work on windows 10. Is there a free program which I could use for 2D drawings which could then be exported to blender ?

I understand anything that will export/save 'SVG' files. SVG can be imported into Blender. There's quite a few questions about how Blender treats SVG in here.

An SVG option under save/export has rapidly become fairly standard for most vector drafting applications. I'm not up on the free stuff right now, so I'm afraid you'll need to do the leg work to find out which one's will save SVG files. Hope this helps.


Changing selection around a mesh object I have selected some faces one one side of this object. How can I move that selection around the object to the other side, or how can I change the selection to select the same faces on other side?

I want this selection on the other side of cube.

First off, there is no way to rotate or move the area where the selection is. The selection is selecting something whether it be objects, vertices, edges, or faces, you have to select something.

Going from your picture, and using the view in that picture; selecting the faces on the other side will be easy.

Change to wireframe view, in the 3D view header, or by pressing Z.
Use Border Select B to select the same area that is already selected. However in now wireframe both sides will get selected.
Change the view back to solid view, again by pressing Z. Now use border select, but instead of pressing with the LMB , use the MMB . That will unselect everything that is inside of the box.


How to activate different tool gizmos with shortcuts? When I use S, R, or G it allows me to interact with the object in all directions but I would like that those commands just activate the respective manipulator.

thank you for your answer! I've found a solution
Just Right-click on the move, rotate and scale buttons, then "assign shortcut" and you add the respective command


The subpane for any modifier does not appear in my version of Blender I am new and novice at Blender (version 2.79 under Mac OS 10.11.6 El Capitan).
I am just trying to intersect a cube and a cylinder. I get them to overlap, select the cylinder then I hit the spacebar to get to Add modifier. I select Boolean and ...nothing happens.
No subpanel with information or asking to click on the cube. Nowhere to decide what boolean operation to perform.

I lost half a day looking on line for tutorials, but got nowhere. I suspect this is a bug.
Can anyone help me ?
Thank you
Alain

Your Modifier properties will be under this tab.


Define position by 3 Euler Angles and Radius I want to set the position of an object, using only the 3 Euler angles and a radius. I couldn't find any equation online, and mine doesn't work at all.
Where can I find it?

Thank you!

3 euler angles and a radius is not enough values to accomplish what you want. If you added an AXIS, than that may help, but then you also need the axis. If you say X axis, well that really means (1,0,0). After rotation with your euler angles will transform that (1,0,0) to something else. Then you can multiply by scaler distance to get the point you are looking for.

import mathutils
from math import radians

vec = mathutils.Vector(0.0, 0.0, 1.0))
eul = mathutils.Euler((0.0, math.radians(45.0), 0.0), 'XYZ').to_matrix()
scalar = 10.0

vec = vec * eul
position_of_object = vec * scalar


Is it possible to copy text settings? I want to change multiple text objects at once.

Is there a way to copy the settings to all selected text objects?

This script will enable you to copy the text object properties from active to selected :

run the script once to register
you will find it in: 3D View -> object ->copy text properties
or  hit space and type  'copy text '

import bpy
from bpy.types import Operator  # for defining new operator
from bpy.props import *   # for operator parameters

S = scene   = bpy.context.scene
C = context = bpy.context

def text_prop_copier():

        if context.active_object.type != 'FONT':
            return False

        active = bpy.data.curves[context.active_object.name]

        for ob in context.selected_objects:
            if ob.type == 'FONT':
                text = bpy.data.curves[ob.name]

                # collect names of writeable properties
                properties = [p.identifier for p in active.bl_rna.properties if not p.is_readonly]

                # copy those properties (prop != 'body') will skip from setting body property same as active object this changes all other properties but text content

                for prop in properties:
                    if (not prop.startswith('texspace') ) and (prop != 'name') and (prop != 'body') :
                        print(prop, 'copied')
                        setattr(text, prop, getattr(active, prop))

        return True

class   tex_prop_cop(Operator):

        """copy active text object properties to selected"""
        bl_idname = "fonts.prop_copy"
        bl_label = "copy text properties"
        bl_options = {'REGISTER', 'UNDO'}

        def invoke(self, context, event):
                if text_prop_copier():
                    self.report({'INFO'},"properties copied")
                return {'FINISHED'}

def addObject(self, context):
    self.layout.operator(
        tex_prop_cop.bl_idname,
        text = tex_prop_cop.bl_label,
        icon = 'PLUGIN')

def register():
    bpy.utils.register_class(tex_prop_cop)
    bpy.types.VIEW3D_MT_object.append(addObject)
    print("register done")

def unregister():
    bpy.utils.unregister_class(tex_prop_cop)
    bpy.types.VIEW3D_MT_object.remove(addObject)
    print("unregister done")

if __name__ == "__main__":
    register()


How can a Diffuse material not be effected by light? I downloaded a model from blendswap.com and when I rendered it I got this -

The scene is made up of: the model, plane, hdr map and hemi lamp that is lighting the object. As you can see, the ground plane is not effected by the light. Its node setup is this -

Why is the plane not effected by the light? I even replaced it with other lamps but the effect is the same. Why? How is that done?

This is simply done by setting the color to black. The light of a diffuse material with a roughness of 0 is calculated using the Lambert lighting model.
This model calculates the light that an object reflects as follows:

where  is the intensity of the diffusely reflected light,  is the material's color and  is the intensity of the incoming light,  is the surface's normal vector and  is the normalized vector from the surface point to the light source.

For typical colors  this will give you light areas where the surface faces the light source and darker areas where the surface points away from the light source. But since in your material the color is a pure Black (RGB (0,0,0)) the red green an blue light component will always be multiplied by 0. Thus the resulting surface color will always be black as well, no matter how strong the lightsource is.


How Texture Paint over assigned material I have a problem with painting. I don't know what am i missing.
The mesh becomes black and the colors do nothing when i try to paint on it.

Also is it possible to assign a diffuse color and to paint over the material like this?

You have your image texture also loaded as a brush texture, so you are painting black on black. Press the little X to remove the texture from your brush and see if that doesn't help.


Blender VSE proxies show the bad video I'm editing my first film project in Blender VSE. I had big problems with replay due to my phone's camera using a strange video codec, but this answer fixed it. I've set the proxy option for all strips and generated them and since I care about replay speed and not about preview quality, the proxies are at 25% size 30% Jpeg compression.

The problem is: Blender really likes one of my strips. It's always the same and I don't know why Blender chose exactly that one, but very often during replay the editor shows that strip instead of the actual one. This may happen during a whole strip or just for a few frames scattered around the strip and is really annoying. It usually goes away by refreshing the proxy or turning off proxies for some while, but not always.

Does anyone know why this is happening and how to work around it? I sadly can't upload any examples.

EDIT:

I just found that in the BL_proxy folder there was not only one subfolder per strip, but one more called proxy_misc having the subsubfolder named 25 in it. That one contains all frames of the problematic strip I see all the time in single jpg pictures. I am pretty sure that it is the cause of my problem, but why is it there and what does it actually do? Are there any documentations on what files Blender generates for creating the proxies?

Under the "Proxy/Timecode" for the problematic video, change Storage from "Per Strip" to "Project", then rebuild proxy and timecode. Worked for me.

Edit: it stopped working again. i have the same problem


How to add Objects to a scene AND to a list? (Sphere Packing) I want to add several spheres (rocks) to my scene to create this image:

To achieve this look, I have to pack the spheres. And I want to do it in python.
That's my plan:

Define the radius of the circle; the number of spheres to pack
Add a sphere at a random location inside the sphere. Add this object to a list as well
add the next sphere; check if the sphere is intersecting with spheres in the list. If not, add the new sphere...

How can I add an object to a list after creating it to loop over this object-list afterwards.

My code so far:

import bpy
import random
import math

radius = 50
ptnum = 80

curserPos = bpy.context.scene.cursor.location

spheres = []

for i in range(ptnum):
    r = random.random() * radius
    alpha = random.random() * 2 * math.pi

    x = curserPos[0] + math.sqrt(r) * math.cos(alpha)
    y = curserPos[1] + math.sqrt(r) * math.sin(alpha)

    bpy.ops.mesh.primitive_ico_sphere_add(location=(x,y,0))

Creating an empty list, and adding objects to it

# Create empty list
lobjects = []
# adding an object to it
lobjects.append(rock_object)

If you create more objects, you keep appending them to lobjects.

Creating objects

If you already have a template rock object that you want to use to create all of the other rocks:

Duplicating the mesh data of the template rock object

original_data = rock_object.data
new_rock_obj = bpy.data.objects.new('CopiedMeshRock', original_data.copy())
Linking the original object's mesh data

new_rock_obj = bpy.data.objects.new('LinkedMeshRock', original_data)

Distribution of the rocks:

I think you could start by creating a grid, so an object is placed within each cell of this grid (I am using spheres for this example)

Then if you distort this grid, using any (radial?) distortion function, you can change the size of each cell of the grid, and fit a sphere at the centers with a radius less or equal to the smallest side of the cell.

You would only do this for cells that fall within the desired target pattern (a circle in your case).

I have used the following code to generate those images. If you set $a_x = a_y = 0.0$ you get the first image (no distortion); if you set $a_x$ and $a_y$ to positive values you get barrell distortion.

Blender

import bpy          # bpy.data.filepath (path to the current blend file)
import mathutils    # mathutils.Vector

class ExitError(Exception):
    pass

def addSphere(center, radius):
    '''
    Add a sphere at the given location, with the given radius

    @param center (mathutils.Vector) 3D location of the center of the sphere
    @param radius   (float) Radius of the sphere
    #return (bpy.types.object) newly created object
    '''
    bpy.ops.mesh.primitive_uv_sphere_add(radius = radius, location = center)

    return bpy.context.active_object

def distortPoint(p, ax, ay):
    '''
    Distort point p

    @param p    (mathutils.Vector) 2D point to be distorted
    @param ax   (float) Distortion coefficient in X
    @param ay   (float) Distortion coefficient in Y
    @return (mathutils.Vector) Distorted 2D point
    '''
    px = p.x * ( 1.0 - ax * p.length * p.length)
    py = p.y * ( 1.0 - ay * p.length * p.length)

    return mathutils.Vector((px, py))

def isPointWithinCircle(p, center, radius):
    '''
    Is point p within circle

    @param p        (mathutils.Vector) 2D point
    @param center   (mathutils.Vector) Center of circle
    @param radius   (float) radius
    @return         (boolean)
    '''
    return (p - center).length < radius

def main():
    #fireworks.testDrawCubes(5, mathutils.Vector((2, 1, 0)))
    #fireworklib.drawCubes(2)
    scene = bpy.data.scenes.get('Scene')
    if not scene:
        raise ExitError('Could not retrieve scene')

    # Dimensions of the grid
    nrows = 50
    ncols = 50
    # Original size of each cell of the grid
    width = 0.8
    height = 0.8
    center = mathutils.Vector(( (nrows / 2.0) * width, (ncols / 2.0) * height ))
    # Normalized grid cell size
    nwidth = 1.0 / nrows
    nheight = 1.0 / ncols
    nwidth_half = nwidth / 2.0
    nheight_half = nheight / 2.0
    # Center of the normalized grid
    ncenter = mathutils.Vector(( (nrows / 2.0) * nwidth, (ncols / 2.0) * nheight ))
    # distortion coefficients
    ax = 0.9
    ay = 1.5
    # Circle: Center at center, and with radius
    radius = width * nrows / 3.0

    # List of created objects
    lobjects = []

    for i in range(nrows):
        for j in range(ncols):
            # Calculate center of the cell
            pc = mathutils.Vector(( i * nwidth + nwidth_half, j * nheight + nheight_half)) - ncenter
            # distort it
            dpc = distortPoint(pc, ax, ay) + ncenter
            # offset by center
            unnormalized_center = mathutils.Vector((dpc.x * width / nwidth, dpc.y * height / nheight))

            # only proceed if the center of the distorted cell falls within the circle
            if isPointWithinCircle(unnormalized_center, center, radius):
                p0 = mathutils.Vector((    i * nwidth,     j * nheight)) - ncenter
                p1 = mathutils.Vector((    i * nwidth, (j+1) * nheight)) - ncenter
                p2 = mathutils.Vector(((i+1) * nwidth,     j * nheight)) - ncenter
                p3 = mathutils.Vector(((i+1) * nwidth, (j+1) * nheight)) - ncenter

                # compute distorted points
                dpc = distortPoint(pc, ax, ay) + ncenter
                d0 = distortPoint(p0, ax, ay)
                d1 = distortPoint(p1, ax, ay)
                d2 = distortPoint(p2, ax, ay)
                d3 = distortPoint(p3, ax, ay)

                # approximate distorted bounding box
                dwidth = (d1 - d0).length * width / nwidth
                dheight = (d2 - d0).length * height / nheight
                # smallest side of the bounding box approximation
                dmin = min(dwidth, dheight) / 2.0

                # sphere's radio cannot be larger than smallest side of the approximate bounding box
                r = dmin

                lobjects.append(addSphere(mathutils.Vector((dpc.x * width / nwidth, dpc.y * height / nheight, 0.0)), r))

if __name__ == '__main__':
    try:
        main()
    except ExitError as e:
        print('Failed: {}'.format(e))

Note:* The example above creates a new sphere for each cell of the grid, which in this case is very inefficient: we could just reuse the same mesh and have the subsequent spheres link to it.

Another idea, if you use objects that are not spherical, is to:

give the objects (rocks) a small value to their location Z coordinate
enable rigid body dynamics
add a plane right below the given Z coordinate
Animate the scene so the objects fall by that small z, colliding with the plane and with each other, naturally randomizing them (without having to do that from code).

You could add rigid body dynamics for an object with

sphere = addSphere(mathutils.Vector((dpc.x * width / nwidth, dpc.y * height / nheight, 0.0)), r)
scene.rigidbody_world.collection.objects.link(sphere)

# add to the list of objects
lobjects.append(sphere)

Note: make sure that the target scene has rigid body world enabled:

if not scene.rigidbody_world:
    bpy.ops.rigidbody.world_add()

if not scene.rigidbody_world.collection:
    scene.rigidbody_world.collection = bpy.data.collections.new('RigidBodyWorld')


How to select animation channels using Python? How to select channels using python?

ActionGroup.select

As an example set the "spine" group to selected / unselected from the python console.

>>> C.object.animation_data.action.groups['spine'].select = True


Exporting rotations of selected objects to a text file I am using this script which I got from the internet and it works perfectly for 2.79.
Please could someone help adding selected objects rotation to export to the same txt file? In degrees.... Thanks in advance.

# import the necessary modules we need
# in our case, blender's python API and python's os module
import bpy, os

# get the current selection
selection = bpy.context.selected_objects

# initialize a blank result variable
result = ""

# iterate through the selected objects
for sel in selection:
    # get the current object's dimensions
    dims = sel.dimensions
    # write the selected object's name and dimensions to a string
    result += "%s - %.03fm x %.03fm x %.03fm\n" % (sel.name, dims.x, dims.y, dims.z)

# get path to render output (usually /tmp\)
tempFolder = os.path.abspath (bpy.context.scene.render.filepath)
# make a filename
filename = os.path.join (tempFolder, "newfile.txt")
# open a file to write to
file = open(filename, "w")
# write the data to file
file.write(result)
# close the file
file.close()

You already outlined everything that needs to be done. Rotation can be reached at .rotation_euler:

Note that you can find this information by typing stuff to the console and hitting ctrl+space for auto complete.

The values are in radians so you need an easy way to convert them. You can just multiply the values by 57.29577951308232, or you could do from math import degrees or from math import degrees, radians so you have functions that can convert between the two for you.

Everything from math is imported in the console so you could just get the degrees of x rotation of the active object by typing degrees(bpy.context.object.rotation_euler.x) in the console to check that this indeed does work.

In a script this would look something like:

import bpy
from math import degrees

result = ''

for o in bpy.context.selected_objects:
    #something else that you need to get to result
    n = o.name
    r = o.rotation_euler
    result += "%s - X:%.3f, Y:%.3f, Z:%.3f \n" % (n, degrees(r.x), degrees(r.y), degrees(r.z))
    # carry on to do whatever else
#write to file


Make a ring larger but same thickness Is it possible to make a ring larger, but maintain the same thickness?

I only selected the vertices of the ring, the ring is part of a larger object and I don't want to separate it.

If I simply scale it with S, it becomes thicker as well.

Try scaling in the y axis how much you want, then scale the same in the x axis. (Example with things you type: S,Y 90, S,X 90)


How to use bl_label inside an operator? How do I reference the bl_label inside operators? I want to know the name of the operator based on the bl_label to be precise.

You define bl_label inside the operator's code as a variable so after that you can reference it as any other variable inside the operator. It would be self.bl_label:

import bpy

class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

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

    def execute(self, context):
        print(self.bl_label)
        return {'FINISHED'}

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

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

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.simple_operator()


Creating rings with wave texture? Trying to make a procedural metal texture. I used this question to help me make the blue wave texture wrap around the object but I also want to have the red wave texture form in rings so that it would match the direction of the blue wave texture.

By forming rings I mean it would look like the section of the sphere here:

So the wave texture would move in this direction:

I've tried messing around with the rotation and location of the wave but I can't get it to move in the direction I want. How would I do this?

You can use the "Object" output of the Texture Coordinate node, together with the "Rings" type wave texture.


Layers tab not showing Usually my layers tab appears in the area of the red circle, but I did something that changed it. I would like to know how to get it back. Thanks!

You pressed the Numpad / key switching you into Local View. Scene layers and lock buttons do not show there. Press  Numpad / again to go back into Global view


create a folder in a specific path using Blender python I'm trying to create a folder using python in blender and run in in blender text editor. I don't know how I can do this.

I want to export the vertices of a mesh in this specific created folder. Currently I'm doing this which create the file in the blender folder.

fout = open("mesh.verts", "w")

You have following options. I use the file name myfile.xxx as placeholder for whatever file shall be opened.

Open within the folder where blender is installed:

    fout = open("myfile.xxx")

However you might run into permission issues when the installation folder is write protected.

Open in the user Application folder (Appdata)

    import bpy
    import os
    userdir = bpy.utils.resource_path('USER') # see note
    mypath  = os.path.join(userdir,"myfile.xxx")

    fout    = open(mypath)

Note: Please check also bpy.utils.user_resource(...)

Open in the same folder where the current blend file is located

    import bpy
    import os
    blenddir = py.path.abspath('//')
    mypath   = os.path.join(userdir, "myfile.xxx")

    fout     = open(mypath)

Note: If the current session has not yet been saved to a blend file, then blenddir is returned as empty string! You might need to test for this in your script.

Open in addon folder

    import bpy
    import os
    import myaddon
    myhome = os.path.dirname(myaddon.__file__)
    mypath = os.path.join(myhome, "myfile.xxx")

    fout     = open(mypath)

Hint: When you have installed the Addon by using the Addon Tab in User Preferences, then myhome points to Blender's scripts/addons/myaddon folder in the Appdata directory.

Open in Preset folder (where to store addon presets)

    import bpy
    import os
    import myaddon
    presets   = bpy.utils.user_resource('SCRIPTS', "presets")
    mypresets = os.path.join(presets, myaddon.__name__)
    if not os.path.exists(mypresets):
        os.makedirs(mypresets)
    mypath = os.path.join(mypresets, "myfile.xxx")

    fout     = open(mypath)


How do I can grab the current image in blender game engine from a python controller? I am trying to create a python controller that executes game commands based on the image pixels of one of the camera viewports. This is for a robot simulation using computer vision.

I've tried two different approaches to no avail:

APPROACH #1: use bge.render.makeScreenshot() to save the current frame to a png file. The PROBLEM is that when I process that file later in the script, the PNG file is invalid/incomplete. I think the image file writing buffer is not flushed and closed yet. The files are there and look fine after the I exit the game engine.

APPROACH #2: try to render and grab pixel values as outlined in this thread. The PROBLEM is that image array is None.

Is there a way to fix either of these approaches or another better approach for getting an image frame from the blender game engine?

import bge

def main():
    cont = bge.logic.getCurrentController()
    own = cont.owner
    scene = bge.logic.getCurrentScene()

    if not 'init' in own:
        own['init'] = 1
        own['counter'] = 0

    own['counter'] += 1

    ######### APPROACH #1
    # get frame using makeScreenshot()
    frame_filename = "//frame" + str(own['counter']) + ".png"
    bge.render.makeScreenshot(frame_filename)

    # do image processing on frameXXX.png ...

    # ***PROBLEM: frameXXX.png is empty/invalid/incomplete

    ######### APPROACH #2
    # render a camera scene and get image pixels
    cam = scene.active_camera
    source = bge.texture.ImageRender(scene,cam)
    source.capsize = [640,480]
    imageArray = bge.texture.imageToArray(source, 'RGB')
    charArray = imageArray.to_list()

    # do image proccessing on charArray ...

    # ***PROBLEM: source.image and imageArray are type 'None'

The second approach is the closest. But here's some code that may help (untested, but pulled from a working setup)

    obj = cont.owner
    camera = obj.scene.objects['NOT ACTIVE CAMERA']
    tex = bge.texture.Texture(obj, 0, 0)
    tex.source = bge.texture.ImageRender(
        camera_obj.scene,
        camera_obj,
    )
    tex.capsize(640*480)
    tex.source.background = [0, 0, 0, 0]
    source = self.tex.source
    data_array = bytes(640*480*4)
    source.refresh(data_array, 'RGBA') # Take the picture....

    print(data_array)  # Hopefully lots of data - in a 1D array.

You shouldn't recreate the data_array and texture objects each frame. Only do it on the first  frame, then just keep running the source.refresh() line.

If you run into issues, let me know and I'll make a blend file.


How to add a ghostly "Glow" effect? I want to add an "aura" effect to objects. I tried adding blur nodes in the compositor but it didn't look right. I also thought about using layer weights and with fresnel to make the edges glow. Then after watching Coco for the bazillionth time — the scene where Miguel sees his dead family — I liked the way the light surrounds each person.

Create a Glow Layer

You separate your render into two, the normal render and a glow render, both layers with a transparent background, in the glow layer set all the objects to have the same material (use an emission shader with the color of the glow you want):

Then, you can use this Node Setup in the Compositor:

You have to take into account that, in this example, the lighting is lame, that's why the effect doesn't look realistic, but using the same lighting that your scene will give you great results


Making sticthes in leather What method is the best to make stitches like the leather foot stool example? I am using UV texture for my chair.  Thank you for your reply.

Blender isn't too great for stitches in my experience since it lacks proper texturing tools like a world space based brush size. But I found 2 decent ways:

Make the stitches in 3D by modelling one simple stitch, adding an array and curve modifier combo, extract edge loops from your model, convert them to curves, and assign those curves as target for your array and curve modifiers. This will create believable stitches.
Paint the stitches in Texture Paint mode to affect diffuse and height map, you can use this images I made as a texture for your brush, mapping : 'view plane' and stroke method : 'line' with big spacing. But be careful as your brush size won't change on your screen when you zoom in and out so you have to manually adjust, unlike in Substance Painter.


Why do I get weird rotations in exported FBX? I have a simple, extruded cube model with two bones assigned to it. Now, when I export the model to FBX, the bones get weird rotations. I've checked that the bones have XYZ rotation of (0, 0, 0) in Blender, but for example the root bone has a rotation of (90, -90, 0) and the child bone has a rotation of (-180, 0, 0). The armature has a rotation of (-90, 0, 0) which I kind of expect to be there (as far as I know it's because of the axis conversion).

So, where are these rotations coming from?

When exporting, different formats have different space formats. Usually it's just a case of the axis getting mixed up.

There's some help here, but generally I'd suggest skipping exports if possible.


Out of memory after rendering thousands of similar scenes I have a project on which I have to render thousands of different screenshots of a scene. It is basically a for loop that changes the scene, calculates some stuff and renders.
However after around 2000 I blender complains that it is out of memory. In fact at each iteration it shows that the usage of memory is increasing, but I don't understand why, since I am not adding new elements to the scene and i am not keeping information from previous iterations.

I guess that there is some variable which is not being free in the loop. However I have no idea on how to find out that. Do someone have any ideas?
EDIT:
This is the error that I have:

In case anyone have a similar problem, I figured out the solution.
My script was generating a new texture at each iteration. I thought it was being discarded but actually not, blender was retaining this information as orphan data. So I simply needed to add bpy.ops.outliner.orphans_purge() at each iteration to clean this unused data that was loading my memory.


How to reduce the number of faces for selected parts of a mesh? hello,
I have made a high-poly 3D model by myself. But this 3D model has so many faces and I want to reduce the amount the faces only for some parts of this 3D model. How can I do this in Blender?

Go into Sculpt Mode.

Pick any brush (for example "draw") and set its strength to 0.

Enable "Dyntopo" from the Sculpt toolshelf and set Density = Brush in the Dyntopo options.

Now, control the size of your brush using F and "Sculpt" on the areas where you want to reduce the number of faces. One quarter of the brush size will be the approximate size of the new faces. Use undo CtrlZ when you need to!


Why is spotlight shining through cube? (Blender 2.80 EEVEE render view) I'm wondering why the spotlight here, if I'm seeing what's going on correctly, seems to be passing right through the cube. Thanks for any ideas.

For any curious about this, here's the nature of the problem and the solution
at Blender bug reports. Turns out it's not a bug, but I had thought it might be,
so to help by reporting it I thought I'd inquire there at Blender bug reports.
https://developer.blender.org/T63768