{"id":13765787,"url":"https://github.com/jtomori/vex_tutorial","last_synced_at":"2025-05-10T21:31:53.106Z","repository":{"id":37550005,"uuid":"119985858","full_name":"jtomori/vex_tutorial","owner":"jtomori","description":":bookmark_tabs: A collection of code snippets and examples showing syntax and capabilities of VEX language inside SideFX Houdini","archived":false,"fork":false,"pushed_at":"2021-07-27T23:21:48.000Z","size":2476,"stargazers_count":712,"open_issues_count":1,"forks_count":137,"subscribers_count":89,"default_branch":"master","last_synced_at":"2024-08-03T16:08:56.152Z","etag":null,"topics":["houdini","tutorial","vex","vfx"],"latest_commit_sha":null,"homepage":"https://jtomori.github.io/vex_tutorial/","language":"C","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jtomori.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-02-02T13:36:14.000Z","updated_at":"2024-07-24T20:19:23.000Z","dependencies_parsed_at":"2022-07-12T16:22:56.285Z","dependency_job_id":null,"html_url":"https://github.com/jtomori/vex_tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jtomori%2Fvex_tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jtomori%2Fvex_tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jtomori%2Fvex_tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jtomori%2Fvex_tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jtomori","download_url":"https://codeload.github.com/jtomori/vex_tutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224989507,"owners_count":17403408,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["houdini","tutorial","vex","vfx"],"created_at":"2024-08-03T16:00:45.871Z","updated_at":"2024-11-17T01:31:25.859Z","avatar_url":"https://github.com/jtomori.png","language":"C","readme":"# VEX tutorial\n\n*A collection of code snippets and examples showing syntax and capabilities of VEX language inside SideFX Houdini*\n\u003cp align=\"right\"\u003e\u003csmall\u003eby Juraj Tomori\u003c/small\u003e\u003c/p\u003e\n\n# How to use it\nYou can clone, or [directly download](https://github.com/jtomori/vex_tutorial/archive/master.zip) this repository.\n\nIt contains `examples.hipnc` and `vex/include/myLib.h` files which are full of various examples with explanations in comments.\n\nIt is the best to check all the nodes with open *Geometry Spreadsheet* and *Console Output* windows to see values of attributes and output text. Alternatively you can use this page for quick looking at the topics covered and most of the code that I include here as well. I am not including here all of the code since sometimes it might not make a lot of sense outside of Houdini. Where necessary I include related functions from *myLib.h* or attach screenshots.\n\n# Topics\n* [Reading parameter values](#reading-parameter-values)\n* [Reading attributes](#reading-attributes)\n* [Exporting attributes](#exporting-attributes)\n* [Reading arrays](#reading-arrays)\n* [Arrays](#arrays)\n* [Arrays and strings example](#arrays-and-strings-example)\n* [Reading and writing Matrices](#reading-and-writing-matrices)\n* [Checking for attributes](#checking-for-attributes)\n* [Automatic attribute creation](#automatic-attribute-creation)\n* [Getting transformation from OBJs](#getting-transformation-from-objs)\n* [Intrinsics](#intrinsics)\n* [VDB intrinsics](#vdb-intrinsics)\n* [Volumes](#volumes)\n* [VOPs / Using Snippets](#vops--using-snippets)\n* [VOPs / Using Inline Code](#vops--using-inline-code)\n* [DOPs / Volumes workflow](#dops--volumes-workflow)\n* [DOPs / Gas Field Wrangle](#dops--gas-field-wrangle)\n* [DOPs / Gas Field Wrangle - accessing DOPs and SOPs data](#dops--gas-field-wrangle---accessing-dops-and-sops-data)\n* [DOPs / Geometry workflow](#dops--geometry-workflow)\n* [DOPs / Geometry Wrangle](#dops--geometry-wrangle)\n* [DOPs / Geometry Wrangle - accessing fields](#dops--geometry-wrangle---accessing-fields)\n* [Conditions](#conditions)\n* [Loops](#loops)\n* [Stopping For-Each SOP from VEX](#stopping-for-each-sop-from-vex)\n* [Printing and formatting](#printing-and-formatting)\n* [Printing attributes](#printing-attributes)\n* [Including external VEX files](#including-external-vex-files)\n* [Include math.h](#include-mathh)\n* [Using macros](#using-macros)\n* [Functions](#functions)\n* [Functions overloading](#functions-overloading)\n* [Variables casting](#variables-casting)\n* [Vectors swizzling](#vectors-swizzling)\n* [Functions casting](#functions-casting)\n* [Structs](#structs)\n* [Structs in Attribute Wrangle](#structs-in-attribute-wrangle)\n* [Groups](#groups)\n* [Attribute typeinfo](#attribute-typeinfo)\n* [Attributes to create](#attributes-to-create)\n* [Enforce prototypes](#enforce-prototypes)\n* [Attribute default values](#attribute-default-values)\n\n# Tutorial\n\n## Reading parameter values\n~~~ C linenumbers\n/*\nmulti-line comments can be typed\nusing this syntax\n*/\n\n// in vex you can evaluate values from parameters on this node\n// by calling ch*() function, with * representing a signature, check the docs\n// for the full list, some of them: chv() - vector, chu() - vector2, chs() - string\n// chramp() - ramp, chp() - vector4, chi() - int, chf() - float, ch4() - matrix, ch3() - matrix3 ...\n// you can also use optioinal argument for time which will enable you to evaluate\n// the channel at different frame\n//\n// once you type ch*() in your code, you can press a button on the right, to\n// generate a UI parameter for it automatically, you can do the same by hand as well\nfloat y = chf(\"y_position\");\nvector col = chv(\"color\");\nmatrix3 xform = ch3(\"xform\");\n\n// you can also reference parameters from external nodes\n// if there is an expression (Python/hscript) in the parameter,\n// it will be evaluated\nfloat up = chf(\"../params_1/move_up\");\n\n\n// apply variables to attributes\nv@P.y += y*5;\nv@Cd = col;\nv@P *= xform;\nv@P.y += up;\n\nv@myVec = 1.456;\nv@myVec += v@N.y;\n~~~\n\n## Reading attributes\n~~~ C linenumbers\nfloat blend = chf(\"blend\");\nfloat blendPig = chf(\"blend_pig\");\nvector P1, P2, P3, P_new;\n\n// this is one way of reading attributes, this is only valid, when\n// point count is exactly the same in both inputs, then attribute from\n// point from second input with the same @ptnum is retrieved\n// v@P can also be replaced with @P, since its signature can be guessed as it is\n// commonly used attribute, however I prefer explicit declaration :)\n// v@ - vector, i@ - integer, f@ - float, 3@ - matrix3, p@ - vector4\n// 4@ - matrix4, 2@ - matrix2, u@ - vector2, s@ - string,\n//P1 = v@P;\n//P2 = v@opinput1_P; // inputs numbering starts at 0, therefore 1 refers to the second input\n\n// this approach is useful for querying attributes from different points (other from the currently processed one)\n// node input numbering starts from 0 (first input), 1 (second input) ...\nP1 = point(0, \"P\", @ptnum);\nP2 = point(1, \"P\", @ptnum);\n\n// note that you can also read attributes from node, which is not connected\n// to the current node using the \"op:\" syntax\n// this is valid for any function which is expecting geo handle (sampling from other volumes...)\n// note that Houdini network UI will not detect this dependency when Show -\u003e Dependency links display is enabled\nP3 = point(\"op:../pig_shape\", \"P\", @ptnum);\n\n\n// blend positions\nP_new = lerp(P1, P2, blend);\nP_new = lerp(P_new, P3, blendPig);\n\nv@P = P_new;\n~~~\n\n## Exporting attributes\n~~~ C linenumbers\n// create a new attribute simply by typing *@attrib_name with\n// * representing its signature\n// v@ - vector, i@ - integer, f@ - float, 3@ - matrix3, p@ - vector4\n// 4@ - matrix4, 2@ - matrix2, u@ - vector2, s@ - string\n\nv@myVector = {1,2,3};\n// vectors with functions/variables in them need to be created with set()\nu@myVectorFunc = set(@Frame, v@P.y);\nu@myVector2 = {4,5};\nf@myFloat = 400.0;\ni@myInteger = 727;\n3@myMatrix3x3 = matrix3( ident() ); // this line contains function casting, which is explained in functions_casting section\n4@myMatrix4x4 = matrix( ident() );\ns@myString = \"abc\";\n\n\n// attributes can be set to different point from the currently processed one\n// and if they do not exist, they need to be added first\n// setpointattrib() is also the only way of setting an attribute on newly\n// created points\naddpointattrib(0, \"Cd\", {0,0,0});\nsetpointattrib(0, \"Cd\", 559, {1,0,0});\n\n// arrays can be exported as well\nv[]@myVectorArray = { {1,2,3}, {4,5,6}, {7,8,9} };\nu[]@myVector2Array = { {4,5}, {6,7} };\nf[]@myFloatArray = { 4.0, 2.7, 1.3};\ni[]@myIntegerArray = {132, 456, 789};\n// arrays containing functions/variables need to be initialized with array() function\n3[]@myMatrix3x3Array = array( matrix3( ident() ), matrix3( ident() ) * 5 );\n4[]@myMatrix4x4Array = array( matrix( ident() ), matrix( ident() ) * 9 );\ns[]@myStringArray = { \"abc\", \"def\", \"efg\" };\n~~~\n\n## Reading arrays\n~~~ C linenumbers\n// this is how you can create local array variables and load array attributes into them\nvector myVectorArray[] = v[]@myVectorArray;\n\nmatrix3 a = ident() * 5;\n\nv@P.x *= a.yy; // you can access matrix components using this syntax\n// x -\u003e 1st element, y -\u003e 2nd, z -\u003e 3rd, w -\u003e 4th\nv@P.y = 4[]@myMatrix4x4Array[1].ww; // second array matrix, last element\nv@P.z = u[]@myVector2Array[1][0]; // this is how you can access array of vectors - second array, first element\n~~~\n\n## Arrays\n~~~ C linenumbers\nint numbers[] = array(1,2,3,4);\n\n// arrays can be handled in Pythonic way\nnumbers = numbers[::-1]; // array reverse\n\n// rading from arrays\ni@firstItem = numbers[0];\n// writing into arrays\nnumbers[0] += 1;\n// indexing can also go backwards\ni@secondLastItem = numbers[-2];\n\n// slicing\ni[]@firstHalf = numbers[:2];\ni[]@secondHalf = numbers[2:];\n\n// some useful functions\ni@returnedPopVal = pop(numbers); // removes the last element and returns it\npush(numbers, i@returnedPopVal); // appends element to the array\ni@lenghtOfArray = len(numbers);\n\n// export into integer array attribute\ni[]@numbers = numbers;\n\n// flattening an array of vectors and reverting it\nvector vectors[] = { {1,2,3}, {4,5,6}, {7,8,9} };\nf[]@serializedVectors = serialize(vectors);\nv[]@unserializedFloats = unserialize(f[]@serializedVectors);\n~~~\n\n## Arrays and strings example\n~~~ C linenumbers\n// simple example of manipulating strings and arrays\n// it will convert /path/to/the/project/file/project_v3.hipnc\n// into            /path/to/the/project/file/preview/project_v3_img_0001.jpg\n// with 0001 being current frame number\n\nstring path = chs(\"path\"); // get string from path parameter of the current hipfile\ns@pathOrig = path; // store into attribute original value\n\nstring pathSplit[] = split(path, \"/\"); // split path into array of strings based on \"/\" character\n\nstring fileName = pop(pathSplit); // remove last value of the array and assign it into a variable\nstring fileNameSplit[] = split(fileName, \".\"); // split string into an array based on \".\" character\nfileNameSplit[0] = fileNameSplit[0] + sprintf(\"_img_%04d\", @Frame); // append into the string _img_0001 (current frame number)\nfileNameSplit[-1] = \"jpg\"; // change file extension\nfileName = join(fileNameSplit, \".\"); // convert array of strings into a one string with \".\" between original array elements\npush(pathSplit, \"preview\"); // append \"preview\" string into the array of strings\npush(pathSplit, fileName); // append file name into the array of strings\n\npath = \"/\" + join(pathSplit, \"/\"); // convert array of strings into one string, starting with \"/\" for root, because it is not added before the first element, only to in-betweens\n\ns@path = path; // output into the attribute\n~~~\n\n## Reading and writing Matrices\n~~~ C linenumbers\n// To intilize a vector or a matrix with a variable/attribute we have to use the set method\nfloat   f = 0;\nvector  v = set(f,f,f);\nmatrix3 m = set(f,f,f,f,f,f,f,f,f);\n        m = set(v,v,v);\n\n// We can then read the value back by\nfloat f = getcomp(m,0,0);\n// However we can not read back a vector directly instead we have to use:\nf = set(getcomp(m,0,0));\nv = set(getcomp(m,0,0),\n        getcomp(m,0,1),\n        getcomp(m,0,2));\n// Likewise the setcomp can be used\nsetcomp(m,f,0,0);\n~~~\n\n## Checking for attributes\n~~~ C linenumbers\n// it is also possible to determine if incoming geometry has an attribute\n\ni@hasCd = hasattrib(0, \"point\", \"Cd\");\ni@hasN = hasattrib(0, \"point\", \"N\");\ni@hasOrient = hasattrib(0, \"point\", \"orient\");\ni@hasPscale = hasattrib(0, \"point\", \"pscale\");\n~~~\n\n## Automatic attribute creation\n~~~ C linenumbers\n// if you use @attribute and it does not exist, \n// then it will be automatically created\n// this might lead to problems, when you have a typo and a \n// new attribute is created\n\nf@foo = 4;\nf@boo = v@Cd.y;\n//v@CD = {1,1,0}; // this line does not work here, otherwise it would crete new v@CD attribute\n\n// if you remove * chracter from \"Attributes to Create\" parameter\n// bellow, then you need to manually specify new attributes\n// to be created, if you then have a typo and use v@CD instead\n// of v@Cd, node will report an error\n~~~\n\n## Getting transformation from OBJs\n~~~ C linenumbers\n// VEX is well integrated into Houdini, it can for example fetch\n// world space transformation matrix from an OBJ node, let it be a null OBJ\n// or part from a rig, camera or whatever object there which has a transformation\n// optransform() will contain also all parent transformations\n\nstring nodePath = chs(\"node_path\"); // parameter is a string, but I went into \"Edit Parameter Interface\" and specified it to be a Node Path\nmatrix xform = optransform(nodePath);\n\nv@P *= invert(xform);\n~~~\n\n## Intrinsics\n~~~ C linenumbers\n// a lot of information and functionality is stored in\n// \"intrinsic\" attributes, they might be hidden to many users\n// because they do not show up in primitive attributes list\n// by default\n// they are however very useful and important for manipulating\n// and controlling those primitives from VEX\n\n// you can display intrinsics in Geometry Spreadsheet, in primitive attributes\n// and Show All Intrinsics in Intrinsics drop-down menu\n// intrinsics that are greyed out are read-only, the rest is also writable\n\n// in this example I will show you how to access and modify those\n// values, I will refer to them based on their point numbers as\n// those intrinsics vary based on the primitive we are dealing with\n// 0 - packed geo, 1 - VDB, 2 - sphere, 3 - packed disk, 4 - abc\n// if you change order of inputs in merge, then those numbers will change\n// in our case @ptnum matches @primnum\n\n// this is the type of our primitive\ns@primitiveType = primintrinsic(0, \"typename\", @ptnum);\n\nmatrix3 xform = ident();\n\n// sphere\nif (@ptnum == 2) {\n    // accessing sphere volume and area\n    f@sphereVolume = primintrinsic(0, \"measuredvolume\", @ptnum);\n    f@sphereArea = primintrinsic(0, \"measuredarea\", @ptnum);\n    \n    // changing sphere scale, rotation which is not accessible through standard attributes\n    // this intrinsic is also present on other primitives\n    xform = primintrinsic(0, \"transform\", @ptnum);\n    scale(xform, {1,2,3});\n    rotate(xform, radians(45), normalize({1,2,3}) );\n}\n\n// packed geo\nif (@ptnum == 0) {\n    // change viewport display to point cloud\n    setprimintrinsic(0, \"viewportlod\", @ptnum, \"points\", \"set\");\n    \n    // move packed's pivot to the bottom\n    // bounds are stared in this order: xmin, xmax, ymin, ymax, zmin, zmax\n    float bounds[] = primintrinsic(0, \"bounds\", @ptnum);\n    vector pivot = primintrinsic(0, \"pivot\", @ptnum);\n    pivot.y = bounds[2];\n    setprimintrinsic(0, \"pivot\", @ptnum, pivot, \"set\");\n    v@P.y = bounds[2];\n    \n    // and now transform the primitive along its new pivot :)\n    xform = primintrinsic(0, \"transform\", @ptnum);\n    scale(xform, {1,2,3});\n    rotate(xform, radians(-45), normalize({1,2,3}) );\n}\n\n// packed disk\nif (@ptnum == 3) {\n    // changing this intrinsic can point the primitive into different geometry on disk\n    // so instead of boring cube let's have something way cooler\n    // this is very powerful - e.g. controling your instances, see my other blog post about using it\n    // https://jurajtomori.wordpress.com/2016/09/29/rain-and-ripples-rnd/\n    setprimintrinsic(0, \"unexpandedfilename\", @ptnum, \"$HH/geo/HoudiniLogo.bgeo\", \"set\");\n    \n    // and our mandatory transformation :)\n    xform = primintrinsic(0, \"transform\", @ptnum);\n    scale(xform, 5);\n    rotate(xform, radians(-90), {1,0,0} );\n}\n\n// alembic\nif (@ptnum == 4) {\n    // make him move in the loop, he has 48 frames of animation\n    float frame = @Frame / 24;\n    frame = frame % 2;\n    setprimintrinsic(0, \"abcframe\", @ptnum, frame, \"set\");\n    \n    // get some useful info\n    s@abcObjPath = primintrinsic(0, \"abcobjectpath\", @ptnum);\n    s@abcFilePath = primintrinsic(0, \"abcfilename\", @ptnum); // also useful intrinsic\n    s@abcType = primintrinsic(0, \"abctypename\", @ptnum);\n    s@abcVis = primintrinsic(0, \"viewportlod\", @ptnum);\n    \n    // scale the bear up\n    xform = primintrinsic(0, \"transform\", @ptnum);\n    scale(xform, 20);\n}\n\n// all of the primitives have \"transform\" intrinsic, so I update it at the end\nsetprimintrinsic(0, \"transform\", @ptnum, xform, \"set\");\n~~~\n\n## VDB intrinsics\n~~~ C linenumbers\n// for some reason updating VDB's transform and other primitives transform\n// did not work properly from one wrangle, so I put it here\n// VDB's transform is 4x4 matrix, while other prims have 3x3 matrices\n\n// VDB\nif (@ptnum == 1) {\n    // accessing useful information\n    i@vdbVoxels = primintrinsic(0, \"activevoxelcount\", @ptnum);\n    s@vdbClass = primintrinsic(0, \"vdb_class\", @ptnum);\n    s@vdbType = primintrinsic(0, \"vdb_value_type\", @ptnum);\n    s@vdbVis = primintrinsic(0, \"volumevisualmode\", @ptnum);\n    v@vdbVoxelSize = primintrinsic(0, \"voxelsize\", @ptnum);\n    \n    // changing volume transformation\n    matrix xform4 = primintrinsic(0, \"transform\", @ptnum);\n    scale(xform4, {1,2,3});\n    rotate(xform4, radians(-45), {1,0,0});\n    setprimintrinsic(0, \"transform\", 1, xform4, \"set\");\n    \n    // setting volume export precision to half float, which saves space when written to disk\n    setprimintrinsic(0, \"vdb_is_saved_as_half_float\", @ptnum, 1, \"set\");\n}\n~~~\n\n## Volumes\n~~~ C linenumbers\n// float volumes can be accessed with volumesample(), vector volumes need\n// volumesamplev() function, those functions expect sampling position, which\n// does not need to match voxel's center, then the value will be tri-linearly\n// interpolated from neighbouring voxels\nfloat den1 = volumesample(0, \"density\", v@P);\n\n// sampling position can be offset and lots of cool tricks and magic can be\n// acheived with that\nvector offset = set( 2, sin(@Frame * .1)*2 , 0 );\nfloat den2 = volumesample(1, \"density\", v@P + offset);\n\n// writing to volumes has the same syntax as writing to attributes\nf@density = lerp(den1, den2, chf(\"blend\") );\n\n// volumes can be accessed with the same syntax as geometry attributes\nf@density = f@density * chf(\"scale\");\n~~~\n\n## VOPs / Using Snippets\n*Check Houdini project to get the best idea of how it works.*\n~~~ C linenumbers\n// in snippets we do not need to use any sign for variables, only\n// their name is needed\n// it is also possible to rename them for this node in\n// Vaiable Name parameters bellow\n\n// to output a new variable, we need to input a constant\n// into the node which will generate output for it (N, color)\n// even though in the UI it is called outN and outcolor, we only\n// need to write to N and color\n\nN = normalize(P);\ndir = normalize(dir);\n\nfloat mix = dot(dir, N);\nmix = clamp(mix, 0, 1);\n\nnoise = abs(noise);\nnoise = clamp(noise, 0, 1);\n\ncolor = lerp(frontColor, noise, 1-mix);\n~~~\n\n## VOPs / Using Inline Code\n*Check Houdini project to get the best idea of how it works.*\n~~~ C linenumbers\n// here we can create additional output variables\n// however we cannot write to read_only variables (which\n// are not exported), therefore for loading $dir I create\n// direction variable and for loading $noise noise_in variable\n\n$N = normalize(P);\nvector direction = normalize(dir);\n\nfloat mix = dot(direction, N);\nmix = clamp(mix, 0, 1);\n\nvector noise_in = abs(noise);\nnoise_in = clamp(noise_in, 0, 1);\n\n$color = lerp($frontColor, noise_in, 1-mix);\n~~~\n\n## DOPs / Volumes workflow\nHere I will show basic steps of creating a simple custom DOP solver operating on volumes.\n\n1. At first we need to create a *DOP Object*, which is a container that will contain all our fields (volumes in DOPs), geometry and any other data. Object name is important, because later we will use it to access our data.\n![DOP Object](./img/dop_object_volume.jpg)\n\n2. In the second step we want to bring in a volume from SOPs. We can use *SOP Scalar Field* node. This node will create field *pig_in*, which you can see in *Geometry Spreadsheet*. *Use SOP Dimensions* option is handy as we do not need to set resolution, size and other parameters by hand. *Border Type* might be useful to have set to *Constant* as it will not introduce infinite streaks when voxels are touching boundaries. *SOP Path* points to the SOP we want to get volume from and *Primitive Number* will identify which volume primitive to import. *Default Operation* when set to *Set Initial* will import the field only at first simulated frame, if you want to import animated volume, set it to *Set Always*. *Data Name* is important as it will be unique identifier for our volume.\n![SOP Scalar Field](./img/sop_scalar_field.jpg)\n\n3. DOPs can contain lots of fields and therefore they are not visible by default. To display them in viewport, we can use *Scalar Field Visualization* node.\n![Scalar Field Visualization](./img/scalar_field_vis.jpg)\n\n4. If we want to sample different volume, or sample a volume at different location, we need to set up *Inputs* properly. This is needed for *Gas Field Wrangle* and *Gas Field VOP*.\n![Gas Field Wrangle Inputs](./img/gas_field_wrangle_inputs.jpg)\n![Gas Field VOP Inputs](./img/gas_field_vop_inputs.jpg)\n\n5. We can also use arbitrary SOP operators to process our DOP fields. We can do so by using *SOP Solver*. We just need to set *Data Name* to our field which we want to process.\n![Sop Solver volume](./img/sop_solver_volume.jpg)\n\n## DOPs / Gas Field Wrangle\n*Check Houdini project to get the best idea of how it works.*\n~~~ C linenumbers\n// we can access fields as in the SOPs, pig_in name\n// corresponds to \"Data Name\" in sopscalarfield_init_pig_in node\nf@pig_in *= .9;\n\n// by default this line will not work, even though it should\n// be the same as the previous line\n// to make it work, we need to point \"Input 1\" in the \"Inputs\" tab\n// to the field we want to fetch, in our case \"volume/pig_in\"\n// this way we can access also fields from another DOP objects\n// (\"volume\" is our DOP object in this case)\n//f@pig_in = volumesample(0, \"pig_in\", v@P)  *.9;\n\n// if we want to sample from another position, we also need\n// to set up \"Input 1\" properly\n// note that you can also sample from volumes in SOPs if you\n// specify path to it: set \"Input 1\" to *SOP* and point \"SOP Path\" \n// to the volume you want to access\n//f@pig_in = volumesample(0, \"pig_in\", v@P - {0.01});\n~~~\n\n## DOPs / Gas Field Wrangle - accessing DOPs and SOPs data\n~~~ C linenumbers\n// it is also possible to access DOP fields using this syntax\n// we can sample \"pig_mask\" without setting the field \"Inputs\"\n\nfloat pig_mask = 0;\n// the following lines bellow are identical, the second and third ones are more flexible as they use relative path:\n// it will work even if we renamed this DOP network, the first line would not work after that\n// the second argument is either an int representing primitive number, or string representing primitive name\n// the syntax for accessing DOP data is: op:/DOP_node_path:dop_object_name/field_name\n\npig_mask = volumesample(\"op:/obj/examples/dopnet_vex_vops_volume:volume/pig_mask\", 0, v@P);\n//pig_mask = volumesample(\"op:\" + opfullpath(\"../\") + \":volume/pig_mask\", \"pig_mask\", v@P);\n//pig_mask = volumesample(\"op:../\" + \":volume/pig_mask\", 0, v@P); // op: syntax also accepts relative paths\n\n// we can also directly access SOP volumes using this syntax\n//pig_mask = volumesample(\"op:../../IN_VOLUMES\", 1, v@P);\n\nf@pig_in *= 1-pig_mask;\n~~~\n![Gas Field Wrangle - DOPs and SOPs data](./img/gas_field_wrangle_dop_sop_data.jpg)\n\n## DOPs / Geometry workflow\nHere I will show basic steps of creating a simple custom DOP solver operating on volumes.\n\n1. At first we need to create a *DOP Object*, which is a container that will contain all our fields (volumes in DOPs), geometry and any other data. Object name is important, because later we will use it to access our data.\n![DOP Object](./img/dop_object_box.jpg)\n\n2. We can import a geometry from SOPs using *SOP Geometry* node. By enabling *Use External SOP* we can select a SOP we want to import. *Data Name* is usually set to *Geometry*.\n![SOP Geometry](./img/sop_geometry.jpg)\n\n3. If we want to use functions which take an input as an argument (looking up points, importing point attributes...) in [*Geometry Wrangle*](#dops--geometry-wrangle) or *Geometry VOP*, we need to set up our *Inputs* properly.\n![Geometry Wrangle](./img/geo_wrangle_inputs.jpg)\n![Geometry VOP](./img/geo_vop_inputs.jpg)\nAlso note, that *Geometry Wrangle* and *Geometry VOP* have an option to use *Myself* in *Inputs* which is equivalent to previous settings.\n![Geometry VOP Myself](./img/geo_vop_inputs_myself.jpg)\n\n4. We can as well use *SOP Solver* to process our geometry in a SOP network.\n![SOP Solver geo](./img/sop_solver_geo.jpg)\n\n## DOPs / Geometry Wrangle\n*Check Houdini project to get the best idea of how it works.*\n~~~ C linenumbers\n// we can access attributes from \"Geometry\" data in our \"box\"\n// object with this syntax\n// however if we want to access other point's attributes, we need\n// to properly set \"Input 1\" in \"Inputs\" tab of this node\nv@P *= 1.1;\n~~~\n\n## DOPs / Geometry Wrangle - accessing fields\n~~~ C linenumbers\n// we can also access DOP fields from Geometry Wrangle, it is explained in:\n// /obj/examples/dopnet_vex_vops_volume/gasfieldwrangle_accessing_DOPs_and_SOPs_data\n\n// all following lines will produce the same result\nfloat mask = 0;\nmask = volumesample(\"op:../\" + \":box/pig_mask\", 0, v@P);\n//mask = volumesample(\"op:\" + opfullpath(\"../\") + \":box/pig_mask\", \"pig_mask\", v@P);\n//mask = volumesample(\"op:../../IN_VOLUMES\", 1, v@P);\n\n// visualize what points sampled non-zero density in the volume\nif (mask != 0) v@Cd = {1,0,0};\n~~~\n\n## Conditions\n~~~ C linenumbers\n// it there is only one statement after if condition, it\n// can be written in the same line\nif (v@P.y \u003c 0) v@Cd = {1,0,0};\n// or in any other line, since VEX is not indented language,\n// but this works only for one operation, else-if block will end with the first semicolon\nelse if (v@P.x \u003c 0) \n                    v@Cd = {0,1,0};\n// to execute more operations, we need to use a block of code in {} brackets\nelse {\n    v@Cd = {0,0,1};\n    v@P += v@N;\n}\n\n// it is also possible to use conditional (ternary) operator with the following syntax\n// (condition) ? true : false\nv@P.x *= v@P.x \u003e 0 ? 0.5 : 1.5;\n\n// and use of logical AND: \u0026\u0026, OR: || is also possible\nif (v@P.y \u003c 0 \u0026\u0026 v@P.x \u003e 0) v@P -= v@N * .3;\nif (v@Cd == {0,0,1} || v@Cd == {1,0,0}) v@P += v@N * .4;\n~~~\n\n## Loops\n*Check Houdini project to get the best idea of how it works.*\n~~~ C linenumbers\n// VEX uses C-like syntax for for-loops\nint valA = 2;\nfor (int i=0; i\u003c11; i++) {\n    valA *= 2;\n}\ni@valA = valA;\n\n// for convenient iterating over elements of an array we\n// can use foreach loop\nint nbs[] = nearpoints(0, v@P, .5);\n\nvector P_avg = {0};\nforeach(int nb_ptnum; nbs) {\n    P_avg += point(0, \"P\", nb_ptnum);\n}\nP_avg /= len(nbs);\n\nv@P = P_avg;\n\n// we can also stop the loop at any point by using \"break\" keyword\nint valB = 5;\nfor (int i=0; i\u003c13; i++) {\n    valB *= 5;\n    if (valB \u003e 10000000) break;\n}\n\ni@valB = valB;\n\n// we can also use \"continue\" keyword to jump to the next loop iteration\n// in this example we average point position with positions of neighbours\n// which are above it in world space (their Y coordinate is larger)\nint pts[] = neighbours(0, @ptnum);\n\nvector P_avg_upper = {0};\nint count = 0;\n\nforeach(int nb_ptnum; pts) {\n    vector pos = point(0, \"P\", nb_ptnum);\n    if (pos.y \u003c= v@P.y) continue;\n    P_avg_upper += pos;\n    count++;\n}\n\nP_avg_upper /= count;\nv@P = P_avg_upper;\n~~~\n\n## Stopping For-Each SOP from VEX\n~~~ C linenumbers\n// in this example we are offseting our points along X axis in each iteration\n//\n// it is also possible to control For-Each SOP loop from VEX\n// \"Iterations\" count in this loop is set to 300, however we want to stop the loop\n// when our X coordinate is higher then 30\n// to do so, we can use \"Stop Condition\" in the loop, when it equals to 1, the loop will end\n// in this parameter we can use hscript expression checking for detail attribute\n// and we can set this detail attribute from VEX\n// hscript expression: detail(\"../attribwrangle_move_a_bit\", \"repeat\", \"0\") == 0\n\nv@P.x += .3;\n\n// if we comment out the line below, the loop will execute 300 times, otherwise it will execute\n// only until our condition is met\nif (v@P.x \u003e 30) setdetailattrib(0, \"repeat\", 0, \"set\");\n~~~\n\n## Printing and formatting\n~~~ C linenumbers\n// Windows - check console window which \n// should pop up automatically\n// Linux - run Houdini from command line with \n// the -foreground flag to see the output\n\n// manipulating with strings is useful, not only for doing console outputs,\n// but also for generating and stylizing strings, use sprintf() to return a string\n// type instead of printing to console\n\nstring var_string = \"abcdef\";\nfloat var_float = 1.23456789;\nint var_int = 256;\n\nprintf(\"string: %+10s, float: %10.3f, integer: %-6d \\n\", var_string, var_float, var_int);\n// string = abcdef\n// %[+-][length]s\n\n// %10s -\u003e ____abcdef\n// %-10s -\u003e abcdef____\n// %+10s -\u003e __\"abcdef\"\n// %+-10s -\u003e \"abcdef\"__\n\n\n// float = 1.23456789\n// %[+-][0][length][precision]f\n\n// %8.3f -\u003e ___1.235\n// %-8.3f -\u003e 1.235___\n// %08.3f -\u003e 0001.235\n// %+8.3f -\u003e __+1.235 (+ shows sign)\n\n\n// integer = 256\n// %[+-][0][length]d\n\n// %6d -\u003e ___256\n// %+6d -\u003e __+256\n// %-6d -\u003e 256___\n// %06d -\u003e 000256\n\nprintf(\"\\n\");\n\n// escaping characters in string\n// from my testing it requires 4 more backslashes to escape \\n\n// when using raw strings, they are automatically escaped, but @ symbol still\n// needs to be escaped\n// following lines will output the same thing\n// 4 backslashes are needed probably because hscript is parsing this text field\n// and sending to vop's field, see the node bellow\nstring a = 'abc \\\\\\\\\\n \\\\\\\\\\t v\\@P, %04.2f';\nstring b = \"abc \\\\\\\\\\n \\\\\\\\\\t v\\@P, %04.2f\";\nstring c = r\"abc \\n \\t v\\@P, %04.2f\";\nstring d = R\"(abc \\n \\t v\\@P, %04.2f)\";\n\nprintf(a + \"\\n\");\nprintf(b + \"\\n\");\nprintf(c + \"\\n\");\nprintf(d + \"\\n\");\n\nstring multiLine = \nR\"(It is possible to easily create multi\nline strings with this syntax.\nIn some cases it might\nbe useful to do it this way,\nrather then using \\n\nHowever as you have noticed it has weird\n4 characters offset starting on the second line,\nnot sure if it is a bug or feature)\";\n\nprintf(multiLine);\n\nprintf(\"\\n\\n\");\n~~~\n\n## Printing attributes\n~~~ C linenumbers\nprintf(\"s\\@shop_materialpath (string): %+s, v\\@P (vector): %+-10.3f, \\@ptnum (integer): %5d \\n\", s@shop_materialpath, v@P, @ptnum);\n\nprintf(\"\\n\\n\");\n~~~\n\n## Including external VEX files\n~~~ C linenumbers\n#include \"myLib.h\"\n\n// files located in $HIP/vex/include,\n// $HOME/houdiniXX.X/vex/include,\n// $HH/vex/include\n// can be included in wrangles\n\n// to refresh updated header files, \n// promote the \"Force Compile\" button \n// from the attribvop1 node inside of this node, \n// or do a change (add a space somewhere) \n// in the code and press Ctrl+Enter\n\nmyRemPoints(@ptnum);\n~~~\n*From myLib.h:*\n~~~ C linenumbers\n// void functions do not return anything\n// \"function\" keyword is not required\nfunction void myRemPoints(int ptnum) {\n\tif (ptnum \u003e 30)\n    \tremovepoint(0, ptnum);\n}\n~~~\n\n## Include math.h\n~~~ C linenumbers\n#include \"math.h\"\n\n// This include file contains useful math constant macros\n// and is available to every Houdini setup :)\n// You can use couple of constants like\n// e, pi, sqrt(2)...\n//\n// check the file at $HH/vex/include/math.h or end of this wrangle\n\nf@pi = M_PI;\nf@e = M_E;\nf@log2e = M_LOG2E;\n\n// XFORM_SRT and XFORM_XYZ are also constants set to values that functions \n// maketransform() and cracktransform() expect, they define order of transformations\n// and axes\n\nvector tr = {3,4,5};\nvector rot = {0,M_PI,0};\nvector scale = {2,1,2};\nmatrix xform = maketransform(XFORM_SRT, XFORM_XYZ, tr, rot, scale);\n\n// v@tr_check attribute will match original tr variable\nv@tr_check = cracktransform(XFORM_SRT, XFORM_XYZ, 0, {0}, xform);\n\nv@P *= xform; // apply transformation\n\n/*\npart of the $HH/vex/include/math.h file:\n\n#define M_E             2.7182818\n#define M_LN10          2.3025850\n#define M_LN2           0.6931471\n#define M_LOG10E        0.4342944\n#define M_LOG2E         1.4426950\n#define M_PI            3.1415926\n#define M_TWO_PI        6.2831852\n#define M_PI_2          1.5707963\n#define M_PI_4          0.7853981\n#define M_SQRT1_2       0.7071067\n#define M_SQRT2         1.4142135\n#define M_TOLERANCE     0.0001\n\n#define M_2SQRT6_3  1.6329931618554518  // 2 * sqrt(6) / 3\n#define M_SQRT3     1.7320508075688772  // sqrt(3)\n#define M_1_SQRT3   0.5773502691896257  // 1 / sqrt(3)\n#define M_SQRT_2_3  0.816496580927726   // sqrt(2 / 3)\n\n#define XFORM_SRT       0       // Scale, Rotate, Translate\n#define XFORM_STR       1       // Scale, Translate, Rotate\n#define XFORM_RST       2       // Rotate, Scale, Translate\n#define XFORM_RTS       3       // Rotate, Translate, Scale\n#define XFORM_TSR       4       // Translate, Scale, Rotate\n#define XFORM_TRS       5       // Translate, Rotate, Scale\n\n#define XFORM_XYZ       0       // Rotate order X, Y, Z\n#define XFORM_XZY       1       // Rotate order X, Z, Y\n#define XFORM_YXZ       2       // Rotate order Y, X, Z\n#define XFORM_YZX       3       // Rotate order Y, Z, X\n#define XFORM_ZXY       4       // Rotate order Z, X, Y\n#define XFORM_ZYX       5       // Rotate order Z, Y, X\n*/\n~~~\n\n## Using macros\n~~~ C linenumbers\n#include \"myLib.h\"\n\n// check attributes in Geometry Spreadsheet, \n// they will match values from myLib.h\n\n// use constants\ni@my_int = MY_INT;\nf@my_float = MY_FLOAT;\n\n// use function alias\nf@renamed_power = RENAMEDPOWER(2,2);\n\n// use macro function\ni@add_ten = ADDTEN(10);\n~~~\n*From myLib.h:*\n~~~ C linenumbers\n// you can use macros to define constants and use them in your code\n#define MY_INT\t\t\t123\n#define MY_FLOAT\t\t3.1415926\n\n// you can also create alias to the function\n#define RENAMEDPOWER\tpow\n\n// or use macros for defining new functions\n#define ADDTEN(val)\t \t(val+10)\n~~~\n\n## Functions\n~~~ C linenumbers\n#include \"myLib.h\"\n\n// void does not return anything\nmyRemPoints(@ptnum);\n\n// arguments are passed by reference - function can modify their original value\nscaleByTen(v@P);\n\n// you can prevent voids from modifying variable references\n// just to be safe :)\nint a = 1;\nint b = 1;\nint c = 1;\nchangeA(a, b, c);\ni@a = a;\ni@b = b;\ni@c = c;\n\n// functions can also return different types - float, string, int, custom struct...\n// they can also return an array of any of those types\nvector4 seeds = {1.23,4,56.489,0.849};\nf@superRandom = superRandom(seeds);\n\n// function returning array of int(s)\nint items = 9;\ni[]@items = range(items);\n~~~\n*From myLib.h:*\n~~~ C linenumbers\n// void functions do not return anything\n// \"function\" word is not required\nfunction void myRemPoints(int ptnum) {\n\tif (ptnum \u003e 30)\n    \tremovepoint(0, ptnum);\n}\n\n// function parameters are passed by reference automatically, without additional syntax\n// (function receive the original variable, not its copy)\nvoid scaleByTen(vector P) {\n\tP *= 10;\n}\n\n// you can prevent changing input variable references\nvoid changeA(int a; const int b; int c) {\n\ta += 10;\n\t//b += 10; // uncommenting this line will result in error\n\tc = a;\n\tc += 4; // even though arguments are passed by reference, they are not true references, \"c\" is still independent from \"a\"\n}\n\n// a function returning float value\nfloat superRandom(vector4 seeds) {\n\tfloat out = rand(seeds.x * seeds.y * seeds.z * seeds.w);\n\treturn out;\n}\n\n// a function returnig an array\nint[] range(int max) {\n\tint out[];\n\n\tfor(int i=0; i\u003cmax; i++) push(out, i);\n\n\treturn out;\n}\n~~~\n\n## Functions overloading\n~~~ C linenumbers\n#include \"myLib.h\"\n\nfloat rand = chf(\"randomness\");\n\n// visualize Normals in the viewport to see the effect\n//v@N = randomizeN(v@N, rand, @ptnum + @Frame); // randomizeN(vector, float, float)\n\n// however we can overload our function to accept different set of arguments\nvector4 seed;\nseed = set(v@P.x, v@P.y, v@P.z, @ptnum * @Frame);\n//seed = set(v@P, @ptnum * @Frame); // this does not work as might be expected\nv@N = randomizeN(v@N, rand, seed); // randomizeN(vector, float, vector4)\n\n// we can also overload functions to return different type\nfloat randVal;\nrandVal = float( randomizeN(v@N, rand, @ptnum) );\n//randVal = randomizeN(v@N, rand, @ptnum); // this has the same result now, but sometimes VEX might choose another function\nv@Cd = randVal;\n//v@Cd = set(randVal, randVal, randVal); // this is equivalent to the previous line\n\np@a = set(v@P.x, v@P.y, v@P.z, 4);\n//p@a = set(v@P, 4); // uncomment this line and see the difference in geometry sphreadsheet\n~~~\n*From myLib.h:*\n~~~ C linenumbers\n// normalize Normal vector by amount [0..1] with specified seed value\nvector randomizeN(vector N; float amount, seed) {\n\tvector randDir;\n\t\n\t// getting different random value for each axis, scaling to [-1..1] range\n\trandDir.x = rand(seed * 684.49848) * 2 - 1;\n\trandDir.y = rand(seed * 178.46548) * 2 - 1;\n\trandDir.z = rand(seed * 489.49856) * 2 - 1;\n\t\n\trandDir = normalize(randDir);\n\n\tN = lerp(N, randDir, amount);\n\tN = normalize(N);\n\n\treturn N;\n}\n\n// function has different set of parameters, but the same name\nvector randomizeN(vector N; float amount; vector4 seed) {\n\tvector randDir;\n\t\n\t// getting different random value for each axis, scaling to [-1..1] range\n\trandDir.x = rand(seed.x * 684.49848 * seed.w) * 2 - 1;\n\trandDir.y = rand(seed.y * 178.46548 * seed.w) * 2 - 1;\n\trandDir.z = rand(seed.z * 489.49856 * seed.w) * 2 - 1;\n\t\n\trandDir = normalize(randDir);\n\n\tN = lerp(N, randDir, amount);\n\tN = normalize(N);\n\n\treturn N;\n}\n\n// this function declaration returns different type\n// the function name does not really match its functionality, it is just for the example\nfloat randomizeN(vector N; float amount; int seed) {\n\tfloat randDir;\n\t\n\t// getting different random value for each axis, scaling to [-1..1] range\n\trandDir = rand((float)seed * 684.49848) * 2 - 1;\n\n\treturn randDir;\n}\n~~~\n\n## Variables casting\n~~~ C linenumbers\n#include \"myLib.h\"\n\nint myPt = @ptnum;\nint maxPts = @numpt-1;\n\nfloat color;\n\n// by casting to float, we can do float division, which is more helpful in our case\ncolor = float(myPt) / (float)maxPts; // for variables both syntaxes are valid\n//color = float(myPt) / maxPts; // it is also valid as the other variable (does not matter which one) will be upcasted to float\n\n// dividing integer by integer produces integer, it is not what we need\n//color = myPt / maxPts;\n\ncolor = pow(color, 3); // make color more contrasty\n\n// assigning a float to vector will assign uniform vector: { color, color, color }\nv@Cd = color;\n~~~\n\n## Vectors swizzling\n~~~ C linenumbers\nvector col = {.1, .3, .7};\n\ncol = col.zzy; // this syntax is equivalent to the following line\n//col = set( col.z, col.z, col.y );\n\n// reversing order of vector elements had never been easier :)\n//col = {.1, .2, .3};\n//col = col.zyx;\n\n// swizzling is not however as powerful as in other graphics languages\n// e.g. following lines do not work as expected, or at all\n//col.zyx = col.xyz;\n//col.xy = col.yx;\n\nv@Cd = col;\n~~~\n\n## Functions casting\n~~~ C linenumbers\n#include \"myLib.h\"\n\n// this line results in an error, because dot() is expecting two vectors\n// and rand() is overloaded - it can return float, vector, vector2, vector4\n//v@Cd = dot(v@N, normalize( rand(@ptnum)  ) ) * 0.5 + 0.5;\n\n// here we are explicitly asking for rand() function which is returning a vector\nv@Cd = dot(v@N, normalize( vector( rand(@ptnum) ) ) ) * 0.5 + 0.5;\n\n\n// this will not work as length() is expecting a vector\n//v@Cd = length( rand(v@P) );\n\n// this now works fine\n//v@Cd = length( vector( rand(v@P) ) ) * .5;\n~~~\n\n## Structs\n~~~ C linenumbers\n#include \"myLib.h\"\n// in this node I will show some examples of using structs, they will be defined in myLib.h\n// for defining structs inside a wrangle, see node below\n\n// declare struct variable, member variables will have default values\nmyCustomMatrix A;\nmyCustomMatrix B;\n\n// change values of member variables in A\nA.uniformScale = 2.5;\nA.comment = \"a very useful struct\";\npop(A.myArray);\npop(A.myArray);\npush(A.myArray, 7);\n\n// check Geometry Spreadsheet for values of variables in A and B\nf@myPiA = A.myPi; // 3.14\nf@myPiB = B.myPi; // 3.14\nf@uniformScaleA = A.uniformScale; // 2.5\nf@uniformScaleB = B.uniformScale; // 1.0\ns@commentA = A.comment; // a very useful struct\ns@commentB = B.comment; // default comment\nf[]@myArrayA = A.myArray; // [ 1.0, 7.0 ]\nf[]@myArrayB = B.myArray; // [ 1.0, 3.0, 3.0 ]\nv@xA = A.x; // {0,0,0}\nv@xB = B.x; // {0,0,0}\n\n// one way of initializing a struct (as explicit struct)\nhipFile myProjectA = {\"project_A\", \"hipnc\", 1};\ns@baseA = myProjectA.base; // project_A\ns@extA = myProjectA.ext; // hipnc\ni@verA = myProjectA.version; // 1\n\n// another way (initialize using constructor)\nhipFile myProjectB = hipFile(\"project_B\", \"hip\", 1);\ns@baseB = myProjectB.base; // project_B\ns@extB = myProjectB.ext; // hip\ni@verB = myProjectB.version; // 1\n\n// you can call methods (member functions) in structs with -\u003e operator\nint versionA = myProjectA-\u003eincVersion();\nversionA = myProjectA-\u003eincVersion();\nversionA = myProjectA-\u003eincVersion();\n\nint versionB = myProjectB-\u003eincVersion();\n\n// printName is our another struct method,\n// check your terminal output\nmyProjectA-\u003eprintName(); // this file has name: project_A_004.hipnc\nmyProjectB-\u003eprintName(); // this file has name: project_B_002.hip\n\n// we can use functions operating on our structs and accessing their data\ni@match1 = compareHipFiles(myProjectA, myProjectB); // 0\n\n// now let's make them identical\nmyProjectB.base = \"project_A\";\nmyProjectB.ext = \"hipnc\";\nmyProjectB.version = 4;\n\n// and check if they really are :)\ni@match2 = compareHipFiles(myProjectA, myProjectB); // 1\n\n// we can also create functions which return hipFile type\n// this function expects comma separated list of files and will return\n// first occurance of a hip file (with .hip or .hipnc extension)\nstring files1 = \"image1.jpg,image2.png,text.pdf,awesome_tutorial_jtomori_003.hipnc,tutorial.h\";\n\nhipFile first = findFirstHipFile(files1);\ns@first = first-\u003egetFullName();\n\n// in VEX we can also output error with custom message, uncomment the line bellow and check\n// node's error message\nstring files2 = \"image1.jpg,image2.png\";\n//hipFile second = findFirstHipFile(files2); // No houdini project found in this file list: \"image1.jpg,image2.png\".\n\n// we can also output an array of hipFiles\n// this function will find all Houdini project files and will return array of hipFile(s)\nstring files3 = \"dust_024.hip,img7.tif,odforce_file_001.hipnc,render1.exr,blood_123.hip,notes.txt\";\nhipFile allHips[] = findAllHipFiles(files3);\n\n// let's check it by adding it into a string array attribute\ns[]@allHips;\nforeach(hipFile i;allHips) {\n    push(s[]@allHips, i-\u003egetFullName());\n}\n// result: [ dust_024.hip, odforce_file_001.hipnc, blood_123.hip ]\n~~~\n*From myLib.h:*\n~~~ C linenumbers\n// vex also supoorts structs and methods associated with them\nstruct myCustomMatrix {\n\t// uninitialized variables\n\tvector x, y, z;\n\t\n\t// variables with default values\n\tvector translate = {0,0,0};\n\tstring comment = 'default comment';\n\tfloat myPi = 3.14159265;\n\tfloat uniformScale = 1.0;\n\tfloat myArray[] = {1,2,3};\n}\n\n// struct for carrying information about our project file\nstruct hipFile {\n\tstring base, ext;\n\tint version = 1;\n\n\t// you can create methods that operate on structs\n\t// this method increases version by 1 and returns new version number\n\tint incVersion() {\n\t\tthis.version++;\n\t\treturn this.version;\n\t}\n\n\t// inside of a struct function, you can refer to struct fields by name as if they \n\t// were variables (for example, base is a shortcut for this.base).\n\t// this method writes to console window / terminal\n\tvoid printName() {\n\t\tprintf(\"this file has name: %s_%03d.%s\\n\", base, version, ext);\n\t}\n\n\t// returns a string with full file name\n\tstring getFullName() {\n\t\treturn sprintf(\"%s_%03d.%s\", this.base, this.version, this.ext);\n\t}\n}\n\n// we can create functions that operate on our structs and use their methods\nint compareHipFiles(hipFile A, B) {\n\tint match = 0;\n\tif (A-\u003egetFullName() == B-\u003egetFullName()) match = 1;\n\n\treturn match;\n}\n\n// func returning hipFile type\n// this function expects comma separated list of filenames and will \n// return the first occurance of a hip file\nhipFile findFirstHipFile(string text) {\n\tstring inFiles[] = split(text, \",\");\n\tstring hipParts[];\n\n\tforeach(string file; inFiles) {\n\t\tstring parts[] = split(file, \".\");\n\t\tif (parts[-1] == \"hip\" || parts[-1] == \"hipnc\") {\n\t\t\thipParts = parts;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// we can also return error state, warning() function is also available\n\tif (len(hipParts) == 0) error(\"No houdini project found in this file list: %+s.\", text);\n\n\tstring prefix[] = split(hipParts[0], \"_\");\n\tint ver = atoi( prefix[-1] );\n\tstring base = join( prefix[:-1], \"_\");\n\tstring ext = hipParts[1];\n\n\thipFile out = hipFile(base, ext, ver);\n\treturn out;\n}\n\n// we can as well return an array of structs\nhipFile[] findAllHipFiles(string text) {\n\tstring inFiles[] = split(text, \",\");\n\thipFile hips[];\n\n\tforeach(string file; inFiles) {\n\t\tstring parts[] = split(file, \".\");\n\t\tif (parts[-1] == \"hip\" || parts[-1] == \"hipnc\") {\n\t\t\tstring prefix[] = split(parts[0], \"_\");\n\t\t\tint ver = atoi( prefix[-1] );\n\t\t\tstring base = join( prefix[:-1], \"_\");\n\t\t\tstring ext = parts[1];\n\n\t\t\thipFile out = hipFile(base, ext, ver);\n\t\t\tpush(hips, out);\n\t\t}\n\t}\n\n\t// output a warning when no Houdini projects were found\n\tif (len(hips) == 0) warning(\"No Houdini projects found.\");\n\n\treturn hips;\n}\n~~~\n\n## Structs in Attribute Wrangle\n~~~ C linenumbers\n// VEX does not allow defining structs inside this field, they need to be defined\n// externally, either in a .h file, or in \"Outer Code\" string parameter of \"snippet1\"\n// which is inside of every Wrangle node (this \u003e attribvop1 \u003e snippet1)\n// in this case I unlocked the wrangle and promoted \"Outer Code\" parameter from \n// the inside of snippet1 to this wrangle\n\nhipFile A = hipFile(\"awesome_vex_examples_file\",\"hipnc\",3);\ns@A = A.base;\n\n// uncommenting of the following lines will result in an error\n/*\nstruct hipFileB {\n        string base, ext;\n        int version = 1;\n}\n*/\n\n// Outer Code behaves just like a .h file included\ni@my_int = MY_INT;\n~~~\n*Outer Code*\n~~~ C linenumbers\nstruct hipFile {\n        string base, ext;\n        int version = 1;\n}\n\n#define MY_INT  123456\n~~~\n\n## Groups\n~~~ C linenumbers\n// it is also possible to manipulate group membership through VEX, group names\n// are bound by default with i@group_name syntax (int value: 0 - not member, 1 - member)\n// you can disable it in \"Bindings\" tab of Wrangle node with \"Autobind Groups by Name\"\n\n// it is also possible to create new groups, they are created automatically like attributes\n// in the following line we assign all points that belong to \"selected\" group to \"red\" group\ni@group_red = i@group_selected;\n\n// all points, that have positive X coordinate will belong to \"green\" group\ni@group_green = v@P.x \u003e 0 ? 1 : 0;\n// except those, which are already in \"red\" group\ni@group_green = i@group_green \u0026\u0026 !i@group_red ? 1 : 0;\n// i@group_name can have two values and can be treated as a boolean, the following line\n// has the same effect as the previous one\n//i@group_green = i@group_green == 1 \u0026\u0026 i@group_red == 0 ? 1 : 0;\n~~~\nGroup mirror\n~~~ C linenumbers\n// groups in VEX are very helpful as we can use VEX functions to do our own group logic\n// in this example we mirror red group along X axis and will assign it to \"blue\" group\n\nint pt_reflected = nearpoint(0, set(-v@P.x, v@P.y, v@P.z) );\nint pt_group_red = inpointgroup(0, \"red\", pt_reflected);\n\ni@group_blue = pt_group_red;\n~~~\n\n## Attribute typeinfo\n~~~ C linenumbers\n/*\nIt is possible to assign a meaning to attributes. Houdini will understand this meaning and\nwill treat attributes in a specific way based on it. For example a Transform SOP operates\non P attribute, but will also modify N attribute accordingly. For modifying this behavior \nwe can use setattribtypeinfo() function which can set typeinfo to attributes.\nYou can check which typeinfo an attribute has by middle-clicking on a node and checking value\nin brackets, e.g. P (pos) - this means point typeinfo\n\nYou can chceck list of available typeinfos in the docs, or below:\nnone - No transformations should be applied.\npoint - Scales, rotations and translations should be applied.\nhpoint - A four-vector with scales, rotations and translations applied.\nvector - Scales and rotations should be applied.\nnormal - Scales and rotations should be applied. Scales are applied with inverse-transpose.\ncolor - No transformations.\nmatrix - A 4×4 matrix with scale, rotations, and translations applied.\nquaternion - A four-vector with rotations applied.\nindexpair - No transformations.\ninteger - Integer values that do not blend when points are averaged.\ninteger-blend - Integer values that blend when points are averaged.\n*/\n\n// set color to green\nv@Cd = {0,1,0};\n\n// initialize N attribute, which will get automatically get values\nv@N;\n\n// change typeinfos of Cd and N to see funky results after modifying geometry with Transform SOP\nsetattribtypeinfo(0, \"point\", \"Cd\", \"point\");\nsetattribtypeinfo(0, \"point\", \"N\", \"color\");\n~~~\n\n## Attributes to create\n~~~ C linenumbers\n// when dealing with more code you might often run into\n// errors caused by typos, when you mistype an attribute\n// name, VEX will automatically initialize a new one\n// like in the following example\nv@Cd = {1,0,1};\n\n// to avoid this kind of errors, we can specify which attributes\n// to create, in \"Attributes to Create\" parameter of a Wrangle\n// e.g. the following line will result in a node error, because\n// we did not specify to create a \"n\" attribute\n//v@n = {0,1,0};\n~~~\n\n## Enforce prototypes\n~~~ C linenumbers\n// If we want to be even more organized, we can use \"Enforce Prototypes\" option \n// in Wrangles, it is handy with larger code projects as it helps with \n// managing attributes and simplifies syntax for accesing them (especially with arrays)\n\n// initialize attribute \"Prototypes\" - here we need to specify all attributes\n// that we want to use/create, it also applies to default/global attributes \n// like v@P, @Frame, @ptnum\nvector @P;\nvector @Cd;\nint @ptnum;\nfloat @Frame;\nfloat @new_attrib = 4; // we can also set initial value, but without any expressions\nint @new_int_array_attrib[];\n\n// we can still use local variables in a standard way\nfloat A = @Frame * .5;\nint B = 4;\n\n// now we can use attributes without their signature before @ sign\n@P += set(0, B, 0);\n@Cd *= rand(@ptnum);\n@new_attrib *= A;\n@new_int_array_attrib = {1,2,3,4};\n~~~\n\n## Attribute default values\n~~~ C linenumbers\n// It is also possible to set default values for attributes from VEX.\n// It replicates behavior of \"Default\" parameter in Attribute Create SOP,\n// it means that when we create a new geometry (without passing current ptnum\n// to addpoint() function to copy all attributes), it will have those default\n// values. Otherwise it will be usually set to 0, or 1 in case of Cd.\n// The same applies for merging in a geometry, which does not have the attribute,\n// the attribute will be added with default values which we specified.\n// Note that defaults do not work with string attributes, it is a known limitation.\n\n// Default values can be set with Attribute Prototypes which were mentioned in\n// the previous node. Any new geometry will have those default values.\nvector @Cd = {1,0,0};\nint @id = 4; //@Frame or other expressions will not work\n\nstring @default = \"abc\"; // defaults for strings are not supported yet\n\n// Let's create couple of copies of our points\nvector offset = {0,8,0};\nfor (int i = 0; i \u003c 3; i++)\n    addpoint(0, v@P + offset * (i + 1));\n\n// Original sphere will have this value set to 7, while new points will have\n// default value 0\nf@pscale = 7.0;\n\n// This will set id attribute to zero only on input geometry, new geometry will \n// have default value 4\ni@id = 0;\n~~~\n\n# Resources \u0026 More\nIn this tutorial I am focusing on VEX syntax, capabilities and integration in Houdini.\n\nFor more practical and visual VEX examples check [Matt Estela's awesome wiki](http://www.tokeru.com/cgwiki/?title=HoudiniVex)\n\nAnother good source is *$HH/vex/include* folder which is full of VEX include files with many useful functions. *( $HH expands to /houdini_install_dir/houdini/ )*\n\nMake sure to watch this very cool [VEX Masterclass](https://vimeo.com/173658697) by Jeff Wagner.\n\nVEX is well documented, [language reference](http://www.sidefx.com/docs/houdini/vex/lang) and [functions](http://www.sidefx.com/docs/houdini/vex/functions/index.html) pages are very helpful too.\n\n# Feedback \u0026 Suggestions\nPlease let [me](https://jtomori.github.io) know if you find any mistakes or have ideas for improvements.\n","funding_links":[],"categories":["Learn"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjtomori%2Fvex_tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjtomori%2Fvex_tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjtomori%2Fvex_tutorial/lists"}