Outils pour utilisateurs

Outils du site


issue156:python

As I sit in self-imposed isolation, I have once again struggled with what to present to you this month. I'm fairly certain that I won't be repeating anything that I have presented before. This month, we will explore Blender and its Python scripting possibilities. If you aren't aware of Blender, I'll give you a quick introduction as to what it is, what it does, and how to do something simple, before we get into the programming aspects. I will say from the start, I am just learning how to do things with Blender from Python (and I'm not really that good with Blender by itself), so bear with me.

Alors que je m'impose le confinement, je me suis à nouveau retrouvé devant la question de ce que je vous présenterai ce mois-ci. Je suis quasi certain que je ne répéterai pas ici ce que j'ai déjà présenté. Ce mois-ci, nous explorerons Blender et ses possibilités de scripts en Python.

Si vous ne connaissez pas Blender, je vous présenterai succinctement ce dont il s'agit, à quoi il sert, et comment faire quelque chose de simple, avant de rentrer dans les aspects de programmation. Pour commencer, je dirai que j'apprends juste comment faire des choses avec du Python dans Blender (et, pour ma part, je ne suis pas vraiment à l'aise avec Blender) ; aussi, soyez indulgents.

From their website (blender.org), “Blender is the free and open source 3D creation suite. It supports the entirety of the 3D pipeline—modeling, rigging, animation, simulation, rendering, compositing and motion tracking, video editing, and 2D animation pipeline.” I'm sure that you have heard of “Big Buck Bunny”, but have you heard of Agent 327? https://www.youtube.com/watch?v=mN0zPOpADL4 Blender runs on almost any platform. The latest version is 2.8.2a, and you can download it at https://www.blender.org/download/

D'après leur site Web (blender.org), « Blender est une suite de création 3D, Open Source et gratuite. Elle supporte l'ensemble des activités de la 3D : modélisation, accessoirisation, animation, simulation, rendu, composition et suivi du mouvement, montage vidéo et pipeline d'animation 2D. »

Je suis sûr que vous avez déjà entendu parler de « Big Buck Bunny », mais avez-vous entendu parler de l'Agent 327 ?

https://www.youtube.com/watch?v=mN0zPOpADL4

Blender tourne sur à peu près toutes les plateformes. La dernière version est la 2.8.2a et vous pouvez la télécharger sur https://www.blender.org/download/

One other thing, before we get started. Blender has always gone through many changes, and the tutorials out there don't often catch up. In fact, many of the tutorials (and many books) are written and published based on a preview or pre-release version that many times is changed multiple times before the actual version release. A good example is when a tutorial (for Blender 2.8.x) refers to changing things in preferences by accessing the File | User Preferences menu. That no longer exists. It's actually located under Edit | Preferences. I, at this point, don't have a good place to point you to in order to find all the changes like this. Many API calls were changed as well, so you should keep the API documentation close at hand when attempting to learn from a tutorial or book on the subject. The Blender 2.8.2a API reference is located at https://docs.blender.org/api/. Luckily, the API documentation has a change log from the last release version (2.7.9) at https://docs.blender.org/api/current/change_log.html

Autre chose, avant de commencer. Blender a toujours fait des modifications et les tutoriels disponibles sont rarement à jour. En fait, beaucoup de ces tutoriels (et beaucoup d'ouvrages) sont écrits et publiés sur la base d'une présentation ou d'une pré-version qui est modifiée plusieurs fois avant la vraie publication de cette version. Un bon exemple est quand un tutoriel (pour Blender 2.8.x) fait référence à des modifications dans les Préférences en y accédant par le menu Fichier > Préférences utilisateur. Ça n'existe plus. C'est en fait situé dans Édition > Préférences. Je suis ici démuni pour vous indiquer un bon endroit où vous trouveriez tous les changements comme celui-là. De nombreux appels d'API ont changé aussi ; ainsi, vous devriez garder sous le coude la documentation sur les API quand vous essayez de vous former sur ce sujet à partir d'un tutoriel ou d'un livre. La référence sur les API de Blender 2.8.2a est située à : https://docs.blender.org/api/. Par chance, la documentation sur les API a un enregistrement des modifications depuis la précédente version (la 2.7.9) sur https://docs.blender.org/api/current/change_log.html

Now, on with the fun! Download Blender and un-pack it in a convenient folder and run it from the terminal command: $ ./blender The first screen you should see is something like that shown below. This is the default ‘new project’, and contains three objects: a cube, a camera and a light. I should tell you, right now, that Blender is NOT something you can learn in a single day or week. However, if you really want to learn it, within a week, with the right tutorials (and this is NOT one of those), you can become very conversant and effective. You will ALWAYS need to have the keyboard and mouse very close, since Blender uses both for most any action. We'll get into the programming aspect in a couple of minutes. For now, let's do something with our Blender scene (bottom left).

Maintenant, amusons-nous !

Téléchargez Blender et extrayez-le dans le dossier convenable, puis lancez-le avec une commande dans le terminal :

$ ./blender

Le premier écran que vous devriez voir est quelque chose comme celui montré ci-dessous.

C'est le « nouveau projet » par défaut, et il contient trois objets : un cube, une caméra et un éclairage.

Je dois vous dire, tout de suite, que Blender N'est PAS quelque chose que vous pouvez apprendre en un jour ou une semaine. Cependant, si vous voulez vraiment l'apprendre, en une semaine, avec les bons tutoriels (et ceci n'en est PAS un), vous pouvez le maîtriser et devenir efficace. Vous aurez TOUJOURS besoin d'avoir votre clavier et votre souris sous la main, car Blender utilise les deux quelle que soit l'action. Nous nous lancerons dans l'aspect programmation dans quelques minutes. Pour le moment, faisons quelque chose de notre scène Blender (en bas à gauche).

I took a screenshot of Blender, opened it into Inkscape, and labeled the camera and light for you (I think the cube is fairly obvious), and showed the three axes for you in order to help you understand the ways things will move. If we take a VERY close look at the cube, which is our default object when we start Blender, you will see something interesting… See that little circle with an “X” and a dot in the cube? That’s the 3D cursor. This is the origin of all the objects that we put into our blender scene. Even though it doesn’t look like it, it is at the intersection of the Green and Red layout lines, and the origin is in the center of the cube. That means that only the “top” half of the cube is above the imaginary plane which is the grid that is shown on the layout screen.

J'ai pris une copie d'écran de Blender, l'ai ouvert dans Inkscape et j'ai étiqueté la caméra et l'éclairage pour vous (j'ai trouvé que le cube était vraiment évident) et je vous ai montré les trois axes de façon à vous aider à comprendre comment les choses se déplaceront.

Si vous regardez très PRÉCISÉMENT le cube, qui est notre objet par défaut au démarrage de Blender, vous verrez quelque chose d'intéressant…

Voyez-vous le petit cercle avec un « X » et un point dans le cube ? C'est le curseur 3D. C'est l'origine de tous les objets que nous mettons dans la scène de Blender. Même si ça n'apparaît pas ainsi, il est à l'intersection des lignes de mise en place verte et rouge, et l'origine est au centre du cube. Ça signifie que seule la moitié « supérieure » du cube est au-dessus de la surface imaginaire représentée par la grille sur l'écran de mise en place.

Let’s do some coding… Change your screen to the Scripting window tab, which should be close to the center of the screen at the top. You should see something like the image bottom right. The editor (shown top right) is located near the center of the screen. The Blender menu for the editor is laid out a bit differently than what you would normally expect. Normally, we would expect File | New, File | Open, and File | Save options, but these are located under ‘Text’. LARGE DISCLAIMER: While I've been a user off and on of Blender for many years and a Python programmer for almost 15 years, until I started working on this month's article, I've never tried to do anything that mixed the two. You are learning what I am learning almost in real time, but without the pain.

Effectuons un peu de codage

Sur votre écran, passez sur l'onglet Fenêtre de script, qui devrait être proche du centre de l'écran en haut. Vous devriez voir quelque chose qui ressemble à l'image en bas à droite.

L'éditeur (en haut à droite) se trouve près du centre de l'écran. Le menu de Blender pour la modification est organisé un peu différemment de ce à quoi vous vous attendriez.

Normalement, vous attendez à Fichier > Nouveau, Fichier > Ouvrir et Fichier > Enregistrer les options, mais ceux-ci sont situés sous « Texte ».

GRAND AVERTISSEMENT : Bien que je sois un utilisateur intermittent de Blender depuis des années et un programmeur en Python depuis presque 15 ans, avant que je commence à travailler sur cet article, je n'avais jamais essayé de faire quelque chose qui mixe les deux. Vous apprenez ce que j'apprends en quasi temps réel, mais sans les difficultés.

We’ll start our first program. I found a few small programs for Blender at: https://medium.com/@behreajj/creative-coding-in-blender-a-primer-53e79ff71e. However, due to changes in the API from when it was written and when I tried to run it, it refused to run, so I broke it down into a simpler version. Use Text | New to make the editor allow you to type in our code. Here's the program itself… import bpy Of course, we need to import the Blender API library. Next, we’ll create a function (below) that will delete everything in the default scene, so we can put what we want where we want it.

Nous commencerons notre premier programme. J'ai trouvé quelques petits programmes pour Blender sur : https://medium.com/@behreajj/creative-coding-in-blender-a-primer-53e79ff71e.

Cependant, du fait du changement dans les API depuis que ça a été écrit, quand j'ai essayé de les faire tourner, il a refusé ; aussi, je l'ai transformé en une version plus simple.

Utilisez Texte > Nouveau pour que l'éditeur vous permette de saisir notre code. Voici le programme lui-même :

import bpy

Evidemment, nous devons importer la bibliothèque des API de Blender. Ensuite, nous créerons une fonction (ci-dessous) qui effacera toute la scène par défaut ; ainsi, nous pourrons y mettre ce que nous voulons où nous voulons.

We need to code it this way, since we have to delete each of the existing objects one at a time. There is no “delete all objects” command that I could find. The bpy.data.objects command will provide a “list” of all the objects, and we can step through that, one at a time, to remove or delete each of the objects. Next, we’ll define two variables, the first for the size of the object and one for the size of the “world” that we will be creating. sz = 2 extents = 8.0 Next, we’ll create a single cube (yes, I know we just deleted one, but this shows how to create a new object) and set its location. Notice that we set the cube at Z axis of 1, so it’s above the “floor”, which in this case, is imaginary, but you can create one later on if you want (see above).

Nous avons besoin de la coder de cette façon car nous devons effacer un par un chacun des objets existants. Il n'y a pas de commande « effacer tous les objets » disponible par défaut. La commande bpy.data.objects nous fournira une « liste » de tous les objets, et nous pouvons la parcourir pour enlever ou supprimer, un par un, chacun des objets.

Ensuite, nous définirons deux variables, la première pour la taille de l'objet et l'autre pour la taille du « monde » que nous créerons.

sz = 2

extents = 8.0

Ensuite, nous créerons un simple cube (oui, je sais, nous venons juste d'en effacer un, mais ça nous montre comment créer un nouvel objet) et définirons sa position. Notez que nous définissons que le cube est à 1 sur l'axe Z ; il est donc au-dessus du « plancher », qui dans notre cas, est imaginaire ; mais nous pourrons en créer un plus tard si nous voulons (voir ci-dessus).

That’s our code. Now save the code as “test1.py” and click on the ‘Run Script’ button. The script will run and you will see the result in the upper left layout window. If you press the {F-12} keyboard button, you will see the scene rendered. It’s pretty boring, so I won’t even show it here, but it was important to show how to create an object from code. Now we’ll start a new script to something a bit more interesting… We’ll call this Test2.py. We’ll go ahead and import the library and use the clear_scene function we created in test1.py (see next page, top left).

Voici notre code. Maintenant, sauvegardez-le dans « test1.py » et cliquez sur le bouton « Lancer le Script ». Le script sera lancé et vous verrez le résultat dans la fenêtre de mise en scène en haut à gauche. Si vous appuyez sur la touche {F12} du clavier, vous verrez le rendu de la scène.

C'est plutôt sans intérêt ; aussi, je ne le montre pas ici, mais c'est important de montrer comment créer un objet à partir du code.

Maintenant, démarrons un nouveau script pour quelque chose de beaucoup plus intéressant. Nous l'appelerons test2.py.

Nous commencerons par importer la bibliothèque et utiliserons la fonction clear_scene que nous avons créée dans test1.py (voir page suivante, en haut à gauche).

Now we need to define a number of variables for our program. This will include the extents (size of our “world”), the count of cubes that we will create (on each layer), the spacing between each cube, and the size of each cube. The comments within the original code should be enough to help you understand what is happening. # Size of grid extents = 8.0 # Number of cubes count = 10 # Spacing between cubes padding = 0.005 # Size of each cube sz = (extents / count) - padding

Maintenant, nous devons définir quelques variables pour notre programme. Cela incluera extents (la taille de notre « monde »), le nombre de cubes que nous créerons (sur chaque calque), l'espacement entre chaque cube et la taille de chaque cube. Les commentaires dans le code d'origine devraient suffire pour vous aider à comprendre ce qui se passe.

# Taille de la grille extents = 8.0 # Nombre de cubes count = 10 # Espacement entre cubes padding = 0.005 # Taille de chaque cube sz = (extents / count) - padding

# To convert abstract grid position within loop to real-world coordinates. iprc = 0.0 jprc = 0.0 kprc = 0.0 countf = 1.0 / (count - 1) diff = extents * 2 # Position of each cube. z = 0.0 y = 0.0 x = 0.0 # Center of grid. centerz = 0.0 centery = 0.0 centerx = 0.0 Now we’ll create our cube of cubes (shown below).

# Pour convertir la position abstraite de la grille dans la boucle en coordonnées du monde réel. iprc = 0.0 jprc = 0.0 kprc = 0.0 countf = 1.0 / (count - 1) diff = extents * 2

# Position de chaque cube. z = 0.0 y = 0.0 x = 0.0

# Centre de la grille. centerz = 0.0 centery = 0.0 centerx = 0.0

Maintenant, nous créerons notre cube de cubes (voir ci-dessous).

The rest of our program will be just like the end of test1.py, in that we create a lamp and camera into the scene (next page). Now, when we run the program, it will take some time. On my machine, it took over a minute and a half. Nothing happens on the blender screen, but if you look at the terminal window, you will see the output of the print statements that shows something is actually happening. Remember, we are creating 1000 cubes (10 x 10 x 10) along with the light and camera. Shown right is what the result of test2.py looks like when rendered.

Le reste de notre programme sera comme la fin de test1.py, parce que nous créons une lampe et une caméra dans la scène (page suivante).

Quand nous lançons notre programme, ça prend un peu de temps. Sur ma machine, ça dure environ une minute et demi. Rien ne se passe sur l'écran de Blender, mais, si vous regardez la fenêtre du terminal, vous verrez la sortie des déclarations print qui montrent que quelque chose se passe vraiment. Souvenez-vous que nous créons 1 000 cubes (10 x 10 x 10) ainsi que l'éclairage et la caméra.

À droite, le résultat de test2.py est présenté tel qu'il est rendu.

As always, I have uploaded these two programs onto pastebin… Test1.py https://pastebin.com/enNDN0mh Test2.py https://pastebin.com/CaVXwhDQ Until next month; stay safe, healthy, positive and creative!

Comme toujours, j'ai téléversé ces deux programmes sur pastebin :

Test1.py https://pastebin.com/enNDN0mh Test2.py https://pastebin.com/CaVXwhDQ

Jusqu'au mois prochain, restez à l'abri et en bonne santé, positif et créatif !

Encadré p 19, en haut à droite, lignes noires :

This creates a cube at location 0, 0 and 1 unit above the imaginary “ground” plane. Now we’ll create a lamp and a camera for the scene…

Ceci crée un cube à l'emplacement 0, 0 et 1 unité au-dessus de la surface imaginaire du « sol ».

Maintenant, nous créons une lampe et une caméra pour la scène…

issue156/python.txt · Dernière modification : 2020/04/29 14:46 de andre_domenech