Python Crash Course for Blender!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right everyone welcome to my Python the crash course for blender I've been receiving too many requests to make Python videos so I figured now is probably a good time to do it so there we are and naturally this is gonna be a bit more of like a workshop format rather than a regular tutorial so this will definitely be a longer video if you're not happy with that then that's okay you don't need to watch this but if you are interested in starting to make add-ons for bender then this is the video for you but at the end of this video you'll be able to make this cool strange generative emissive type effect thing there's no real purpose behind this tool but I think it's a good demonstration because it will show you how to access objects materials modifier stack nodes and those all stuff like that so before we get into it there's a few things you should keep in mind when using Python in blender first of all you want to make sure that you enable the python tooltips and I'll explain what this is if you go to edit then preferences under interface and here you will see Python tooltips and you should also have toe tips enabled but if you hover over this it'll say what it is it shows Python references in toe tips now toe tips are where say if I create an object and add a modifier if you have a value in the interface and you hover over it a tool tip will appear and it basically gives you a description of what the value does but if you enable the Python tooltips there'll be a dog gray description underneath that basically tells you the code path to that value and this code path is basically an address inside of blender that tells you exactly where to go when writing python code or regular Python commands to access their value and change it so this is super important because you probably aren't gonna remember all of the names of these values in Python off by heart so just by hovering over the value you can remind yourself another super useful thing as well is that we can also open up a new window and go to info and basically everything you do in the blender scene has a command associated with it and in the info window you can see exactly what this command is so this is helpful say if you want to automate a specific workflow of yours and there's a set number of actions that you do repeatedly and it's something you want to automate you can just do all those actions then a read back through the info window and see exactly what those commands were you could then copy them and paste them and then use them and at the moment my blender might look different tears because I'm using a darker theme it's a custom theme of mine and also I've changed a start-up file so I've got my own self premade workspaces up here we're inside of the scripting one which has the text editor window as well as the Python console so what I'm going to do is I'm going to press new in the text editor window and this creates a new text object in the blender file now I'm gonna name this demo spy and the reason I'm calling it Pi is because all Python files end in PI well actually there's an exception that could be made their regular Python files and into a PI but there are some other extensions that we don't need to worry about also if we go to view you might want to make sure that syntax highlighting is enabled this ensures that when we write code it will be colored appropriately which will make it much easier to read okay now we can actually get started so if you haven't done any coding or programming before then I highly recommend you watch my intro to coding video because it outlines some pretty commonplace principles and concepts that are relevant to every single programming language these are things like abstraction functions variables and data being represented by an address format and stuff like that I won't explain all of those things here so I recommend you go and watch down and come back because you've been a much better position one thing you need to keep in mind is in Python most of the code you'll be writing it comes from modules of ways known as libraries in some languages a language like Python is usually prepackaged we have a bunch of modules or libraries there serve different purposes and when you run a Python script it doesn't import all of them by default and that's because it would be very inefficient because there might be some libraries for networking for text editing for mathematics as well as a whole host of other fundamental functionality and then there's a huge library of community made modules available online as well which you can easily download now when it comes to telling Python what kind of modules we want to use we use the import command and this basically says to python hey we want to make use of any of the commands that are available in this module so if blender the main module we want to import is called vpy for blender Python and if we look down inside of the Python console here you can see that it says built-in modules and convenience imports the built-in modules of b py e py dot data PP wider ops and props and types in context and just to explain these in a bit more detail now APY is basically basic blender functionality bpy dot data is what we used to modify the contents of a file and search for it so all the things like object and mesh data textures and stuff like that bpy drops is for useful operations say creating new objects or materials and stuff like that and props and types is stuff that we won't necessarily get into we might take a look a props a little bit later on this is slightly more advanced stuff there's the thing when you write a Python file inside of the text editor it does not automatically import these modules so we need to manually write import bpy whereas in the console we don't need to do this so just to demonstrate this if I create a basic object like a cube and the console I can type in bpy about context which contains all of the contextual information for the scene dot active underscore object then it's going to say BP wired updated objects cube so it's basically giving us an address for the selected object so we know this works however if I did not import bpy and I typed the same thing then when we go to run this we immediately get an error and it's because bpy has not been imported so this is something very important they need to keep in mind that if you run Python code in one part of blender it will not necessarily run the same as another part of lender now if I go in for bpy here and then press old P we can see that it runs the script and no error appeared another thing to keep in mind as well is that if you run stuff in the text editor that should output things to a console it won't output it to the Python console here instead any errors or messages that are created by the text editor will go into the system console which you can get to from window and toggle system console and we can see here where we had a bpy error bpy not being defined the last time we ran the script so now we've got the boring import and stuff out of the way let's take a look at actually how to make stuff so starting from an empty scene one way that you can add new objects to blenders to make use of the BP wired ops module so ops as I said is basically a collection of really useful commands generally if you're doing complex code it's best to avoid ops as much as possible but if you're doing lightwei workflow improving scripts then they're quite useful and they can save you a lot of extra lions now these code paths were like an address as in a web address or a folder address but instead of forward slashes or back slashes we're using dots we can filter down through categories so BPI adopts mesh means that we're now taking a look at the operations that are related to meshes dot and then we can type in primitive underscore cube underscore add so what this command will do is add a primitive cube so if I run the script which we can either do by going to text run script or pressing alt P or pressing this button over here for run script or two P is the easiest way to do it then it will make a cube so we've imported bpy and then we've called the operation to add a cube very simple two lines of code but now that we've created the cube we don't really have a way to modify in any way what if we wanted to change some of the values like the rotation the scale the position or add modifiers to it or stuff like that we basically just blindly created it and we don't have a reference to it in any way one thing to keep in mind is when we cooperations like this lambda automatically makes the cube the newly selected object so we can actually take advantage of that I like the story inside of a variable called s au which stands for selected object if you can call it anything you'd like so I could write here s au equals b py context Doh active underscore object so now after we've created the cube we've now stored it inside of air--so which makes it easy to manipulate because then we can just go s o dot and then modify any data that we can find so let's give this a try if I type in s o dot location and then square brackets and inside there put 0 and then I'm gonna do something like fine now let me just explain this some variables are single values and some variables are more complex like lists or arrays of objects and basically they can contain more than one value with an array all values start at a position of 0 so 0 1 2 3 and then they can all be equivalent to different things in the case of this location value zero equals x 1 equals y and 2 equals Z X Y Z regular Cartesian coordinates so by typing in Esso dot location sir equals five or we're saying is we're on the x position of this cube to be equivalent to five units so if I press alt P to run this and we zoom out we can see that we've created a cube and has moved five units on the x-axis so that's a simple way of how you can move objects what about rotation now rotation is slightly more tricky because you can't just pass a regular number to it instead we have to work with radians typically when you describe rotations you're either using degrees or radians degrees or something that's easier for us to understand but not so much for a computer so if we have a degree in mind like 45 90 180 degrees so we want to retain an object by be to convert that degree into radians first but there's an easy way to do this an easy way and a slightly hard way so I'm gonna start with the harder way and I'm gonna show you the easy way and then you will see how useful that is so let's say I wanted to move this cube by 45 degrees so if I type in Tabriz equals 45 just so we know then go create a new variable called rad for our radians now how do I convert degrees into radians the equation for this is degrees multiplied by pi divided by 180 now I promise we won't get too mathematical for the rest of this video but this is something that's quite important just to know the asterisk or star symbol in code means multiply and the forward slash means divide so rad will become the Radian value of 45 now I can prove this to you by going down into the Python console here so if I type out this again degrees equals 45 radicals degrees multiplied by pi divided by 180 and then type rad they gives us naught point 75 blah blah blah blah blah but there's a special function we can use it's a lot easier to understand to confer these degrees for us radians and then brackets 45 and you see it has the exact same value now here's the thing we could type in radians 45 into this code but this wouldn't work and I can prove this to you now error message the reason is because radians comes from a module that we have an imported yet C radians does not come from bpy it actually comes from one called math now with Python you don't have to import entire modules you can't just import the individual elements of the modules that you want so I'm gonna type in from math import radians and this will basically import the radians command into our script for us to use so if I delete this and of course we haven't actually told the object to move so if I run this now it's not gonna do anything but it won't give us an error because we have the command its orderly there again and now let's actually put this to use s Oh God rotation underscore Euler yes that's not just rotation its rotation underscore Euler Euler representing Euler angles you don't need to know too much about that just trust me and then in brackets zero because we're working with X rather than Y I said plus equals radians 45 and now let me get rid of that original line now what does plus equals mean basically plus equals is a way of writing out s ODOT rotation underscore Euler zero equals s over rotation underscore Euler 0 plus radians 45 so what we're saying here is the the x value for the rotation should be made to be the x value plus the radiant value now obviously this is quite long to write out so plus equals is just a way of saying hey just make this equal to the value of both of them combined so now if I run this we see it creates the object moves it five units on the x axis and then rotates it by 45 degrees okay now I'm going to remove this move code because I actually just want to keep the object centered Bo now we're gonna move on to taking a look at how to add modifiers so how do we add modifiers and we're gonna step away from this script for a minute so I can demonstrate this using the console I'm gonna manually create a cube then in the Python con so I'm gonna type in s so pickles EP wide on context to active object again so we're basically storing this cube inside of there so what I can type in now is s o dot now this is actually a good point for me to talk about the Auto completion feature in the Python console if you type in a value and then dot as if you're looking for the next part of the code address and then press tab it'll basically give you a list of all the possibilities or things you can type next so then here we can see that modifiers is a valid thing that we could type next so s o dot modifiers and then I have breasts dot and then tab forward to complete again and we can see that there's a command here called new so s Oda modifiers new we know that we're along the right lines for adding a new modifier to the cube now I already know exactly what to type so I'm going to put brackets here now and there's two values that the command can take to string values the first one is just the name they were going to give to the modifier it can be anything you want it to be so I'm going to call it my modifier but the second one is the type of modifier this code needs to be absolutely perfect so usually it's the uppercase shorthand name of the modifier so for example a subdivision surface modifier is subsurf this tells blender exactly what we want it to be so if I press ENTER we see that it's come back with a good value it's now told us exactly how to find this modifier B P by dou theta two objects cubed or modify as my modifier but nothing has changed yet until we rotate the camera as soon as we move the camera it updates the scene and if we look in the modifier tab then we can see it here so this is code to add the modifier so I can write this in here as well som modifiers door new my modifier subsurf but the problem is again just like before we're line ly creating this and we don't have a way to modify the values of the modifier so say we wanted to change the viewport number of subdivisions how can we do this in the Python code well there are two main ways to access the modify values again I'll show you the long winded way and then I'll show you the easier way so we could go Esso modifiers square brackets my modifier and then access to value through here so we can see that it's bpy table data the modifiers my modifier dot levels so don't levels saw we need to type and then I can change it to something like free and then I can actually test this down here in the console it was free and then we can see that immediately it increases the number of subdivisions so that's fine this method is what we would call the searching method because we're going to the modifiers list and then we're searching for my modifier and then we're modifying the value there but let's say you wanted to change lots of values on a modifier one after the other then it would be quite inefficient searching for the modifier for every single value that you wanted to change so instead what we can do is type in something like mod underscore subsurf I'm basically creating variable equals s odo modifiers doneyou my modifier subsurf so we're storing the newly created subdivision surface modifier inside of the variable mod underscore subserve so then I can do this get rid of all this code - mod underscore subsurf and it will do the same thing so if I run this script now they creates the cube rotates to 45 degrees adds a subsurf modifier and then it increases the viewport levels to free okay we're taking a look at this smoothed cube I don't like the way that it's flat shaded you know so if I open up the info window here let's say I wanted to apply the smooth shading to the subject using Python how would I do that if I don't already know what the code is I would either have to look it up or try to do some convoluted searching through the - console but no like I said with the info window we can see exactly what commands are being called in blender so if I right click and choose a shade Smoove we can see that the command being cord is bpy dog's dog Jake tor shade Smoove so this will apply the smooth shading to any object that's actively selected and as we know when bpy dobbs creates an object it makes this object the selected object so i could just type in here leepu i the ops objects' of shade smooth so if I delete this then run the script there we go it automatically creates it again and shades it smooth so this is an example of how we can use the info window to inform our script but for the sake of learning I'm actually going to show you a slightly more convoluted way to do this and by that what I mean is we're going to create a loop and look at each of the individual polygons and then set them to smooth shading individually so I'm gonna do is comment out the line of code Weaver in there and I haven't mentioned it already but the comments you can make by typing in the hashtag and the colors will be different on your screen because I'm using a custom theme but what it basically means is that private will ignore everything on that line so if I type in mesh equals s OData now we don't need to create mesh but it's just gonna make it a bit easier to understand when we write the loop so I can type in for face in mesh dot polygons face don't use underscore smooth equals true so what this loop is saying is for every face that we find in the list that is mesh top polygons otherwise known as s OData top polygons we could just put that in here as well and they would perfectly fine face though we're looking at don't use smooth equals true so for every face we find in the polygons list make it smooth so if I run this that's the same thing makes all the polygons smooth now you'll notice here that some code is being indented what I mean is that there's a tab when we create loops or a new kind of scope you always need to indent to a new line so say for example that I did an if statement of any kind I would then need to indent all of this say that I had a like another kind of for loop here I would also need to indent this code so basically it's easy to read and it's easy to perform to understand what code needs to run inside of what conditions but we don't need to worry too much about that at the moment I'm just going to reset this and bring back that line of code so now when we run this we've got a subdivided cube let's do something a bit more interesting with it we're gonna add a displacement modifier so let me just make a note using what we've learnt before I can do mod underscore displace equals so2 modifiers don't knew my displacement and then in here I'm going to type in displace in capitals so this will create a new displacement modifier so let's delete the subject run the script I will see it's a bit wider than before because that's what a displacement does to start with and we can adjust the value but the real power of displacement comes from created generated textures so now you can see why I've chosen to use the displace modifier because we're about to learn how to create these textures programmatically so just to take a look quickly if I create a new texture manually and then go into the texture properties they can see that all of the properties of the texture are very dependent on the type of texture that it is so there's four annoy Musgrave magic blend image or movie distorted noise etc as we change the type these settings also change so first of all we need to find a way to create a texture in the code and then we need to find a way to set the texture type this is actually quite simple so if I remove this object I'm going to type in first of all comment new underscore text equals b py because we're not actually creating this date for the object we're creating it for the actual blender file so this texture could be used anywhere else in the scene don't data because we're modifying the data off the blend file dot textures not new so just like modifiers don't new behave textures don't new inside of here I can type in my texture and again here we can type in an uppercase ID for the type of texture we want so just for demonstration I'm going to type in distorted noise and if you want to learn more each of the possibilities for these codes are then they are available on the blender wiki and actually just for reference I'm going to copy the addresses in here just we have them visually on record this is the place where you can find all the different codes and I've just noticed I made a mistake by type in text instead of text so I can remove that T so basically this will create a new distorted noise texture inside of the blend file so say if I wanted to modify a value of that text I could raise something like new underscore Tech's noise scale equals 2.0 and then if I wanted to apply the texture to our new displacement modifier I'd write quite simply this mod underscore displace don't texture equals new underscore Tex and that would be it so if I run this code now he creates a cube then subdivides it rotates a bit then adds a displacement modifier they creates a distort noise texture then applies the texture but also it modifies the noise scale so for example if I come in here the size value is the noise scale value so I can go in and modify afterwards now you can see how we can set the value inside of the Python code okay that's all well and good so now we know how to create an object with its location with its rotation add a modifier change to modify values shade it smooth create textures assign the textures to modifiers how do we create materials for material nodes well this is where things require quite a few more lines to get done so I'm actually gonna go to the shader editor window and to object because we'll need to have a visual demonstration of this so the first line is quite easy to understand because we've already covered most of this new underscore max equals bpy dot data dot materials don't you just like our bpy data textures new we're doing ppy data materials new because we're creating a new material object for the blender file and then in here I'm gonna type in name equals my material now why am i typing name equals into here because before we've always just typed in the value by itself but for a lot of functions there were different arguments that you can provide and if you want to be very specific with Python and tell them exactly what argument you want to be writing for then you can actually just type in the variable name equals this so I'm just showing you a different way that you can do things but now that we've created a new material for the blend file we need to actually assign it to our object so to do this I can type in s Oh dot data don't materials so what we're doing here is taking a look at our selected object the data of our selected object the materials list for our object of which there are currently nothing and then dot pendant where Penta means is it's going to add wherever we provide to it as an argument to the list of materials so we're going to go to materials append and then of course in here new underscore mat because we want to add our new material to our list of materials for the object now of course just to demonstrate something if I create a new material manually we have the option to either use nodes or not use nodes and if we use nodes we can always just easily change the surface shader here to something else we're not gonna worry too much about this instead we're manually going to create a node and then manually go in to form connections between the node we create and the material output node and we're going to do this because I can show you how to access the different ports of a node and connect them together so first of all we want to tell the object that we are actually going to be using nodes so I'm going to type in new underscore matte dot use underscore of nodes equals true now to save us from having to write out a lot of code I'm gonna type in nodes equals V underscore matte dot node tree nodes now the reason I'm doing this is because I want to make this shortcut variable just like when we did the loop with this moving before you can basically write a variable that acts as a shortcut between a longer line of code so nodes is equivalent to writing new mad node tree nodes so now we'll have access to the node tree that we're creating for our new material I want to create a reference to the material output node first of all some node type material underscore output equals nodes dot yet basically this is a function for searching for a node and then by using a string I'm going to type in material output so this is basically going to find at the material up and load and store it inside of our material output variable now for this demonstration I'm going to create an emissive shader for us because the emissive shader is my favorite type of shader so let's use it no to underscore emission equals nodes dot new so instead of using get to find a node we're gonna use new to create a node and then here we're gonna write type equals and then I'm gonna create a string shader node and mission again there's a very specific code that needs to be written for the type of shader and yes I get it's a bit confusing the the is written with upper and lower cases or as the other types here are written incompletely upper case these are just some things you need to remember and again there'll be a list of all the different types of codes you can write somewhere as well okay so now we've got references to our two different types of nodes we've got the material output node and the emission node and now we need to find a way to connect these in code so this is where we need to think about averies again remember how I said the arrays are represented in square brackets and they start a value of zero and it's basically a list so the first object in the list will be zero then the next would be one to free etc think about the inputs and outputs of a shader node on the left side here we have our inputs and they're all in a line this is an array of values so taking a look at the principal psdf shadow the first value base color would be a position zero for the input 0 1 2 3 4 5 and going down and so on this be SDF shader output would be a position 0 for the outputs so keeping this in mind I now know how to manipulate the different inputs and outputs so before we connect these I'm actually gonna make a slight change because one of my favorite colors is cyan I'm going to set the color of the emission node to cyan so if I type in node underscore mission dot inputs 0 and I should actually create an emission node here just we can see exactly what we're looking at input 0 is a color value and I can change this to cyan here but of course this isn't doing in code but if I take the RGB values and type in 0 0.3 and 1.0 then this creates a cyan color and I know this off by heart so I could type in here default value equals and then I need to do this in brackets 0.0 0.3 1.0 and 1 the final one is the alpha value so this will basically set the color value of the emission node to cyan and also because I want to make it stronger I can type in node underscore mission your inputs one third default value equals and I can do 504 strength so this is how we modify the values of a node but now say I wanted to connect these two together how do I do that first of all I'm gonna make another shortcut variable so length equals Matt dot node underscore tree dot links so we're taking the list of all of the different connections between nodes and storing inside of links this will make it easy to add to and then I'm going to create a new link equals links no new and then in these brackets this is where we're gonna make the connection this is quite easy to understand actually because now that we know exactly where the addresses for inputs and outputs are in terms of arrays we can just type them in here so node underscore omission dot outputs 0 comma material output dot inputs 0 so to take a look at this visually node emission which is our mission shader door outputs so the right side position 0 which is this omission thing and material output this node door inputs left side position 0 surface so it's gonna make a link between these two like that so if I delete the subject run the script okay we'll see Python script failed now this is a good demonstration of debugging if I open the console line 47 I've made a mistake it says name Matt is not defined that's because I've incorrectly written the variable name did he notice so before I've created a variable new Matt to represent our material they here I've only written Matt so I need to resolve this by fixing it typing new Matt now if I delete the object and run the script again everyone's fine now if I go into the rendered mode and I should also really set the world background to black then we have the emissive object here and if we take a look at the material nodes it automatically creates a principle be SDF we don't need that but the emission shader has been created the color has been set to cyan and the strength has been set to 500 the connection has also been made between the output position 0 and the input position 0 of these two nodes but of course we can't really see the color that much here so let me just like increase the intensity value of the bloom in Eevee and then we can see the blue outline so well done with this script so far we have imported the modules created a cube made of the selected object rotate today added a subsurf modifier increase the subdivision levels shaded it's smooth added a displacement modifier created a texture for that modifier change the texture values specifically the noise scale then assign the texture to the displacement modifier then created a new material appended it to the object then we did some node stuff basically making a reference to the material output node creating an emissive shader node changing the values of the emissive shader and then connecting those two nodes together so so far this has given you a demonstration of how to manipulate most of the major types of data inside of a blend file but how do we take this further okay this is where it gets a little bit more complicated I imagine that some people might want to drop off of the video here and now I'm actually gonna show you how to turn this script into an actual addon so this is something that you'd be able to cool from a blend file and it would be able to pop up in the bob left of the 3d view with a bunch of parameters that you could change on the fly okay so inside of blender you can actually go to templates here in the text editor window and then there's templates for Python and open shading language or OSL scripts this is a good way to study using Python for blender because you can see all of these different demonstrations of code that you can study for yourself one that we're gonna make you so for turning our script into an add-on is operator simple so if we click on this it will add a new text file to our list of files and it's called operate a simple PI now we're not gonna need everything in here in fact what we can do is delete this def main section we're going to delete this class method section we've def Pole basically all of our code that we're gonna use we're gonna put inside of this area called death execute and I'll explain this a bit more imagine this code as like wrapping paper or packaging for an order something you've proved online so if you've brought something from Amazon it gets delivered to you the the only thing you're interested in is the actual product itself but to get that product to you Amazon has to package it up and apply labels and stuff and it's all really boring is essential because without that packaging Amazon and the Postal Service has no idea where to put the product or rather where to send the product now we've making an add-on in Python for blenders something similar applies inside of this death execute section this is where our product or our code is going to go everything else is just wrapping paper packaging and labels and important stuff for blender to know it but not ready for us so whenever someone runs your add-on it will execute everything inside of the execute section everything between F execute and return finished this section of code here who would deaf pole basically that's us look at the context of the blend file and see whether it's an appropriate time to run our code or not in this case returning context the active object is not nothing so basically looking to see if an object is selected before we can run the operation we don't really need this for our situation it's not required you don't need it but it's there if you want to plus you always have the option of writing your own exception inside of execute here to see whether or not an object is selected to say whether or not you will actually run the rest of your code so there's lots of options available to you now in this video so far we haven't talked about classes or defining functions functions are a way that you can store code and then recall them really easily so say for example they'll be put code inside of execute here and let's say I want to do the same thing over and over and over again but I didn't want to have to write the same code out over and over again then I could always type our execute and then the round brackets and I can do again and again so it saves you time of writing code repeatedly but in the case of writing add-ons for blender blender looks for very specific functions which is why execute and poll are unique because blender will look for them and then recall them in certain situations at the top here this is like the label on our packaging this basically tells blender where to store stuff so if I remove tooltip I'm actually going to name or class my operator so BL underscore ID name you can think of this as the code address for our add-on so objects dots I'm gonna name it my underscore operator so say someone wanted to call our add-on from the Python console they were type in something like ppy Dobbs dot then object don't my operator object dot my operator whatever we changed this to we would have to change down here as well and we can see in this template script that at the bottom there's a section for a test call so this is where we would actually test to see if the operator has successfully been registered so I could type in my operator here okay now we'll take a look at this bit so you'll see two more special functions here def register and DEF unregister this is how we actually submit our add-on to blender when this script runs then it will reach this line and it will run bpy utils for utilities the register class and then it will be our class name so I've got to change this to my operator and then when blender is done with the code perhaps when it closes or we uninstall it it will run the unregister function for my operator and you don't need to understand necessarily what these lines mean but it basically means that if we're running the script standalone here inside of the editor then it will make sure to call the register function so when we run the script for the first time it will actually add the operator to blenders list of all the operators so let's give this a try I'm gonna run the script now all to P of course nothing will happen we've got no code here then if I go to the search function which you can get to by pressing f3 and type in simple object operator because that's the name we have here then you will see appear here in the list if you click on it it will do nothing I'm actually gonna change this name to make it more consistent to my operator and if I save run the script search my operator it will appear there so now we have it available in the list of operators so now what we need to do is add the code to this execute section so I'm gonna go back to our regular text file we can literally copy all of it except for the import stuff but we'll need to remember this go back here paste it in and then we got to make sure that our indentations are correct so I'm gonna straight all this tab once tap twice that's appropriate indentation if we ran this now we would get an error because remember we need to import radians from math so I'm gonna copy this line put this in here that's fine then I'm going to run the script alt P now it actually created a new cube object again because we have this test cool at the bottom here so I'm gonna delete both run it again just to demonstrate the ego created it again so if I delete this now go to our search menu find my operator if I click on this it calls the script all well and good so now we've added it to blender so if you wanted to give this script to someone else to install as an add-on you could just take all this code copy into a text file save it as a PI file and give that someone else they could then go and install it preferences add-ons install and then choose the PI file it's that simple however of course there are some caveats because there are some conventions that you should follow especially with 2.8 and onwards but we're not gonna cover that in this video but one of the last things I want to show you is how to get a properties window in the bottom left here of the 3d view so we can adjust the values and actually watch our mesh change as we've created it but before we do that there's one more thing on a word if you want to let your operation be compatible with blenders undo system you need to register it with the undo system so underneath be a label we could do BL under scope options equals and then we using the curly brackets instead of the round brackets the first string is register in capitals the second string is undo in capitals so I can run this again there we go no errors fine now as for creating their properties here in the bottom left this is where things get slightly more advanced again so we're taking another step up in complexity just like we've created this packaging these labels for our add-on code for the variables that we want to modify live we also need to create some packaging for them so to speak so inside of our class we need to create properties and properties are essentially our variables but they're just glorified variables really we can give them like names and descriptions and stuff as well basically metadata to go along with the actual value to do this I will need to import one more thing I only type in from bpy props mining properties import and then the asterisk which means import everything because there are many different types of properties representing different datatypes integers strings boolean's enumerations stuff like that if you've never done coding before a lot of those words won't mean anything to you that's because python so far has been a loosely typed language in terms of datatypes basically whenever we create a new variable like a modifier or a texture we don't need to tell Python what type that variable is going to be because as soon as we assign it - goes oh okay this is a texture or this is a modifier and stuff like that it automatically figures it out for you but it comes to properties this is not the case we need to say specifically what type you want the variable to be so blender knows how to present it for example if it's an integer it needs to know to create this kind of box for it where we can scrub up and down or if it's a boolean it needs to know to create a tick box for us so that's why it's important for blender to know so I'm going to tie a comment here create properties now because in our script we're modifying the noise scale of the texture we're going to type in noise scale and then need to do a colon float property now a float otherwise known as a floating point value is basically a decimal value like the fresh hold here 2.0 it's got a point there at that point can float between the numbers then I'm going to open a round bracket leave a couple of lines closed around bracket and then type in name equals noise scale description equals the scale of the noise you can write whatever you like and also notice I'm putting commas after each of these values default equals and then you put the default value I'm going to put our one point zero that seems appropriate min equals zero point zero and Max equals two point zero so the minimum value for example if we were playing around with this threshold value would be 0 and the in the threshold value here is 10 so we can set minimum and maximum values if we like okay so basically we've created a property called noise scale and we've given blender a bunch of contextual information so it now knows how to present that property in an extra window so now we need to replace in our code the hard-coded noise scale value here with the property we've created and to do this all we need to do is type in a set of 2.0 self dot noise scale basically whenever you want to access a property you've created inside of the class you need to type in self and what that means is it looks at itself naturally and then finds the noise underscore scale so I can save run the script and then it creates this cube but if we run the script from here there doesn't come up the properties window so let me delete it search my operator click and then you'll see here in the bottom left my operator I can click this to expand it then it says noise scale and then it's got a box which we can scrub relevant for a floating-point value and if we hover over it at or tip appears and you can see it's got noise scale and our description we've written in the scale of the noise so this is how you can create properties which you can change as you create an object using your addon so yeah so this has been your crash course into Python for blender with me Curtis Holt hopefully this has taught you something we've covered quite a lot of stuff especially for someone who's new to Python different ways of accessing the different types of data within blend files and hopefully this has given you enough information that you can actually go on ahead and write your own scripts and add-ons and start experimenting if you want to download the final copy of this file then I will put a link to it in the description so feel free to give that download and also if you want to support my work then feel free to leave a tip on the package I appreciate all of the support from you generous and lovely people all right so now we've come to the end of the video we're gonna take a minute to talk about the sponsor for this video which is Sketchup you may already know sketchfab for providing the best free d-model viewer for the web but you might not know that they actually have an online store for buying and selling 3d models you can use the built in model inspector to preview the geometry of the mesh along with all the textures so you know exactly what you're getting there's a wide range of content available and a good number of dedicated artists providing high quality content if you're interested in maybe selling your own models store then you can also consider applying to become a seller sketchfab has been well integrated with the blender community for a long time and continues to provide a valuable service for all kinds of artists so thanks for sponsoring this video sketchfab and thanks to the rest of you for watching make sure to follow me on all the appropriate platforms you can also join our discord server with the link in the description so thanks for watching have a great day and I'll see you next time [Music] now if I do the object
Info
Channel: Curtis Holt
Views: 113,575
Rating: undefined out of 5
Keywords: blender 2.8, 2.83, 2.9, crash, course, new, tutorial, tutorials, python, coding, code, programming, procedural, addon, resources
Id: XqX5wh4YeRw
Channel Id: undefined
Length: 44min 43sec (2683 seconds)
Published: Fri Jul 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.