Home
Tutorials and Topics
Contents
1. t ssimpleto repatch bpatcher objects oncethey arecreated even ifthenew bpatcher containsa different number of inlets or outlets To implement areplace feature we need to take the following steps 1 Theoriginal bpatcher object must benamed Any objects connected to it viainlets or outlets should also benamed 2 Toreplacethe object wefirst delete it using thescript delete message 3 Usingthescript new message wethen create a new bpatcher with the same object nameas the previous onethat refers to anew patch file 4 Finally wereconnect objects to the inlets and outlets of thenew bpatcher as necessary Let s begin with two simple patches bpatch1 and bpatch2 that we d liketo useinsidea bpatcher 240 Tutorial 4 Advanced scripting Our main patch lookslikethis and already contains abpatcher named mybpatcher containing the bpatchl patch example2 replace master patch TheM ax text filefor this patch looks like max v2 N vpatcher 31 53 416 384 number 8 166 35 10 0 0 0 22 0 0 0 221 221 221 222 222 222 0 0 0 objectname num_ bottom P number 78 49 35 10 0 0 0 22 0 0 0 221 221 221 222 222 222 0 0 0 objectname num_topright number 8 49 35 10 0 0 0 22000 221 221 221 222 222 222000 objectname num_topleft bpatcher 8 71 105 90 0 0 bpatch1 1 objectname mybpatcher connect 1000 connect 0 030 fasten 2 0 0 1 83 67 108 67 pop In thetext file listing above items
2. im 7 p m a wi B a Any volume eventin thetimeline will be sent out viatheticmd volume i object asthe value of a M IDI controller 7 message to modify the volumeof thesynth Similarly any bend eventin the timelinewill besentoutasaM IDI pitchbend message A pitch event will beplayed asa200msnote with a randomly chosen velocity somewhere between 64 and 127 A random number from Oto 63 ischosen then 64 is added to that number beforeit is sent to the velocity inlet of makenote An action patch doesn t need to handleall the events itself It can simply send them somewhere else by connectingtheoutlet of ticmd to asend object or atiout object asisdonein portionsC and D of thisaction ticmd note 1 tifuk 2 D jtitmd seqeontrol titmd scalespeed tidut 1 Thetiout object passes any messagesit receives in its inlet out the specified outlet of thetimeline object itself So in this case note or scalespeed events from thetimeline get sent out the outlet of the timeline object in the41 Timdinepatch You might find it useful to think oftiout objects in an action as analogous to outlet objectsin asubpatch T hey send messages out the outlets of thetime linethat containsthem W ealso seethat seqcontrol messages do not go directly to aseq object in the action rather they go to a send seqcmd object so in fact they will come out anywherethat thereis an existing receive seqcmd object Th
3. send lt symbol gt already exists receive lt symbol gt already exists Occurswhen you typein anameas an argument to a send or send receive which is already being used for atable or other object sxformat illegal type in message Occurswhen the patch is running and somemessage other than an int is received in the inlet of sxformat text lt filename gt file is protected You vetried to open aM ax binary patcher file protected against editing as text textbox bad args Occurs when opening a M ax document T hedocument has been damaged Unable to load MaxQuickTime dll Error code Windows only A required component of M ax was missing Try reinstalling to seeif it fixes the problem 1 fnotpleasecontactC ycling 74supportand providethemessageand that wasreported warning extra arguments for message Occurswhen an objectisgiven moretyped in argumentsthan it expects or when too many argu ments are present in an incoming message U sually thisis just awarning of something that s not quite right but is basically harmless warning lt objectname gt no port lt symbol gt using lt default port gt Occurswhen a port argument is typed into the object box ofa M IDI object and theportnameis not currently valid Thevalid port namesarelisted in theM IDI Setup dialog box T hedefault port isthe first namein thedevicelistin the M IDI Setup dialog Error Dialogs W hen an error occursthatrequiresyour immediateattention theerr
4. gt lt pattr name offset value 8 8 gt lt pattr name range value 50 147 gt lt slot gt lt pattrstorage gt Thefirst relevant tag that encompasses all our data defines theinformation as belonging the a pat trstorage object The lt pattrstorage gt tag also tells usthenameofthepattrstorage argument which israndomly generated unless weset it explicitly with an argument to the object Between the lt pattrstorage gt tags we have lt slot gt tags defining the saved states N ote that slot 0 is not saved in thefile Within each lt slot gt we have lt pattr gt tags that list the exposed objects by nameand list their preset value for that state e Makeachangeto thenumerical datain oneof the slots and savethe XM L file Be careful to preserve the quotation marks around the values Read it back into the patch by clicking the read message box and selecting thefile Thestorage window will update to thenew preset value which you can then recall Because XM L isastraightforward human readable format it s quitesimpleto edit preset files saved using pattrstorage W ecould even usea piece of software e g M ax to automatically gener ate preset files for our patches oncethey ve been set up to usepattrstorage Summary Theautopattr object functions asa hybrid of the pattr and pattrhub objects allowing you to auto matically expose multiple user interface objects to the pattr system in oneeas
5. lt filename gt error creating file Therewasan error writing a file the disk may be write protected or full lt filename gt out of memory writing file Thereisinsufficient memory to write the file you re trying to save If possible close other files and windows that don t relate to thefile you re saving ad Floating point exceptions were caught lt number of exceptions gt Windows only This messageis sent to the max window when audio is stopped if floating point 394 Erro rS Explanation oferror messages exceptionswerecaughtwhileprocessingaudio T hetellsyou how many exceptions werecaughtto giveyou an indication of the severity of the problem This can betriggered by underflow of float ing point operations causing denormal numbers to be generated You may want to try modifying your patcher to cause the exceptions to stop asit may impact the performance admme unable to open wave input device admme unable to open wave output device admme unable to start output admme unable to start input ad_mme stopping due to error ad_mme No MME input or output devices found Windows only Please check that you have the latest driver update for your audio device Please exitall other audio applications rebootif necessary and try again Also pleasecheck your settings in the DSP Status window to insure appropriate choices are selected for Input Device Output Device Sampling Rate 1O V ector Size and Signal V ector Size If
6. Adding Non Max Files to a Collective When you create a collective you can include files of any type which may have been created with applications other than M ax by clicking the Include File button in the Collective Script dialog This allows you to add for example graphics files to your collective for use with thefpic object Testing a Collective A collective can function as a complete program one or more top level M ax patches combined with all the other files they need to function correctly Before you give your collective to someone else to use however you should test it to be sure that it s really complete and that you haven t for gotten to includeany essential files The best way to do that isto open thecollective by choosing Open from the File menu or by double clicking on the collectivein the Finder on Macintosh or theW indows Browser on Windows Collective Formats On Macintosh apop up menu when saving thecollectiveallowsyou to choosetheM ax collective format or theOld Format Collective Theonly reason to usetheO d Format Collectiveisif you are building aplug in to usewith Pluggo or wish to producesomething that can beused by older ver sions of M ax But note that for compatibility with older versions your collective cannot contain any external objects that arespecific to M ax M SP 4 5 Thesecan bestripped out manually usinga M acintosh resource editor such as Resourcerer simply delete all mAxL resources T
7. Channel Mode Messages Controller numbers 122 to 127 are reserved for special M IDI commands known as channel mode messages Channel mode messages can be received and transmitted with ctlin and ctlout just like any other control message The last patch shows an example of ctlout used to transmit a channel mode message meaning All Notes Off controller number 123 with a value of 0 M any synths but not all recognize this mes sage and turn off all notes currently being played For turning off notes within M ax its more rali able to use an object such as flush or poly All Motes Gf controller am her gontrol data channel Thepatch also demonstratesthat ctlout and theother transmitting objects can receive values for all inlets in the form of alist in the left inlet W hen there are no arguments ctlout transmits on channel 1 out porta 58 Tutorial 16 M oreM IDI insand outs Summary Pitch bend messages are received and transmitted with bendin and bendout program changes with pgmin and pgmout and continuouscontrol messages and channel mode messages with ctlin and ctlout M IDI data can be altered and reassigned in any way within M ax A stream of numberscan be slowed down byfilteringthem with speedlim which ignoressomeof thenumbers if they arrivetoo fast T hisis a good method of converting a continuous stream of numbers into regular discrete steps See Also bendin Output incoming M IDI pitch bend val
8. cece cece eee e eens eee eeeeees 281 TUEO Kali 52 Patcher Storage ets cote aident iii ndira E E sm cia te enebes 294 Tutorial 53 More Patcher Storage stir see tices Pata iene ele ae alee taainenee miners 301 Files How Max handles Search Pathsand Files 1 00 cccceeeeeeeeeeeeeeeueeeeeeeenenaes 308 Interfaces Picture based User Interface Objects cece cece eee eens eee en eee een eens 314 Graphics Overview of GraphicsWindowsand Objects 0 ccce sees cece teen tees 321 Collectives Grouping Filesinto aSingleProject cece ccc cece eee e eee e teen ee eeeees 326 Encapsulation How Much Shoulda PatchD0 cccecseeeee ee eee eee eeeeeeeanenes 339 Efficiency issues of Programming Style Ss cae aida sh iacuge nian h ina aa ean een eee 341 Loops Waysto Perform Repeated Operations ccc cece cece eee e eee en eee eeeeenes 344 Data Structures Waysof StoringData in MaX ccc cece cece cece eee e teen eeeeeanes 348 Arguments and ChangeableArgumentsto Objects ccc cece cence eee eee eens 351 Punctuation Special Characters in O bjectsand M essages ket eee cece eect eee eee eeaes 355 Quantile Usinga Table for Probability Distribution ccc ce cece eee e eect eee eeees 357 Sequencing Recording and Playing Back MIDI Performances 0csceseeeeeeeeeeeeaes 359 Timeline Creating a Graphic Score of M ax MESSAGES ces cece eee eee eect eee e ete ee ne ens 362 Detonate Graphic Editing of a M IDI Sequ
9. r somemoredata ae a ae 7 Script move myfunction 30 36 Script size myfunction 100 50 thispatcher U singthescript move and script size messages 244 Tutorial 4 Advanced scripting Click on thelargeand small message box objects to trigger script commandsto move and resize thefunction object Theresult of sendingthelarge message Additional commands script messages are available for advanced object moving operations Thecommand script offset message permits you to specify achangein an object s location relativeto its current position script offset lt variable name gt lt delta x gt lt delta y gt Thescript command script offsetfrom message allows you to movean object relative to the position of another object script offsetfrom lt variable name to move gt lt target variable name gt lt top left flag gt lt delta x gt lt delta y gt The variable lt variable name to move gt is thename of the object you want to move and lt target variable name gt isthename of the object being used to determinethe relative position Set the lt top left flag gt flag to 0 if you want thenew position to berelativeto thetop left corner of lt target variable name gt or set it to 1 and thenew position will berelativeto the bottom right corner of lt target variable name gt 245 Tutorial 4 Advanced scripting Hiding and Showing and Cicking You can usescripting to hide objects using the following command scri
10. Finally by encapsulating different portionsoftheprogram you makeit easier for yourself or oth ers to seehow the program works long after you develop it Encapsulation Thedifferent modules of aprogram arebest designed to encapsulateasingletask Namethemod ulefor what it does and reusethe module should you ever wish to perform thetask again in another program By keeping certain valuesin oneplace you only haveto changethem onceif you decidethey need to bemodified If the same values are distributed throughout your program you haveto find every instance of that value and change each one individually Oneway to keep valuesin asingleplace yet still makethem availableto many different objects is to storethe values in asinglefilethat can be accessed by any patch For example many different patches can read in valuesfrom thesametable fileby using table objects with thesamefilenameas 339 Encapsulation H ow much should a patch do an argument Changing thecontents of that onefilethen changesthevalues used by all thepatches that share that file Messages between Patches W hen designing small modules patches which will be combined in a larger program itis important to consider not only what the patch doesinternally but also the context in which it will beused Thecontext will determine what kind of messages you want each patch to produceand accept For example you might wish to usea bang to trigger a process numbers to toggles
11. YourApplication app note the app isnot shown in the Finder Contents folder Info plist copied from your plist if included in a collective MacOS YourApplication actually M ax M SP Runtime YourA pplication mxf thenew format collective containing your patches support audio and MIDI support files Resources custom icon file goes here Jitter Javascript and Standalones For thejs and jsui or Jitter objects to work in astandalone their respective libraries can either be included in the application script or they can also beplaced in the same folder as the application insidethe application package 331 Col act ves Groupingfilestocreate a single application The jsand jsui objects requirethe Javascript library located at Library CFM Support SRef shlb on Macintosh systems or C Program Files Cycling 74 M axM SP 4 5 support js32 dl on Windows systems Jitter objects require the Jitter library located on M acintosh systems at Applications M axM SP 4 5 jitlib or C Program Files Cycling 74 M axM SP 4 5 support jitlib dl on Windows systems Customizing Standalones Donotrenamethe mxffileinsideyour standalone otherwiseit will not load when theruntime executable is launched You may nonetheless wantto customizesomeofthefeaturesof your standaloneapplication such as the Overdrive setting the application icon or whether or not users will be allowed to closethe top level patch
12. Default Sacling 200 LI Display MIDI Note Numbers You can change the name of the parameter its minimum and maximum possible values and the default value that will be used for that parameter in notes where it is left unspecified Graph Inter val affects the view only if the parameter is displayed on they axis it controls how often numbers will beshown alongthey axis every 12 semitones in the above example D efault Scaling is a fac tor that determines the default zoom of the axis on which the parameter is being displayed 1 is maximum zoom and larger numbers are successively smaller scales The values on they axis can bedisplayed asM IDI notesinstead of decimal numbersonly for parameter 1 pitch thisoption is disabled for all other parameters T he start time the leftmost parameter is an exceptional case because it can only be displayed on thex axis so for that parameter Graph Interval and D efault Scaling refer only to the x axis The fact that the name and characteristics of all the parameters can beso easily changed suggests that detonate can actually be used as a collector of arbitrary lists of numbers It is designed for holding lists that represent note events but the numbers can in fact mean anything as is true of almost all numbersin M ax so you can useit to storeand recall virtually any collection of lists of integers that you might want to represent and edit graphically 380 Detonate GraphiceditingofaM IDI sequence
13. Messages Understood by Max M boxcolor checkpreempt clean debug enablerefresh externs fileformat getboxcolor seethesection M IDI Configuration M essages at the end of this chapter Sets one of the 15 default object colorsin the Color submenu boxcolor is followed by fivearguments Thefirst istheindex between 1 and 15 followed by three val ues in the range 0 255 that specify the color for thisindex and afinal valuethat specifies whether this change overwrites the user preferences 1 or not 0 Theword checkpreempt followed by a symbol sends the current O verdrive mode to thereceive object named by the symbol Causes M ax not to display a Save Changes dialog when you closea window or quit even if thereare windows that havebeen modified Thisisuseful in conjunc tion with thequit message below Theword debug followed by azero or one toggles thesending of M ax s internal debugging output to the M ax window Debug information may beof limited use for anyonewho isn t debugging M ax itself M acintosh only Theword enablerefresh followed by azero or one toggles an alternativeto thestandard way in which thescreen contentsareupdated resulting in better visual performance T hisfeatureis enabled by default T herateat which refresh is donecan be set by using the setrefreshrate message List all of the external objects currently loaded in the M ax window Theword fileformat followed by two symbols tha
14. Tutori al 15 M aking decisions with comparisons select Theselect object is a special relational operator If the left operand is equal to theright operand a bang is sent out the left outlet O therwise the left operand is passed out the right outlet T he effect is that every number received in the left inlet gets passed on out the right outlet except the one select islookingfor W hen select receivesthenumber it slookingfor itsendsabang out theleft out let Patch 2 shows that theselect object whose name can be shortened to sel can actually begiven several arguments and each argument can bean int a float or a symbol i e aword Theinput is converted to the proper type int float or symbol before being compared to each argument Notice that the right inlet is not present if thereis morethan oneargument e Click on thedifferent messages N oticethat iftheinputmatchesoneofthearguments abang is sent out the outlet that corresponds to that argument If there is no match the input is passed out the right outlet W hen theinputisan int such as4 itis converted to float beforebeing compared with afloat argu ment A float input such as 26 9 is truncated before being compared to an int argument Combining Comparisons with the select object Theselect object sends out abang which can beused to trigger other objects and relational opera tors send out thenumbers1 and 0 which can beused to toggle something on and off such asa
15. e Design and program procedural operations that may bedifficult or impossibleto implement using M ax objects by themselves These may include operations that require recursion or respond to messages with an unknown number of arguments to givetwo examples e Create objects that respond to customizable messages and rely on their own internal data structures Scheduletimed eventsin responseto messages e Manageglobal variables for useamong multiple js objects or between js objects and the M ax patcher e Interfaceto M ax s powerful scripting architecture e Accessthefilesystem of your computer to look for files by nameand types In previous versions of M ax in order to develop aM ax object using a programming language other than M ax itself i e subpatchers you had to develop your own external objectin C usingthe M ax Software D evelopment Kit Starting in M ax 4 5 wealso allow you to develop objectsin J ava using themxj object Both of thesesolutionsrequirethat thecodeyou writebecompiled into afor mat that M ax can execute either directly by loading a shared library or by executing ava code through the avaV irtual M achine W ith thejs object and its graphical cousin jsui codeis eval uated as a script directly by the computer as you run your patch allowing for moreimmediate feedback on how the mini program written for your js object will behave T hat isn t to say that js doesn t check for mistakes first it does and we
16. from the O bject menu and check Save P resets with Patcher This patch shows you another way to store and recall presets you Shift click on a preset to store the current settings and you can then recall the settings by just clicking on that preset The num ber of preset locations in a preset object isnot dependent on the object s physical size Each preset object holds 256 preset locations even if they aren t shown within its object box e Click ondifferent preset buttonsto recall differenttoggle and number boxsettings T ry creating your own repeated note patterns and storing your settings in the preset object shift click to store a setting metro 720 BS0 metro en pa click to recall a setting FassPcot 30 FassPot 20 PassPct 10 H O ee metro 430 metro 240 metro 120 PassPcot 25 PassPeot 15 PassPet 5 Pa pEr nakenote 64 240 Toteowk a Thereareno hidden patch cordsin this window When a preset isnot connected to anything it stores the setting of every user interface object in the window Summary A data structure is used to store data so that individual items can be easily accessed The coll object stores any kind of message with either a number or a symbol as the address D ata to bestored can bereceived as messagesin theinlet or typed into acoll object stexteditor window When coll receives an address in its inlet it sends the address out its second outlet and sends the message stored at t
17. object M ax will look for a help file called rmi nus help not one called help M ax specific mappings arefound in afilecalled max objectmappings txt M SP specific map pingsarein afilecalled audio objectmappings txt Aswith thefileformat message to max the objectfile message can besent within a message box But placing itin afilein theinit folder ensures that mappings are available each time you use M ax 312 FI les H ow M ax handles Search Paths and Files D evelopers of third party external objects can add their own filesto theinit folder with object namemapping messages in them 313 Interfaces Picture based U ser nterfaceO bjects Getting the Picture Thepictctrl pictslider and matrixctr objects are user interface object for creating buttons sliders switches knobs and other controls These objects can open PICT files and if QuickTimeis installed other picture file formats that are listed in the QuickT ime appendix found in the M ax Reference M anual Since the these objects use images from picture files for their appearance you can create these files using any graphics program such as Photoshop or Canvas with what ever appearance you desire Each picture based control expects the picturefile to bein a particular layout The layouts vary somewhat depending on thecontrol but they havesomecommon characteristics e Each picturefilecontainsa rectangular array of oneor moreimages Each image represents
18. M odify that contains thenew commands we want 224 Tutorial 45 D esigningtheuser interface Thescript isas follows X about About Note Modifier X menutitle 5 Modify X item 5 1 Track A 1 X item 5 2 Track B 2 X item 5 3 Track C 3 X item 5 4 Track D 4 x item 55 4X item 5 6 Keyboard K X item 57 X item 5 8 Panic P X end The character is special indicatingthat thecharacter thefollowsit should bethekeyboard short cut associated with that menu item Command lt key gt on M acintosh or Ctrl lt key gt on Win dows The character is also special indicating that a gray line should besubstituted for an actual menu item at that point in themenu which isuseful for dividing themenu into sections Onceour menu bar isin place wehavethree ways to turn tracks on or off a button amenu com mand and akey command This introduces a bit morecomplexity to our programming task however because each of thethree methods needs to highlight or unhighlight the button check or uncheck the menu item open or closethetrack window and enableor disableM IDI in that track window e Toseehowthisisdone you ll haveto resort to atrick to seethe contents of the main patch Closethe45 N oteM odifier window then re open it and hold down the Command and Shift keys on M acintosh or Control and Shift keys on W indowsasit is opening This will stop all loadbang objects from sending out their bang messages and will open the w
19. The delta timeis the number of milliseconds between the beginning of that note and the beginning of the previous note The how long is determined by the number most recently received in the 4th duration inlet Records pitch middle 60 on channel 1 witha wote on ve le ity of 112 lasting 250m ope wring 300i after the onset of the previous mote 500 60 112 250 1 Telatime Fich We doe iby Duration Chane Recordingdelta timeand noteduration aspart of thenoteevent The duration can also beestablished by a later note off message a note with velocity of 0 on the same pitch W hen a note off event is received after a corresponding note on the datatime between the two events is used actually the sum of any delta times between the two if there were 376 Detonate GraphiceditingofaM IDI sequence other intervening events to set the duration of thenote on message and the note off message does not actually get recorded as a separate event Records pitch midl C 60 wih a note on velocity of 112 occuring 00s after the onset of the pre vious note then turns it off after 250m5 300 60 112 250 60 0 Deta time Fich We be ity Letting detonate determine duration based on the delta time between note on and note off A track number may besupplied in the 6th inlet which is useful for separating recorded note events into different streams to be saved as a multi track M IDI file Notes recorded on different tracks show
20. The result sounds like this AutomaticE majoraccompanimentfigure Note on pitches and velocities from your M IDI keyboard are packed into alist along with a delay time and sent to pipe with a delay of 750ms This causes a short note echo of every played note 750ms later The played notes also havean effect on the accompaniment If a played note arrives at pipe in between the first and second notes of the accompaniment figure the delay of the second note of the accompaniment will be 750ms causing this rhythmic change Also if a delayed played note reaches makenote between the second and third notes of the accom paniment the velocity of the chord will be altered e Turnontheaccompaniment and play a melody along with it 118 Tutorial 30 Number groups Summary A list is any message that begins with a number and contains additional items as arguments U su ally the arguments areall numbers but they may also be symbols Sending numbers together as a list ensures that they will be received together M any objects such as pipe makenote and noteout interpret a list of numbers received in the left inlet as if the num bers had been received separately in different inlets The pack object combines the messages it receives in each inlet into a single list The unpack object breaks alist up into its individual items and sends each item out a different outlet in order from right to left Theiter object sends each number of a
21. Thecentral building block of M axistheobject Namesof objects arealwaysdisplayed in bold type like this M essages the arguments that are passed to and from objects are displayed in plain type like this In theSee Also sections anything in regular typeis areferenceto asection of either this manual or the Reference manual MIDI Equipment The first few tutorials in this manual do not deal with M IDI directly but simply teach you about someoftheelementsof M ax Later tutorialsdo involveM IDI quiteextensively though and in the sample programs we make certain assumptions about what M IDI equipment you are using and 6 Introduction how it is connected to the computer In order to benefit the most from the Tutorial keep in mind these assumptions 1 You areusing aa61 key velocity sensitive keyboard with pitch bend and modulation wheels and apolyphonic synthesizer or sampler Your keyboard should ideally beset to send on MIDI channel 1 and the synthesizer set to receivein Omni On mode 2 Youhaveconnected the M IDI Outof your M IDI keyboard to the M IDI In of your M IDI interface and connected theM IDI Outof yourinterfaceto theM IDI In of your synthesizer or sampler 3 ForthepurposeofthisT utorial your M IDI interfaceshould beconnected to themodem port or the primary U SB interface of your computer Even if your equipment doesn t exactly match that assumed by the Tutorial try to emulatethe assumed setup asmuch as possible Y
22. Tutorial 38 exprand if CMath Functions TheC math library has many functions for such calculations as logarithms trigonometric ratios x to the power of y and so on M ax does not have specific objects for these functions but they can beincluded in the arguments of an expr object This is areal strength of expr becauseit lets you make calculations you would not otherwise be ableto makein aM ax program In themain patch of this example we use two different math functions sin and pow to calculate pitch bend curvesto bestored in thetable One formula makes a singlecycleof a sine wave with a rangefrom 0 to 127 Theother formula draws exponential curves from 64 to 127 e Check theAll Windows Active option and double click on thetable object to open its graphic window Click on thebutton at thetop of thepatch to draw acycleofasinewavein the Table window The expression in expr converts the input to a float by using the f1 argument instead of i1 in order to do afloating point calculation It divides the input by 128 so asthe input progresses from 0 to 127 it will produceaprogression from Oto almost 1 multipliestheinput by 27 approx imately 6 2832 and calculates the sine of that amount The resulting sine wave values are multi plied by 63 5 and offset by 63 5 to expand them to the proper range and thefinal result is converted back to an int before being sent out expr int sin f l 6 2992 128 63 5 63 5 e Theexpr
23. When you typea key on your computer keyboard amessageis sent to the computer telling it which key you typed M ax has objects for receiving and interpreting this information TheA merican Standard Codefor Information Interchange ASCII isthe standard system of key numbering Thekey object receives key down messages from the computer keyboard and sends the ASCII number of thetyped key out its left outlet Because key receives its input directly from thecomputer keyboard it has no inlet TheASCII number can then beused in a patch justlike any other number Thekeyup object is similar to key but it sends out theACSII number of akey when it is released when akey up message is received from the keyboard Thenumkey object receives ASCII num bers from akey or keyup object and deciphersthen to determineif anumber is being typed in on thekeyboard It reports the value of thenumber the user is entering key This example contains a single rather complex patch Atthetop of Part A isakey object Every timeyou pressakey on thecomputer keyboard key sendstheA SCII number of that key outits left outlet TheACSII number issent to an object called split split Thesplit object is acombination of relational operator and gate It looks for a specific range of numbers If thenumber received in the left inlet is within the specified range itis sent out the left outlet O therwiseit is sent out theright outlet Theminimum and maximum values of a split ob
24. cession progressing along a particular trajectory Any source of a continuous stream of numbers can therefore be used to control an animation the pitchbend wheel the mod wheel a volume pedal a counter a docker a line etc In this patch we usea line object to moveapicturealonga straight line The same principle can be applied for moving shapes e Closethegraphics window again and double click on the patcher Moving Picture object A pict object loads an entire graphics file and displaysit in a graphics window Since it loads and displays the entire file you will usually want to make sure that your image is tucked asfar as possi bleinto the top left corner of your graphics file so that the fileis no bigger than it needs to be and has no superfluous white space around the edges Thefirst argument of a pict object isthe name of the graphics window in which you want the pic tureto be shown Thesecond argument isthe name of a graphics file to show The file must be located in Max s search path if M ax can t find thefile it just prints an error messagein the M ax window and displays nothing draw or erase 1 or 0 left coordinate top coordinate Pict Animation HaxHead pict 4 window name PICT filename priority level Thethird argumentisthesprite spriority Thehigher asprite spriority thecloser to theforeground itisconsidered and it will beshown in frontof spritesthat havealower priority Thedefault prior 197 Tutorial 42 Gra
25. have the latest driver updatefrom your audio device manufacturer Please also try different set tings for the device buffer sizes and latency in thecontrol panel for your audio device provided by your device manufacturer Check that another audio application isnot using the audio device Also check that the audio deviceis not the default audio devicefor W indows System Sounds no inspector for lt objectname gt Theinspector patch for an object that expects to havean inspector cannot be found when you chooseGet Info from theO bject menu with the object selected Inspector files are normally in afolder called inspectors within the patches folder and their names areof theform lt object name gt insp pat But they can belocated anywherein the search path as long asthenameis prop erly constructed no resource lt filename gt Thiserror occurswhen you aretesting astandaloneapplication and the Search for M issing Files option has been turned off The named object or file has not been included in the collective from which the standalone was created and sincetheruntimeM ax isnot goingto look for the file it declares it missing after it was not found insidethestandaloneas a resource not enough memory to open lt filename gt lt filename gt can t load out of memory Thefileistoo largeto beopened N otethat to open a patcher fileyou need more memory than would berequired to actually use thefile object box has comma or semicolon Indicates
26. s internal clock It also counts the bang messages and sends out the count so it can be used to send a whole series of messages in asingleinstant See Also table Store and graphically edit an array of numbers uzi Send a specific number of bang messages Tables Using thetable graphic editing window 132 Tutorial 33 Probability Tables Making a Histogram A histogram is agraph of frequency distribution showing the relative occurrence of different events The histo object keeps track of all thenumbers it receives as well ashow many timesit has received each number in an internal histogram Each timehisto receives a number from 0 to 127 in its left inlet it adds that number to its internal histogram then sends the number of times it has received that number out the right outlet and thenumber itself out the left outlet This output can be sent directly to atable to keep a graphic representation of thehistogram T headdresses in thetable correspond to thenumbersreceived by histo and the values in thetable tell the frequency of occurrence of each number 64 65 64 62 numbers in the lett inlet are added 64 60 64 39 64 to the histogram and trigger output Low many times has the number been received the number adress table The frequency distribution of different numbers a comparison showing which numbers occurred most frequently is displayed in the graphic window of thetable Probability Distribution T
27. showmenubar 404 Sierpinski Waclaw 203 sine wave drawing 173 size 404 of a loaded patch 341 of objects grow bar 20 slider 28 multiplier 29 offset 29 setting the range of 28 Sliders and dials 46 special character 355 speed of computation 341 speedlim 58 split 72 sprite 195 priority 197 stack overflow 122 346 399 standalone application 220 326 Step 391 step recording 210 382 stopwatch patch 179 storing settings of objects 166 Storing numbers 77 stripnote 44 stuck notes avoiding 43 subpatch 98 101 argument to 106 352 in a collective 326 opening the window of 179 view contents of 204 swap 116 switch 61 sxformat 143 symbol received in a message object 351 synchronizing 123 synthesizer switching sounds 57 165 system 404 system exclusive 142 end byte 143 status byte 143 system exclusive programming 143 T t 24 table 125 348 Don t Save 127 entering values as text 128 141 linked to an etable editor 191 367 quantile message 357 Save with Patcher 126 saving in a file 127 stepping through values 142 storing numbers in 129 viewing 125 Table window creating 128 editing 129 tempo 122 Test 1 Printing 22 Test 3 Comparisons and decisions 64 Test 4 Imitating a performance 87 Test 5 Probability object 110 testing a patch 386 389 text blinking 226 The patcher object 98 The table object 125 thispatcher 223 thisTimeline 185 thistimeline 375 thresh 161 tiAction folder 363 tiCmd 184 362 ti
28. the box This tells M ax wherethe0 0 pointis 175 Tutorial 39 M ouse control e After you have done that click and or drag insidethe box to play notes with the mouse Pitch Velocity Duration 111 177 127 Velocity 64 0 36 lt Pitch gt 96 127 W hen you hold down themousebutton insidethebox notesareplayed continuously M ovingthe mouse from left to right in the box increases the pitch M oving from bottom to top increases the velocity Largechanges upward or downward causethetempo of thenotesto increaseor decrease Themouseis not moving any kind of slider or other type of user interface object so how does it send out notes e Unlock the Patcher window and scroll to theright to see what s going on mousestate Thegenerator of numbersin this patch isthemousestate object W hen itreceivesabang in its inlet mousestate report thecurrent horizontal and vertical location of themouseout itsleft middleand middle outlets A location on thescreen is expressed asa horizontal vertical pair of numbers normally measured as the number of pixels away from the upper left corner of the screen H orizontal location is mea sured from left to right and vertical location is measurefrom top to bottom Thecursor is 127 pixelsto theright of and 81 pixasdown from theupper left corner of thescreen W hen mousestate receives themessagezero it usesthecurrent mouselocation asthenew 0 Opoint and makes all subsequent measureme
29. theN ame Object window will display it Otherwise you ll see lt none gt e Select the object and if possible chooseGet Info from the M ax menu Thename of the object appears in thetitle bar of an object s Inspector window number numboxl Inspector hf No Min hl No Max Object namein its nspector window s title bar e Movingthecursor over an inlet or outlet of anamed object will show thenameoftheobjectin theAssistancefield of the Patcher window if Assistance is checked in the Options menu R number Crurnibos 1 bang When Tab Key Pres Object namein Assistance 229 Tutorial 46 Basic scripting Basic Scripting Scripting commands takethe following form script lt action gt lt arguments gt Scripting commandsaresent as messages to athispatcher object contained insidethePatcher win dow where you want something to happen For instance if you wanted to movethenumber box named numberbox1 to thePatcher window coordinates 15 27 thescriptingcommand to do so is script move numberboxl 15 27 A before and after illustration is shown below Script move numberboxul 15 27 Beforesendingthescript move message Script move numberboxi 15 27 thispatcher After sendingthescript move message Making Connections Thescripting commandsscript connect and script disconnect are used to connect and disconnect M ax objects They both use thesame format script connect lt outlet variab
30. to print information in the M ax window much as you d usetheprint object in a patch and you can usetheout let function to send messages out of your js object back to the M ax patcher containingit You can write avaScript code directly into the text editor for thejs object when you save a modified script thejs object will scan your codefor programming mistakes such as syntax and referenceerrors allowing you to program and debug your codefrom within M ax In thenext two Tutorials we ll examine more features of JavaScript as relevant to its usein M ax 257 Tutorial 48 BasicJavaScript Code Listing popu js simulates the logistic population equation f x rx 1 x input is r output is current x I emdy 5304 inlets and outlets inlets 1 outlets 1 global variables var x 0 66 float run the equation once function msg_float r X et K La x 3 outlet 0 x bang post the current population to the max window function bang post the current population is post x post See Also js M ax JavaScript object expr Evaluate a mathematical expression print Print any messagein theM ax window 258 Tutorial 49 Scriptingand Custom M ethodsin avaScript Patcher Scripting in JavaScript W ith theM ax js object it spossibleto use avaScriptcodeto perform patcher scripting whereyou can create M ax objectsin a patcher dynamically setting their p
31. 23 41 43 this subpateh is to add a couple of notes in between the played motes Contentsofthepatcher addnotessubpatch For example the subpatch measures the amount of time between notes 24 and 25 of the melody the speed of an aghth note then delays for that amount of time before triggering the pitch 42 Likewise thetime between the 41st and 43rd melody notes thespeed of aquarter note is used as a delay time before sending out the pitch 38 This is a simple but fairly effective method of ana lyzing the performer s tempo and playing notes in that tempo Its always a good ideain programming and elsewhere for that matter to prepare for the unex pected W hat happensif theperformer accidentally missesoneofthesenotesthat weneed for ana lyzing the tempo and triggering added accompaniment notes If the performer misses the first note of a pair for example the second note will trigger a ridicu lously largevalue from thetimer and the accompaniment note will get delayed far too long To protect against this eventuality we have used split objects to limit the time values that can be sent to delay within certain only moderately ridiculous extremes Ifthevaluefrom timer exceeds these limits the delay object will usethe delay timein its argument If the performer misses the second note of a pair but continues on the added note will never get played but by then the performer will have passed that point anyway and follow will kee
32. 255 vbrgb 2 b 255 vmrgb 0 0 5 vfrgb 0 vbrgb 0 vmrgb 1 0 5 vfrgb 1 vbrgb 1 vmrgb 2 0 5 vfrgb 2 vbrgb 2 bang draw and refresh display Note Color in OpenGL isrepresented as four floating point values in therange0 0 1 0 corre spondingto thered green blue and alpha transparency amounts respectively Thisisin contrast to many video systems that commonly refer to color in theinteger 0 255 with no alphavalue M ost of thework in our frgb andbrgb functionsisto convert from the latter used by theswatch object into theformer understood by thejsui object Mouse Interaction e Unlock theTutorial patcher and resizethejsui object the circles should resize dynamically Lock the patcher and noticethat the mouseclicks still change the states of the correct circles Lock thepatch again and look at the onclick function in the avaScript code 287 D esigningU ser Interf Tutorial 51 esigning aN Theonclick ondblclick andondrag functions when defined tell our jsui object whatto do when auser clicks double clicks or dragsthemouseacrossthe object Thefunction is called with argumentsfor wherein theobject swindow theaction occurred aswell asanumber of flags such as whether the mouse was depressed the state of the shift key etc 1n our Onclick function weonly usefirst two arguments corresponding to thex and they of the mouse click onclick deal with
33. Change the velocity byr this amount This patch contains bugs When thechangeis 0 of course thereis no problem H owever there are three ways this patch can malfunction T hefirst problem is not serious because the noteout object automatically limits velocity values in its middle inlet to keep them in the valid rangefrom 0 to 127 The second prob lem is easily solved by limiting the values coming out of the object to bealways greater than 0 with a maximum 1 object for example In fact you can limit both theminimum and maximum values by passing through a number box and setting its minimum and maximum values by selecting it and choosing the Get I nfo command from theO bject menu This has the added advantage of showing you what velocities you re actually sending out Het minimum to 1 and set Thad wm to 127 ThisfixesbugN o 2 ThisfixesbugsN os 1 and 2 Thethird problem arises because we neglected to consider a velocity of 0 as a special case which needs to be treated completely differently from all other velocity values We actually want to leave velocity values of 0 unchanged Thefollowing exampleshowsacoupleof possiblewaysto do that by sending only the non zero velocities to the object T wo possiblecorrect versionsoftheprogram The bugs we saw here did not have anything to do with misunderstanding how M ax works they had to do with mistakenly formulating thetask at hand M ax can t really protect you fro
34. D raggingon the slider sends out numbers as the mouse is moved e Click and dragon thefirst slider in the Patcher window and seethe output in the number box W hen you create a new slider its output ranges from 0 to 127 You can changethe Slider Range by selecting the slider when the Patcher window isunlocked and choosing Get Info from the Object menu T heslider automatically resizes itself to accommodatethe specified range 28 Tutorial o Usingtheslider The Get nfo dialog box also called the Inspector has two other values you can set a M ultiplier by which all numbers will be multiplied before being sent out and an Offset which will be added to thenumber after multiplication Slider Range 12 Offset Multiplier Revert i e Thesecondslider in thePatcher window hasarangeof 99 from Oto 98 but beforeanumber is sent out it is multiplied by 50 then has 100 added to it So when the slider isin the lowest position it will output 0 50 100 which equals 100 W hen theslider isin thetop position it will output 98 50 100 which is 5000 M any objects let you set optionslikethis with the Inspector Graphic Display of Numerical Values In addition to responding to the mouse theslider will moveto whatever number it receives in its inlet This makes it useful for graphically displaying thenumbers passing through it The M ulti plier and the Offset are also applied to numbers received in the inlet so the
35. Dote ons r cording 2 when stepping m Deta times Pie hes whe nre orling Messages When detonate is recording we need to send it not only the note information but also thetime elapsed since the previous message Therefore we use thesel 1 object to start atimer when record ingisturned on During recording the pitch value goes directly to detonate and also bangs the timer to report the elapsed time then it restarts thetimer for thenext incoming notemessage The timereported by timer isused asthedelta time and is combined with the pitch velocity and channel numbers to record a note event in detonate W hen theStep command ischosen thenumber 2 issent to gate to open its right outlet Instead of going to thetimer and to detonate the pitch numbers go to stripnote Thestripnote object filters out the note off messages and only thenote on pitches are used to trigger a next message to deto nate back in thep commands subpatch Note Events from detonate e Closethe input window and double click on the p commands object again W hen theuser clickson Play itsends1 from thes delaygateobject to ther delaygate object in p output and then it sends a start message to detonate Fy delaygate 214 Tutorial 44 Sequencing with detonate e Toseewherethosemessageswill go closethe commands window and double click on thep output object to open it Thenumber 1 from r delaygate opens agate to let the n
36. Editing Shortcuts Certain keys on the computer s keyboard are shortcuts for switching editing tools If you are cur rently using the pencil tool holding down the Option key on M acintosh or theA lt key on Win dowsswitchesyou temporarily to theselection tool and vice versa H oldingdown theCommand key on Macintosh or Control key on Windowstemporarily switches to thetweak tool and the Control key on Macintosh or a Right click on Windows temporarily invokes the zoom tool Shift clicking on anote adds it to or removes it from the current selection Techniques for Using detonate To use detonate as a sequencer for timed playback of note events you will need to a produce val ues for recording the duration and data time parameters of each event and b usesomesort of timing object to control the speed with which detonate sends out the note data presumably using thedetatimevalueto determine thetime between notes The following example shows thesimplest method for recording delta times and durations directly from incoming M IDI note messages in real time Use timer to record the Gime elapsed between note messages E i red ording aero the timer record nobein timer Let detonate determing note duration by wing the delta Gme between note on and note off At the same time as we send the record message to detonate we start the timer Each note message that comes in causes timer to report the elapsed time whi
37. On Lock makes objects visible which were previously made invisible with HideOn Lock Hide On Lock isan invaluable feature for making patches with a good user interface For exam ple in the patch in the right part of the Patcher window thereis no reason that the user needs to see thepgmout object and the patch cordsconnecting the various objects All that theuser of your patch needs or wants to seeisthedial thelabel comment and thenumber being sent out by the dial elect Bound Belect ounl Pomout a 1 TheHideOn Lock command lets you hideunsightly partsof a patch Note If you select a region of the Patcher window and hideseveral objects at oncewith HideOn Lock the objects will behidden but the patch cords will still be visible To hide patch cords you must select them before choosing HideOn Lock You can select patch cords by holding down the Option key on Macintosh or theA It key on Windows while dragging a box around a group of objects A lternatively choosingSelect All from the Edit menu selects all boxes and patch cords or you can just click on patch cords individually using the shift key to select multiple objects 67 Tutor al 19 Screen aesthetics Graphical user interfaceobjects such asbutton toggle dial etc that havebeen hidden with Hide On Lock do not respond to clicking and dragging with the mouse Paste Picture Your completed patch can actually have any visual appearance you choose because you can import pict
38. Ports How MIDI ports arespecified 146 Tutorial 35 seq and follow seq M ax has four objects for recording and playing back M IDI performances seq follow mtr and det onate In thischapter of theT utorial wewill discusshow to record asingletrack of M IDI datawith the basic sequencing object seq and how to comparea live performanceto a previously recorded performance in order to follow along with a performer using follow Theseq object records and plays back raw M IDI datain conjunction with midiin and midiout It understands various text messages to control its operation such as stop start and record Patch 1 contains the basic seq configuration shown above plus afew other useful messages e Click on the record message box in Patch 1 Play notes pitch bends and modulation on your M IDI keyboard Click on the word start to hear your performance played back You don t need to click on stop first because start automatically stops the recorder before playing back Thereis probably a delay before you what you played because you didn t start playing at exactly the same moment you sent the word record to seq The delay message can be used to changethe starting time of the sequence e Click on themessage containingdelay 0 to set the starting timeof thesequenceto 0 Now when you click on start again the sequence starts playing immediately Thestart message can be followed by anumber argument specifying the tempo at which
39. Theincoming number isstored in the changeable argument 1 before the messageis sent out Thenumber isthen sent to pipe and 1000ms later it is sent to makenote and on to thesynth e Thelast number to trigger the message box isstill stored in place of the 1 argument N ow if you trigger themessage box with abang thestored number will be sent out again The set Message W ehavealready seen that the messageset followed by a number can specify or replace what is stored in many objects without triggering any output The word set followed by any messagecan replacethe contents of a message box without triggering output Theword set by itself clears the message W hen an empty message is triggered nothing issent out e Click on thedifferent set messages in the portion of the patch marked C e Although thetext in the message box changes nothing is sent out until it istriggered with the bang message append and prepend Theappend and prepend objects are for constructing complex messages Theappend object appendsits arguments preceded by a space at the end of whatever message it receives and sends thecombined messageoutits outlet Theprepend object placesits arguments followed by aspace 93 Tutorial 25 M anaging messages beforethe message it receives and sends the combined message out its outlet An example of these objects isin the bottom right part of the Patcher window append semitones Prepend set Transposition T
40. Theright example shows that both symbols and numbers can replace changeable arguments It also shows that changeable arguments can be arranged in any order in themessage box making it a powerful tool for rearranging messages In the example the message assoc third 3 is sent to thecoll object W hen amessage box istriggered without receiving values for all of its changeable arguments for instance when it istriggered by abang it usesthe most recently received values Theinitial value of all changeable argumentsis 0 Symbol symbol append set makenote 0 100 In the left exampleabove amessage of 60 will initially send 60 0 to themakenote object A fter the61 65 messagehas been received however the number 65 will be stored in the 2 argument so a mes sage of 60 will send 60 65 to makenote A message boxwill not betriggered by a word received in itsinlet except for bang unless the word is preceded by the word symbol In such a case the 1 argument will be replaced by theword and not bysymbol In theright example the 1 argument is replaced by either set or append and the messageset 34 or append 34 is sent to the next message box 351 Arguments and changeableargumentsto objects To includea special character such as a dollar sign in amessage without it having a special mean ing precede the character with a backslash in an object box A changeable argument can also beused in some object boxes such ast
41. Tutorial 5 toggle and comment See Also comment Put explanatory notes or labelsin apatch led Display on off status in color togedge Report achangein zero non zero values toggle Switch between on and off 1 and 0 ubutton Transparent button sends abang 21 Tutorial 6 Test1 Printing Make a Printing Program H ereisan exercise to make sure that you understand what has been explained so far e Create a patcher program which when turned on prints the phrase test 1 In the M ax window every two seconds until it is turned off Include a way of turning the program on and off The answer has been hidden in theright side of the Patcher window Scroll to the right or enlarge the Patcher window to see the answer 22 Tutorial 7 Right to leftO rder Message Order This lesson illustrates that messages in M ax are always sent in right to left order And if a message triggers another object that object will send its message s beforeanything eseis done Knowing these two principles can help you figure out exactly how a patcher program is operating For example e Click on the button marked A The bang message is first sent to the message box containing the number 60 that message is sent to the print object and A 60 is printed in the M ax window Then the bang message is sent to the message box containing the number 50 that message is sent to the print object and A 50 is printed in the M ax window Finally the ban
42. Tutorial folder The document is a working illustration of the con cepts in the chapter text it lets you see M ax in action and try things yourself We feel this hands on approach is a more efficient way to learn about M ax than just reading the manual by itself By thetime you have completed thetutorials you will havea good understanding of M ax and its capabilities and will probably also have many ideas for your own M ax applications Asyou read each tutorial you can open the corresponding M ax document in the M ax Tutorial folder Some of the tutorials takethe form of quizzes so you can be sure you understand the material before proceeding At the end of each Tutorial are suggestions labeled See Also of other sections of the M ax documentation you can investigate in order to learn more Thereareanumber of chapters which follow the tutorials that contain discussions on issues of programming data structures loops encapsulation debugging graphics making standalone applications etc and explain specifically how those issues are handled in M ax If you are new to M ax wesuggest you begin by reading the Setup and O verview sections of the Getting Started manual then tryingafew of theT utorials You can also learn by lookingatthehelp files in themax helpfolder and by browsingtheM ax O bjectT hesaurusin theM ax ReferenceM an ual The sample patches show some of the things others have done with M ax Manual Conventions
43. above Theword objectfile followed by two symbols that specify an object name and afile name creates a mapping between the external object and its filename For exam ple the objectisin afilecalled times so at startup M ax executes the com mand max objectfile times Listthecurrent search pathsin theM ax window Thereisabutton in theFilePref erences window that does this Theword preempt followed by a1 on or 0 off toggles O verdrive mode Theword pupdate followed bytwo integer values that specify horizontal and verti cal position moves the mouse cursor to that global location QuitstheM ax application equivalent to choosing Quit from the Filemenu If there areunsaved changes to open files and you haven t sent M ax theclean mes sage M ax will ask whether to save changes Causes all M ax windowsto be updated 403 M essages tO M ax ControllingtheM ax application runtime sendinterval sendapppath seteventinterval setrefreshrate setsleep setpollthrottle setqueuethrottle setslop showglobal showmenubar size system Theword runtime followed by azero or oneand a message executesthemessageif thecurrent version of M ax isaruntimeversion 1 or non runtime 0 Theword sendinterval followed by a symbol sends the current scheduler interval to thereceive object named by the symbol Theword sendapppath followed by a symbol sends a symbol with the path of the M ax application to therece
44. all graphics files it creates which causes the control images to appear to moveslightly when they change state sincethe control has been given inaccurateinformation about thesize of theimages If you seethis problem try using another graphics application to cre ate the artwork 319 Interfaces U sing picture based user interface objects See Also matrixctrl M atrix switch control pictctrl Picture based control pictslider Picture based slider control 320 Graphics O verview of GraphicsW indowsand O bjects Introduction M ax hasseveral objects for color graphics and animation T heseobjectsusethesameprinciplesas objects that are used for music processing so asingle patcher can combineuser interface music and graphics functions This allows you to experiment with various ways of combining and syn chronizing sound and image Therearethreewaysyou can present graphicsin M ax in aPatcher window in aQuickT imemovie window or in aspecial graphics window M ost graphics objects draw within special graphics win dows associated with agraphic object Each graphic object is given aname and each object that draws something must havethe name of a graphics window as an argument When M ax isin Overdrivemode objects that draw graphics are de prioritized so that a process that both plays musicand displaysgraphicscan run at any speed and themusic will not beaffected by thespeed of thedisplay For example if an animation would ordinarily
45. always to do float arithmetic operations give the object an initial argu ment of a number with a decimal point and then send the numbers you want it to usein through theleft and right inlets bang Message in Left Inlet The program in the bottom left corner illustrates a couple of other features of operators e First send thenumber 4 to the left inlet of the object by clicking on the message containing 4 Theobject performs the calculation 4 5 and outputs the result 9 e Next sendthenumber 10to therightinlet Thenumber 5isreplaced by thenumber 10 but no output is sent Only the left inlet triggers output e Nowclick on thebutton to send abang to What happens T hebang causes to Do It in this case to do the calculation with the numbers it has most recently received 26 Tutorial 8 Doingmath in M ax List in Left Inlet Both operands can be sent to an operator together as alist received in the left inlet The operator will function exactly asif it had received thesecond number in theright inlet and thefirst number in the left inlet The numbers are stored the calculation is performed and the result is sent out e Click on the message box containing 3 20 to see the effect of sending alist to the left inlet e Then send thenumber 4 to the left inlet and you will see that the number 20 has been stored just as if it had been received in the right inlet Thisdemonstratesthat when you send alist of numb
46. are not equal gt Is greater than or equal to comparison of two numbers gt Is greater than comparison of two numbers 55 Tutorial 16 M oreM IDI Insand Outs Introduction Therearemany M IDI objectsbesidesnotein and noteout O bjects exist for receiving and transmit ting any kind of M IDI message In this chapter we introduce a few of these objects bendin and bendout for pitchbend messages pgmin and pgmout for program change messages and ctlin and ctlout for continuous controller messages Likenotein and noteout these other objects can be given optional arguments to specify the port and M IDI channa on which they will operate W hen a channel number is specified as an argu mentin aM IDI receiving object the outlet for sending the channel number disappears channel number comes out right outlet right outlet is unnecessary when when no channel mmber is specified channel number is specified bendin and bendout bendin receives data from the pitch bend wheel of your M IDI keyboard The channel is sent out theright outlet and thepitch bend data theamount of pitch bend issent out the left outlet Pitch bend data ranges from 0 to 127 with 64 meaning no bend at all The first patch demonstrates how easily onekind of MIDI data can begiven a different meaning In this case the velocity of the notes played on the synth is sent to bendout to control the pitch bend e Play asinglenoterepeatedly on thesynth T hepitch isbentupwar
47. arenot saved when thepatch isclosed but you can savetheT ext window asasep aratefileor copythenumbersand pastethem somewhereelse even into agraphicT ablewindow Whenever you want to seewhat numbersarebeingsentfrom an outlet just connect theoutlettoa capture object run the patch then view thecontents of capture e Send out various types of M IDI messages from your keyboard pitch bend modulation notes program changes etc Every byte is received by midiin and stored in capture Double click on the capture object to seethe M IDI data midiparse and midiformat The midiparse object sortstheraw M IDI data it receivesfrom midiin or from seq and sends the vital sorted data out its outlets The combination of midiin and midiparse is like having all of the specialized M IDI receiving objects in one place note data poly key control program attertoweh pitehbend channel packed as a pressure asa change at a change Piteh velocity piteh pressure ctl data list list list 139 Tutorial 34 M anaging raw M IDI data The midiformat object performs exactly the reversefunction of midiparse It prepares data into w ell formatted M IDI messages with the appropriate status byte and sends each byteto midiout for transmission to the synth note data poly key control Packed as a pressure asa change af a program pich elociy pitch presswe ctl data change aftertoweh pitehbend channel list list list midiformat Parsing and Form
48. as an action You may save it anywhere but if you saveit in the TimelineAction Folder as specified by the File Preferences command intheEdit menu it will automatically appear on timeline spop up T rack menu W hen you first install M ax the TimelineA ction Folder is a folder named tiAction inside the M ax applica tion folder Creating a Timeline To create a new timeline chooseTimelinefrom the New menu It is also possible to create a new timeline by typing timeline into anew object box Either way a graphic timeline editor window will be opened for you When you first open a timeline editor window it contains no tracks To create anew track in the window and thus load a specific action click the Track button and select an action file by name from thepop up menu T hepop up menu will show all thepatchescontained in TimelineAction Folder If you don t seethe name of theaction patch you want choose Other from the pop up Track menu and you will beableto load theaction with astandard open filedialog O nceyou have created a track you can view and edit theaction by double clicking on thelittle M ax icon in the leftmost portion of thetrack e608 Untitled i44 44 5 E Db gt gt pei 00 00 00 00 14 23 Track Display 00 00 00 00 04 00 00 08 00 00 12 00 00 16 0 bose Paced ii 1 PrintThree One Inch Four Seconds Creating Timeline Events An event isan object you placein atimeinetrack the event sends o
49. attribute to autopattr when set to 1 will automat ically nameall user interface objects in the patcher and exposethem to the pattr system Likethe M ax preset object the autopattr object will excludeany objects connected to its second inlet or if objects are connected to its left inlet allow you to only specify afew objects explicitly for naming and binding into thepattr system Because theautopattr object combines many of the features of the pattr and pattrhub objects it allows you to rapidly includelargenumbers of M ax objects with asingleobject whileallowing you to query and set their data through the same object Storing States Click on themessage box labeled clientwindow attached to the pattrstorage object The win dow that appears gives you atabulated list of all the pattr objects exposed in the patch as well 303 Tuto ri a 53 M orepatcher storage as someinformation about them Changethesettingsin someof thecontrol objects for the drawing machineand watch the window updateto reflect the new settings ean stored data name ooo j angle 2 desynch Y offset if range Pag Fo Thepattrstorage object provides a number of features for high level parameter management The client window showsthenamesof all the objects exposed to pattr in the patch including those controlled by pattr objects or autopattr objects It shows their current valuesin the last column Themiddletwo columns show therecall priority and interpolatio
50. becomesitalicized in the storage window e Createsomemore preset states by making changes to thecontrol objects then storing their settings in pattrstorage by incrementing thenumber box attached to the int object and clicking thebutton N otethat if you reusea slot number e g you savea state under slot 2 then save again theold settings areoverwritten N otethat once you havemorethan one state saved in the pattrstorage the most recent state is shown in boldface while older states are set in anormal typeface e Click on thenumber box labeled recall a preset Set it to one of the values you vestored The user interface objects should recall to their saved values and theslot column representing that state in the storage window should go to boldface Sending an integer to pattrstorage will recall the slot corresponding to that integer Attempting to recall aslot that has never been saved is harmless and pattrstorage will ignore you Interpolation e Click on the floating point number box labeled interpolate between presets Typein avalue between two adjacent slot you ve saved e g if you ve saved a state under 1 and astate under 2 type 1 5 Thepattr exposed objects will go to an interpolated value between thosetwo states Drag with themousein thenumber boxso that you effect asmooth transition from onestateto another The controlled objects will smoothly interpolate as well Floating point values sent to pattrstorage wil
51. between two note on velocitiesisfrom 1 7 to 17 4 i e from 0 007874 to 127 0 W henever theprevious velocity isless than thenew one theratio will besome fraction between 0 and 1 But if we performed an integer division theresult would always be0 when the velocity is increasing previous velocity new velocity previous velocity new velocity s E7 Oo 955224 bo ratio calculated as a Float ratio calewlated as an int Float division isneeded to get the preciseratio between two velocities 18 Tutorial 21 Storing numbers Theratio isthen multiplied by 250 again the numbers are calculated as floats so that ratios less than 1 arenot converted to 0 beforethe multiplication and theresult is used asthenew note duration for makenote and the new tempo for metro H owever notall thenumbersweget this way arereally suitableas musical values Extremechanges in velocity result in very small or very largenumbers Therange of possible valuesin this calcula tion can beassmall as 1 9685 which will betruncated to 1 when itis converted to int and as great as 31750 So weusesplit to limit the values between 40 milliseconds 25 notes per second and 2000 milliseconds onenoteevery 2 seconds Numbers that exceed these limits will beignored Thesplit object automatically converts the floats back to ints e Playafewnoteson your M IDI keyboard and observehow changesin velocity affectthenum bers being sent out of split W hen the velocity is
52. bounce glob starttime 500 bang start the task function bang tsk cancel cancel the bounce if it s going already count 0 reset the number of bounces decay 1 0 reset the initial decay tsk interval glob starttime set the initial task interval tsk repeat start the bouncing 279 T asks A rgumentsand Tutorial 50 Global O bjectsin JavaScript stop allow the user to stop the bouncing function stop tsk cancel cancel our task mytask the scheduled task output number and reschedule next task function mytask if arguments callee task interval gt 5 keep bouncing outlet 0 note send a note value decay decay Math exp count dcoeff increment the decay variable arguments callee task interval arguments callee task inter val decay update the task interval else bounce interval is too small so consider it floored arguments callee task cancel cancel the task outlet 1 bang send a bang out the right outlet to sig nify that we re done bouncing mytask local 1 prevent triggering the task directly from Max See also js M ax JavaScript object expr Evaluatea mathematical expression send Send messages without patch cords var Sharea stored number with other objects 280 Tutorial 51 D esigningU ser nterfacesin JavaScript Thejsui object allows you use avaScript t
53. by asymbol used as thename of areceive object sends al to thenamed receive object if thecurrent version of M axis arunt imeversion and a0 if not Theword getsleep followed by a symbol used as thename of areceive object causes M ax to report the sleep timeto thenamed receive object See also the set sleep message to M ax Theword getslop followed by asymbol used asthenameof areceive object reports thescheduler slop value to thenamed receive object See also thesetslop message to M ax Theword getsystem followed by asymbol used asthenameof areceive object will report thenameof the system macintosh or windows to the named receive object H ides the floating inspector window H idesthe menu bar Although the pull down menusarenot availablewhen the menu bar ishidden Shortcut keys continueto work Theword interval followed by a number from 1 to 20 sets thetiming interval of M ax sinternal scheduler in milliseconds T hedefault valueis 1 T hismessageonly affects the scheduler when O verdriveison and scheduler in audio interrupt availablewith M SP is off W hen using scheduler in audio interrupt modethe signal vector size determines thescheduler interval Larger scheduler intervals can improveCPU efficiency on slower computer modelsat the expenseof timing accuracy W hen usingtheruntime version of M ax maxinwmenu followed by thenumber 1 will placean item called Status in the Windows menu allowing users to seethe M ax wind
54. c Cross platform M ax collective format mxd iLaF M acintosh only external object mxc maxc Old format pre version 4 3 M acintosh only collective 311 FI les H ow M ax handles Search Paths and Files N ote Caseisimportant MAXB is an entirely different format than maxb An extension can beasso ciated with morethan onefiletype In that case M ax will haveto look atthefile s contents to seeif itcan determine thetype For example files ending in pat could be either text or M ax binary for mat H istorically on M acintosh OS specific file type information determined thenature of the file but when thisis absent the extension aloneis ambiguous H owever most file extensions arenot ambiguous and map one to oneto fileformats M appingfiletypesand fileextensionsareimportantin several situationswhen working with M ax e Fileswith designated extensionsthatdo nothavetypeinformation in them will showupinthe Open Filedialog wherethey might not otherwise appear For example if you have an object that openssound filesof typeAIFF W ithoutafileextension mapping fileswithout AI FF type information stored in them would not appear in theO pen Filedialog If you map the exten sion aiff to this type a file with anamelikesound aiff would be onethat you could select Filescan befound without requiring the extension as part of thename For example assum ing that pat file extensions have been mapped to M ax binary fileformats maxb You can
55. cation In that case you will naturally want the Search for Files N ot in the A pplication s Collective option to beon Pleasealso note that this feature restricts itself to looking in folders nested only three levels deep W hen your application searchesfor filesoutsidethecollective you can control whereitlookswith the Utilize Search Path in Preferences File option If this option ison which it is by default your application will use the search path settings stored in the M ax 4 Preferences file instead of using the default search path You can instruct your application to use its own Preferences file instead of the default M ax 4 Pref erences by supplyingapreferencesfilenamein thisfield If theU tilizeSearchPathin PreferencesF ile is checked and you typein aname other than the default M ax 4 Preferences your application will make its own unique preferences file in Library Preferences where represents your home directory the first timeit is run From then on your application will use that preferences file to recall the settings for options such as O verdriveand All WindowsActive The Options section of the inspector lets you change the various user related options for your standaloneapplication If the Status Window Visible at Startup option is unchecked the Status window the same asthe M ax window in theregular M ax application will not be visible when the application is opened Unchecking this option can help give your applicati
56. combining comparisons 56 comma in amathematical function 295 in amessage box 96 296 command from theM ac keyboard 76 Command key bindings 230 comment 19 clicking on 73 commenting 338 comparison 54 using to make decisions 55 63 67 computational efficiency 281 conditional if then else statement 176 constant value 282 Continue 337 control change ctlin 60 ctlout 60 controller numbers 60 conversion of message type 281 correctness checking 332 335 counter 125 284 ctlin 60 ctlout 60 cyclical pattern creating 85 D data structure 164 288 coll 289 Data structures 164 debugging 332 335 decimal number 14 decrementing 84 284 default scaling 321 default value 17 del 87 delay 87 Delay lines 87 delaying abang 87 numbers 87 deltatime 317 Designing theuser interface 225 detonate 215 317 in atimeline 306 324 devicelist from OMS 231 dial 51 dialog error 345 documenting patches 108 280 Doingmath in M ax 25 dollar sign 96 291 295 E echo 87 edetonate 306 324 editing asequence graphically 318 editor for events in atimeline 304 efficiency 281 efunc 309 emovie 310 EnableT race 337 encapsulation 216 279 error dialog 345 stack overflow 127 286 error message 338 339 etable 308 eventin atimeline 302 exponent 221 exponential curve 178 182 expr 175 expr and if 175 external clock synchronizing M ax to 128 externs 327 extra precision pitch bend data 149 409 F fade in creating 125 filetype 256
57. contents The patcher transpose subpatch contains a nested subpatch thetransposer patch that wemadein Tutorial 27 Subpatches can be nested in this manner so that each task of a patch is encapsulated and is easily modified For more on this subject look under Encapsulation in this manual Notice that we have included an additional handy feature inside the patcher transpose subpatch a flush object to turn off held notes W hen seq is playing a sequence and gets stopped by a stop mes sage it may bein the middle of playing a note and the note off message will not be sent out In Patch 1 wemadethestop message also trigger abutton which sends abang to theflush object in the subpatch to turn off any such stuck notes receive a bang to stop held notes raw MIDI data with Pitches transposed In general whenever your patch is capable of stopping seq while notes are being recorded or played back there is the potential for vital note off messages to be lost T his is especially true if your patch sends stop record or play messages by some automatically generated means Bear this potential danger in mind when constructing your patch and include an object such as flush midi flush poly or makenote whichever is appropriate to provide missing note offs Examples are shown in Tutorial 13 e Record a sequence or usethe bourr e excerpt and play the sequence with a start message Try changing thetransposition with thehslider whil
58. creation isaccomplished through the assignment of variablesto M axobj objects created by a Patcher object which represents the patch in JavaScript Thenewdefault and newob ject methodsallow you to create objects which can bedestroyed byaremove method Theconnect method lets you make patcher connections between M axobjsin your script A M axobj can beassigned to the js object itself through the box property to the patcher W hen designing avaScript functionsto act as methods for M ax messages the arguments passed with the messages are available through thearguments array from within thefunction ThenextT utorial will look at how to scheduletimed events in JavaScript how to parse arguments to thejs object itself and how to sharea variable with theM ax environment Code Listing autosurface js automatically generate a MIDI control surface with visual feedback sliders hook it up to a funnel object and use it to drive a simple sequencer Ef eld 504 inlets and outlets inlets 1 outlets 2 global variables and arrays var numsliders 0 var segqcounter 0 var thereverse 0 var thevalues new Array 128 Maxobj variables for scripting var controlin new Array 128 var thesliders new Array 128 var thefunnel 269 Tutorial 49 Advanced scripting methods start here sliders generates and binds the sliders in the max patch function sliders val i
59. detonate seq or someother sequencer such as Cubase D ouble clicking on a detonate object displays its contents in a graphic editor window allowing you to use the mouseto add or modify notes inside it It is also ableto act as a score reader much likethe follow object it looks at incoming pitch numbers and reports whenever an incoming pitch matches the current pitch in the stored score Unlikeother sequencing objects such as seq follow mtr and timeline however detonate does not really run on an internal clock of itsown Timingand duration information must berecorded into it from elsewhere in the patch and the patch must also use that information to determinethe rhythm and speed at which noteswill beplayed back from detonate Although thismeansyou ll be required to do some additional M ax programming to makeit do exactly what you want it also means that you can program recording and playback options not available with the other sequencing objects such as non realtime recording continuously variable playback tenpo and triggering individual events of the sequencein any desired rhythm Recording Into detonate You can use detonate as a sequencer of M IDI notes to store pitch velocity and M IDI channa information This basic M IDI information must be combined with timing information taling when thenote should occur and how longit should last The when is established by recording a deltatimein theleft inlet for every note event
60. duration specified in the second argument makenote sends the same pitch out again with avelocity of 0 T he result is that every note has a duration of 50ms The velocity and the duration can be changed by numbers received in the middle and right inlets The mos recent values received in these inlets are used the next time a pitch is received in the left inlet e Trychangingthevelocity and duration by draggingon theslider objects then play morenotes by dragging on the pitch slider The notes now havethe velocity and duration you specified N ote W hen no channel number hasbeen specified to noteout either as atyped in argumentor in the right inlet it is set to channel 1 by default Patch 2 demonstrates that the pitch velocity and duration values can all be received in the left inlet as alist e Click on the message box containing thenumber 60 You can see that it iscombined with a velocity of 64 then combined with a velocity of 0 after 250 milliseconds e Click on the message box containing thelist T hepitch 72 is sent out with a velocity of 96 and after 1 5 seconds it is sent out again with a velocity of 0 e Nowclick again on thenumber 60 You can see that the velocity and duration values 96 and 1500 have been stored in makenote and are applied to the pitch received in the left inlet stripnote Thestripnote object is sort of like makenote in reverse It receives a pitch and avelocity in its inlet and passes then on only i
61. e Beforeyou go on and look at the other subpatches you will want to disable the chord playing patch in the coll_ examples window Point the arrow of Ggate to theright outlet or disable MIDI in the window by clicking on the M IDI enable disableicon in thetitle bar Closethe coll_ examples subpatch window menu Themenu object creates a pop up menu in aPatcher window It can beused to choosecommands with the mouse just like any other menu and it can also be used to display messages when the number of amenu item is received in the inlet 163 Tutorial 37 Data structures When an item in the menu is selected with the mouse or by a number received in the inlet the number of themenu item issentouttheleftoutlet Theitemsin themenu arenumbered beginning with 0 IZ O S ae SSFEeZeR UWMenu After you create anew menu object choose Get I nfo from theO bject menu to open themenu Inspector You typethemenu items into the large text field in the Inspector window separating them by commas The menu items can be any type of message numbers lists words sentences whatever If you want to includeacommawithin a menu command you must precede it with a backslash Menu Text stop start record delay O read print Max Number of Items Mode orm Te hf Evaluate Item Text Options hf Auto Size O Allow Click in Label Mode fat Colors 164 Tutorial 37 Data structures If Evaluate temT extischecked in t
62. each timethey receive a bang metro 1000 These values would soon exceed reasonable ranges unless we placesomekind of restriction on them In this patch numbers sent to makenote loop repeatedly through cycles of different lengths Two methods of looping areshown Theaccum that sends durations to makenote and temposto metro starts at 1000 and multiplies itself by 0 9 every timeit sends out anumber Eventually thenumber is reduced to beless than 40 W hen this happens the message set 1000 is sent to the left inlet ofaccum resetting its stored value W ehavealready seen aset message used to set the value of aslider without triggering output Ithas thesameeffect when sent to theleft inlet of accum Every timethevalueof theaccum goes below 40 itisreset to 1000 and the cycle begins again Thetempo of themetro is also set back to 1000 at thesametime by sending a bang to the 1000 object An object box that contains only anumber is actually an int object or afloat object ifthe number contains a decimal point with itsinitial value set to that number Thisshows the basic method of looping change a value continually until some condition ismet for example until it exceeds somelimit then reset the value and begin again 80 Tutorial 21 Storing numbers Thevalues stored in the other two accum objects continueto increase without being reset but the modulo operator limits the numbers so that they always cycle within alimited range U sing
63. extras mystuffl mypatcher pat W indows specific using backslashes Versions prior to 4 3 on the M acintosh used colons for separating path elements M ax objectsthat accept paths asinput will recognizeslashes colons and backslashes but they will generally output filepathsusingthecross platform pathstyle T heconformpath object can be used to convert among different path location conventions 309 FI les H ow M ax handles Search Paths and Files In addition to the choice of separator characters you can chooseto specify afileor folder sloca tion with e an absolutepath starting with a hard disk nameas shown above e apathrelativeto theM ax application starting with a cross platform Macintosh or Windows for example patches isthe patches folder insidetheM ax application folder e apath relativeto theC ycling 74 folder starting with c74 for example c74 externals buddy mxe e apath starting with the boot volume starting with M acintosh for usewith thecolon syn tax cross platform or Windows For example Documents mystuff mypatcher exe afileanywherein thesearch path or default folder which contains no path separator charac tersat all File Types and Filename Extensions On Windows M axusesfilenameextensions a period followed by aseriesofletters asthebasis of theway theapplication knows what file format is associated with agiven application If afile doesnot have an extension M a
64. filename extensions 255 filtering MIDI messages 144 283 filtering out aspecific number 59 float 14 81 floating point division 82 flush 47 follow 155 font characteristics 19 formatting M IDI messages 145 fpic 72 227 frequency distribution histogram 138 funbuff 106 288 309 G gate 64 219 Gates and switches 63 GetInfo table 131 getruntime 328 getsleep 328 getslop 328 getsystem 328 Ggate 63 global variable 94 gracenote patch 112 graph interval 321 graphic 199 Graphics 199 graphics 199 graphics file 72 202 Graphicsin aPatcher 205 graphics window 199 grow bar 19 74 Gswitch 63 H hexadecimal number displaying 35 entering 296 hide objectsin abpatcher 210 H ideOn Lock 71 hideglobal 328 hidemenubar 328 Index Histo 138 hslider 51 if 176 imitation 91 imovie 205 improvising patch 139 in 292 incrementing 84 125 147 284 inlet Assistance description 104 inlet object 103 int 14 81 interface design 225 interpolate between points 309 interval 328 interval of timing resolution 328 inverting pitch values 52 invisible objects and patch cords 71 iter 120 K key 76 key commands 216 keyboard commands 76 entering numbers 78 keyboard onscreen 226 keyboard slider 49 keyup 79 kslider 49 L label mode for umenu 230 labeling with text 230 Icd 206 led 185 limiting numbers to aspecific range 51 76 limiting thespeed of astream of numbers 61 line 126 linear map of ranges in
65. files used by your top level patch es Add any other necessary files to your collective by click ing on thelncludeFile button or thePatcher button ifthefileisaM ax patch and choosing the appropriate file from the ensuing dialog box 328 Groupingfilestocreate Col ect Ives a single application Therearethree reasons why you may need to include files explicitly in this way First of all it s frequently the case that some object in a patch loads in data from a separate file Consider the following example When this patch is loaded it looks for thetable filevolume t and the seq file Scenel sc T hese files will not be included automatically because they are neither patchers nor external objects so you must list them in the script yourself Some objects handleinclusion of their files for you as mentioned above Currently QuickTime movies used by the movie and imovie objects as well as Jitter objects cannot beincluded in collectives Second itis possiblethat theprogram may load someadditional patch es dynamically with aload message to thepcontrol object for example Becausesuch a patch doesnot appear asan Object box in the top level patcher it is not included automatically and you must include it yourself In the following example the file panic isnot asubpatch of the top level patch but it could beneeded nevertheless and should be explicitly included in the collective We added panic using the Patcher b
66. flip it Ourbang method which in our patch istriggered by ametro object steosthrough a sequence of valuesin a manner analogous to the counter object Themaximum count is set by the number of sliders we havein our patch defined by numsliders Thedirection of the counting is always upwards snapping back to 0 when we exceed thenumber of sliders The reverse function sets a variable thereverse based on thearguments for a reverse message sent in from M ax This changes the way in which the bang method reads from the array thevalues storing thenumbers from our control surfaceof uslider objects Our two outlet functionssend our current index valueout our jsobject sright 1 outlet followed by thevalueat that index in thesequenceout our jsobject s left 0 outlet N otethat we follow theimportant M ax convention of outputting values from outlets in aright to left order O therwise our pack object would be triggered by its left inlet before it receives the value it needs in its right inlet 268 Tutorial 49 Advanced scripting Theoutlet function outputs the valueat the current index in the sequence out our jsobject s left 0 outlet e Nowthat you know how the avaScript codeis working play with the patch some more Think about how you would recreate the sequencer using thenormal M ax table and counter objects Summary Thejs object offers you a powerful way to create M ax patches dynamically in JavaScript O bject
67. from M ax via M IDI For moreinformation about working with DLS synths seethe sec tion Using M ax with MIDI chapter in the Getting Started manual To open the sample program for each chapter of the Tutorial choose O pen from the File menu and find thedocument in the M ax Tutorial folder with the samenumber asthe chapter you are reading e Open thefilecalled 1 Saying H alo Objects and Messages e Click in the box marked Hello Notice what happens in the M ax window each time you click on Hello Tutorial 1 Saying Helo The basic operation of a patcher program is simple Different types of boxes called objects send messages to each other through patch cords This program contains two different objects The box containing the word printisaprint object A print object prints whatever message it receives in the M ax window The word Hello isa message contained in a message box which can contain anything that can be typed Often a message will contain numbers Different kindsof objects havedifferent numbersof inlets and outlets Themessage box always has oneinlet and one outlet in let k amiet Inlets are always at the top indicated by blackened areas at the top of an object O utlets are always at the bottom of an object The print object has no outlet its output is always just printed in the M ax window Usually an object will have both inlets and outlets it receives messages performs some t
68. hekey points in the program involvethe main drawing function which defines a sequence of commands to describethejsui object s graphical display and themouseinteraction functions onclick ondblclick and ondrag mportantthingsto notearethedifferencesin color representation floatingpointvs integer and spatial coordinates floating pointworld coordinatesvs Cartesian pixel coordinates between the O penGL API used in thejsui sketch object and the M ax environment respectively Code Listing mymatrix js simulates a simple grid of clickable widgets a la matrixctrl 7 eld 5 04 inlets and outlets inlets 1 outlets 1 global variables var ncols 4 default columns var nrows 4 default rows var vbrgb var vmrgb var vfrgb ott dl HEED CA WoO initialize state array var state new Array 8 for i 0 1 lt 8 i state i new Array 8 for j 0 j lt 64 j state i j 0 289 D esigningU ser Interf Tutorial 51 esigning 7 ae set up jsui defaults to 2d sketch default2d initialize graphics draw refresh draw main graphics function function draw with sketch set how the polygons are rendered glclearcolor vbrgb 0 vbrgb 1 vbrgb 2 vbrgb 3 set the clear color glclear erase the background colstep 2 ncols how much to move over per column rowstep 2 nrows how much to move over per row for i O0
69. image is redrawn will depend on the speed of your computer Summary Pictures and colored shapes can be drawn in agraphics window which is created by placing a graphic object in your patch The name argument given to the graphic object is also given to any object that drawsin its window T he objects frame oval rect and ring are used to draw geometric shapes into a graphics window The pict object loads an entire graphics file into memory and dis playsthe picture at any specified location in agraphics window Each imagein agraphics window is a sprite which you can move around by redefining its coordi nates and which is assigned a priority that determines whether it will be drawn in front of or behind other sprites You can animate sprites in such a way as to give the illusion of continuous movement by redrawing them in rapid succession in different locations along achosen trajectory Any continuous stream of numbers may potentially be used to describe such atrajectory 198 Tutorial 42 Graphics Theparameters and location of theshapesand pictures drawn in thegraphics window can beeas ily correlated to MIDI datato createthedesired correspondencebetween sound and images This is usually achieved by multiplying arange of values by some factor to makethen appropriate for useboth as M IDI data and as pixel locations The poly object assigns a unique voicenumber to each note currently being held This voice num ber can beused to route th
70. inlet Occurswhen you try to connect theright outlet of a grab object to the wrong inlet of another object The right outlet of grab should beconnected only to the leftmost inlet of other objects graphic lt name gt already exists Occurs when you createa graphic object with aname that has already been taken by another object such as atable or send receive pair 396 Erro rS Explanation oferror messages inlet wrong message or type Occurs when a patch is running and an object receives a message that it doesn t expect in some inlet other than the left inlet midi_mme unable to open midi input device midi_ mme unable to open output device Windows only M ax was unableto open themidi input or output device Please exit from all other midi applications and try again MSP ASIO Unexpected error loading driver MSP ASIO error loading ASIO driver for MSP ASIO Error loading driver W indowsonly A problem wasencountered loadingtheASIO driver Please check that you have the latest driver updatefrom your audio device manufacturer Check that another audio applica tion isnot using the audio device Also check that the audio deviceisnot the default audio device for Windows System Sounds MSP ASIO initialization error MSP ASIO can t deal with bufsize MSP ASIO data format lt format gt not supported MSP ASIO driver start error W indowsonly A problem was encountered initializingtheASIO device Please check that you
71. is located in M ax sfilesearch path asan argumentto timeline that timeline filewill be automatically loaded in and you can then play that timeline score by sending a play message to thetimeline object timeline TimelineFile ti Play the previously sawed timeline File With theread message you can load a different timeline file into the same timeline object replac ing any timeline score that was there previously and play it read AnotherTimelineFile ti timeline TimelineFile ti N otethat for thisto work effectively thetimelinefile s must bein M ax sfilesearch path as speci fied by the File Preferences command in the Edit menu or in the same folder as the patch that is trying to load them and the action patches used by those timelines must also belocatable in the TimelineAction Folder specified in the File Preferences dialog or in thesame folder as the patch that contains thetimeline T hetimeline object understands a great many other messages for con trolling it or altering its parameters See the timeline page in the O bjects section for details Playing atimelinefrom within a patch can seem alittle mysterious since once the messages are sent from thetimeline all the action takes placein the action patches which in most cases are out of sight H owever you can create interaction between atimeline and the patch that contains it M essages which are sent to ticmd objects in actions from the timeline event track
72. issent out asalist with thenumber 3000 Thelist is received by pipe 3000 is stored as thenew delay time and thenumbersare delayed for 3 seconds before being sent on e Next click on all threemessage boxesin part D to construct the message 1 3000 1 200 speedlim 30 append 3000 append 1 200 1 3000 1 200 e Nowwhen you send numbersto themessage box it sends out two lists resultingin each num ber being delayed both 3000ms and 200ms semicolon W hen asemicolon appears in amessage box thefirst word after thesemicolon isinterpreted as thenameof areceive object The rest of the message or up to thenext semicolon issent to all receive objects with that name instead of out the message box s own outlet 95 Tutorial 25 M anaging messages e Click on themessage box marked E containingthenumber 700 shommsg delay 1 pipe 1000 Thenumber 700 issent outtheoutletto theright inlet of pipe thenumber 0 issent out the outlet of ther transp object and the message delay 700 is printed in the M ax window Thisis away of send ing many different messages to different places with asingletrigger Summary In addition to simply beingableto send any message out its outlet themessage box can be used to construct messages and to send them to different places Thecomma is used to separate different messages within a message box and send them out one after theother W hen amessageispreceded
73. itto open itsown editor window draw in thenoteevents and 383 Detonate GraphiceditingofaM IDI sequence when thetimelineis played the notes will be sent out over the period of time represented by the length of the edetonate in thetimdine e808 edetonate_t pat 144 44 0 P Db b gt pp 00 00 00 i 00 09 14 00 00 00 00 04 00 00 08 00 e gt 1 Detonation Notes sharedScore mene ea 1 One Inch Four Seconds am This means that the time units shown in the editor window of edetonate are actually relativetime units becausethereal timein which they occur dependson thelength of theeventin thetimeline In the preceding example for instance each of the notes was drawn into edetonate as a 1 second note but becausetheevent stretches out over precisely onesecond in thetimeline thelist messages will actually besent to ticmd Notes every of a second when thetimelineis played However if you want thenotes in edetonate to be played at exactly the same rate as they were drawn in thegraphic editor window select the edetonate and choose Fix Width from the O bject menu Thelength of the edetonate will be changed so that its notes play at the same rate as they were drawn in edetonate s editor window By selecting an edetonate editor and choosing Get nfo from theO bject menu you can assign it aname I twill then shareitscontentswith any other edetonate editorsthat havethesamename or with a single detonate obj
74. ll look at some of the ways in which thejs object can help you catch mistakesin your program TheM axjs object uses version 1 5 of the avaScript language developed by N etscape W hilewe don t presume specific knowledge of JavaScript in these tutorials the better you understand the language the easier it will befor you to develop code Thedefinitivereferencefor the version of JavaScript we usein M ax can befound at thefollowing URL 248 Tutorial 48 BasicJavaScript http devedge netscape com library manuals 2000 javascript 1 5 guidg Note Thereare many variations on the JavaScript language as well asa number of extensions to the language specifically designed for its usewith web browsers The M axjs object supports only thecorejJ avaScript language as outlined at the U RL above as well as someextensions added to thelanguageto support interfacing with M ax JavaScript in Action Open thetutorial patch 48 Basic avascript pat If you want to hear the M IDI playback from thepatch makesureyou havean output synthesizer configured to listen to M IDI outoputfrom M ax seeT utorial 12 Sending and receiving M IDI notes if you need review on thistopic Click on thetoggle at the top of the patch to start theqmetro object Thefloat object sends a value into the js object at every tick of the metro Slowly increment the floating point number box attached to therright inlet of thefloat object The output of thejs object will cha
75. metronome but it operates in somewhat more traditional musical terms than the millisecond specifications necessary with clocker metro and line The first argu mentto tempo or anumber received in theleft middleinlet setsametronomictempo in termsof beats per minute thatis quarter notes per minute just like atraditional metronome Thesecond and third arguments or numbers supplied in the right middle and right inlets spec ify what fraction of awholenotetempo will useto send out ticks of the metronome For example ifthesecond and third arguments arel and 16 thefraction is of awholenoteand tempo sends out anumber from 0 to 15 for every sixteenth note based on the specified quarter note tempo A fraction of 2 would send out half note triplet ticks atick every 2 of a whole note and so on The numbers sent out by tempo always go from 0 to thenumber 1 less than the pulse division the third argument T he greatest allowable division is 96 sixty fourth note triplets The fact that tempo sendsoutanumber asortof pulseindex lets you assign different thingsto happen on dif ferent pulses in a measure In this way you can generate metrically based automated processes 122 Tutorial 31 Usngtmes In PatchF tempo sendsout anumber for each sixteenth noteat atempo of 80 and triggersa differ ent pitch and velocity for each pulse of the measure The pitch ascends in an arpeggiated aug mented triad and the velocities are greater on
76. mousestatus and location 181 mousefilter 180 M ouseState 181 mtr 160 multiplier of aslider or dial 30 multi track M IDI file 300 317 M ulti track sequencing 160 multi tracking 160 mute atimelinetrack 313 N New Object List 10 notein 42 note off message filtering out 47 supplying 45 noteout 42 Now 111 number 14 typing on the M ac keyboard 32 78 Number box 14 32 as a debugging tool 334 Number boxes 32 Number groups 120 numkey 78 411 O object box punctuation in 295 objects aligning 11 creating 9 nonexistent 340 sizeof adjusting 19 74 using a patch as an object 105 octave parallel octave patch 42 random octavetranspositions 118 offset of a slider or dial 30 omni mode 43 oneor both numbers arenot zero 56 onscreen control 49 Open 7 Open Track File 313 or 56 ornamentation patch 113 outlet Assistance description 104 outlet caching 282 outlet object 103 Overdrive 85 282 P pack 121 paletteof graphic editing tools 134 panic command 232 PassPct patch 115 Paste Picture 72 patch cord receive messages without 94 segmented or straight 70 send messages without 94 wiretap in 334 patcher object 102 argumentto 292 paths 329 pcontrol 184 294 periodicity 85 pgmin 60 pgmout 60 picture clicking on 73 Index in apatch 72 pipe 87 pitch bend 14 bit xbendin 149 14 bit xbendout 149 bendin 59 bendout 59 controlled with velocity 59 pitch velocity grid 180 pointer 147 poly 200 port changi
77. mtr M ulti track sequencer seq Sequencer for recording and playing M IDI Sequencing Recording and playing back M IDI performances 154 Tutorial 36 M ulti track Sequencing mtr The mtr object is M ax s most versatile sequencer It can record and play back up to 32 different tracks of messages numbers lists or symbols The tracks can be recorded and played back either separately or all together With this versatility you can record and play back not only M IDI bytes butnumbersfrom any object such asaslider or adial sequencesof text messages to bedisplayed to the user pitch velocity lists etc Well show how mtr is used to record and play back M IDI data Thenumber of tracks in an mtr object is specified by atyped in argument The leftmost inlet isa controlinlet for receiving commands and theother inlets arefor messages you want to record The command messages for mtr aresimilar to those for seq but not identical Notably mtr under stands the message play instead of start and the play message does not take a tempo argument When command messages such as stop play record mute and unmute are received in the left inlet they apply to all tracks of mtr These commands can be followed by anumber argument however specifying auniquetrack to which the message applies A Iternatively these messages can be received in an individual track sinlet to give a command to just that track A4 Track Simul Sync Recorder Patch 1 s
78. mtr file using M ax s text editor detonate Thedetonate object is a flexible sequencing graphic editing and score following object It can record alist of notes tagged with time duration and other information You can save the note list asasingle track format 0 or multi track format 1 M ID I file and you can read in any M IDI file that has been saved to disk by detonate seq or someother sequencer D ouble clicking on a deto nate object displays its contents in a graphic editor window allowing you to usethe mouse to add or modify notes inside it Itis also ableto act as a score reader much likethe follow object it looks at incoming pitch numbers and reports whenever an incoming pitch matches the current pitch in thestored score But unlike other sequencing objects such asseq follow mtr and timeline however detonate does not really run onan internal clock of itsown Timingand duration information must berecorded into it from elsewhere in the patch and the patch must also use that information to determine the rhythm and speed at which notes will be played back from detonate allowing for recording and playback optionsnot availablewith theother sequencing objects such asnon realtimerecording continuously variable playback tenpo and triggering individual events of the sequencein any desired rhythm 360 Recording and playing back Seq uenc ng M IDI performances timeline Thetimeline object is designed for graphi
79. nakenote 64 100 eee e Click on thetwo message boxes marked A in thebottom left portion of thePatcher window Onemessage box contains alist of threenumbers 40 59 80 W hen makenote receives thelist it interprets thethird number asa duration the second number as anote on velocity and the first number asa pitch Theother message box contains three separate messages It sends 40 then 59 then 80 and each number is interpreted as a pitch by makenote You can see the mes sages printed in the M ax window and you can hear the difference in result Thisisoneway to play achord The Changeable Argument Thedollar sign isaspecial character in amessage box Itisachangeableargument an argument that is replaced by an item from theincoming message For example if a message box contains The pitch is 1 and the velocity is 2 and receives the message 60 64 in itsinlet it will send out The pitch is 60 and the velocity is 64 T henumbers60 and 64 arestored in place of 1 and 2 until they arereplaced by other values received in theinlet Thedollar sign can befollowed by numbers in therange 1 9 e Dragon thenumber box marked B in thetop left corner of the Patcher window After being limited byspeedlim each of thenumbers triggers the message box Becausethe message box 92 Tutorial 25 M anaging messages contains the changeable argument 1 the 1 is replaced by theincoming number beforethe message is sent out speedlim 30
80. name or by sending a port message in the inlet The midiparse object interprets raw M IDI datafrom midiin and sends each typeof data out a dif ferent outlet The counterpart to midiparse is midiformat which receives data in its various inlets and prepares different types of complete M IDI messages which are sent by midiout To aid you in formatting system exclusive messages to be sent by midiout sxformat lets you typein arguments which it sends out one a a time as individual bytes You can include changeable argu ments in sxformat which will be replaced by incoming numbers before the message is sent out 145 Tutorial 34 M anaging raw M IDI data Thecapture object storesalist of all thenumbersit receives You can view thelistin aT ext window by double clickingon thecapture object and you can copythecontentsofthatT extwindowintoa Tablewindow T he capture object is good for viewing any stream of numbers when you aretrying to figure out exactly what numbers are coming out of an outlet See Also midiformat Prepare data in theform of aM IDI message midiin Output incoming raw M IDI data midiout Transmit raw M IDI data midiparse Interpret raw M IDI data sxformat Prepare M IDI system exclusive messages xbendin Interpret extra precision M IDI pitch bend messages xbendout Format extra precision M IDI pitch bend messages xnotein Interpret M IDI note messages with release velocity xnoteout Format M IDI note messages with release velocity
81. newly received numbers To see any kind of message symbols numbers lists whatever you can usethe Text object It works similarly to capture although its memory capacity is somewhat more limited To see any message directly in the M ax window useprint Theprint object does not try to understand the messages it receives it just posts them verbatim in the M ax window TheM ax window scrolls as each new message is printed and you can scroll up to see previous messages T he disadvantage of print isthatthetimeneeded to print the messages and scroll the M ax window isoften greater than the time between messages so print may get behind affecting the timing of your patch If all you need to do is verify that some message any message has been sent use a button which will flash each timeit receives any kind of message Message Order Sending messages in incorrect order is a frequent cause of bugs It s important to remember the basic rules of message order which will help you write your patches correctly Him whaneous messages are sent owt im right to left order Leftmost inlet is the triggering inlet gnoringthisright to left orderingcan lead to bugsliketheonein thefollowingexample H erethe intent isto reduce the velocity of all notes from M iddleC on up In the patch on the left however 389 Deb U gg ng Tipsfor debugging patches because the velocity value is sent out of notein before the pitch value and the
82. notes OEE Record Phy Bhp flushinput 212 Tutorial 44 Sequencing with detonate Although it snotstrictly necessary each incomingcommand also stopsdetonate beforegivingita new command and stopsany delayed bang messages that may existin thep output subpatch ifdeto nate were playing OEE Eecorld Phy tep stopdelays Then finally each of theincomingcommandsopensor closestheappropriategate objects in thep input and p output subpatches and sendstheappropriatecommand to detonate So for example an Off command will 1 flush any held notesin thep input subpatch 2 stop any delayed bang messages in the p output subpatch 3 stop detonate 4 send 0 to thep keycommandssubpatch so that theR eturn and Enter keyswill no longer haveany effect 5 closeagatein thep input subpatch to stop incoming M IDI notes 6 flush any held notesin thep output subpatch Ore fluslinput flushoutput stopdelays MIDI Input to detonate e Closethe commands window and double click on thep input object 213 Tutorial 44 Sequencing with detonate A gate objectis used to routetheincoming M IDI pitch numbers to the proper place W hen deto nate is stopped or playing we want it to ignoreincoming M IDI information so thegate is closed When recording the pitches are sent out the left outlet of the gate and when stepping through notes the pitches are sent out the right outlet of gate Whe n stepping
83. notes duration value You can suppress the note off messages by selecting the edetonate editor choosing Get I nfo from the O bject menu and unchecking the Send Note Offs option In the same dialog box you can typeanamefor the editor in the Explode Label box All edetonate editors that share the same namealso sharethesamedata T hey can also sharetheir datawith asingledetonate object that has thenametyped in as an argument timeline NoteVariations ti detonate theme se A single detonate object with a typed in argument shares data with any edetonate editors with thesamenamein thetimaine Note that the horizontal length of an edetonate on thetimeline determines its real duration The time and duration valuesin theedetonate editor window are actually relative times which will be scaled when the timeline is played to fit in the time occupied by edetonate in the timeline Select ingan edetonate editor and choosing the Fix Width command from the O bject menu makes the length of theedetonate equal to thelength of thesequenceit contains If you makeany subsequent changes to the contents of the edetonate or its associated detonate object in a patcher you will haveto adjust it once again with the Fix Width command in order for it to play without its time being scaled The etable Editor Thereare actually three different possible event editors for sending messages to ticmd objects that expect a single integer int likethe number box eta
84. number of core objects that provide functionality for common programming routinesthat you may find necessary TheM ath object for example givesyou accessto avariety of mathematical functions that you would find in theC math library or in the M ax expr object Arguments to thejs object are handled by the jsarguments property to the object The object startsnumberingitsargumentsat 0 but thefirst argument to js isthenameof thesourcefileit had loaded Global objectsin JavaScript allow communication between js objects and allow for object proper tiesto beset directly from the M ax environment 278 T asks A rgumentsand Tutorial 50 Global O bjectsin JavaScript Code Listing globaltask js generate a stream of numbers timed to an exponentially decaying time curve arguments set the curve and the value to output rid 5 04 inlets and outlets inlets 1 outlets 2 define global variables and set defaults var tsk new Task mytask this our main task var count 0 Ae Ove var decay defaults for arguments var dcoeff 0 0002 decay coefficient var note 60 note to trigger upon bounce process arguments decay coefficient note to trigger if jsarguments length gt 1 argument 0 is the name of the js file dcoeff jsarguments 1 if jsarguments length gt 2 note jsarguments 2 Global Max namespace variables glob new Global
85. number within aspecified range but it keeps track of thenumbers it has sent out and doesnot send out the same number twice until its memory has been cleared Thus urn is useful for generating a ran dom non repeating sequence of any set of messages or events See Also bpatcher Embed avisiblesubpatch insidea box Graphics Overview of graphics windows and objects imovie Play a QuickTime moviein a Patcher window Icd Draw QuickDraw graphicsin a Patcher window menu Pop up menu to display and send commands urn Generate random numbers without duplicates Tutorial 42 Graphics 209 Tutorial 44 Sequencingwith detonate Extended Sequencing Capabilities In this chapter we demonstrate the use of the detonate object for sequencing M IDI note events and weshow how detonate can beused to implement moreadvanced sequencing capabilitiessuch as non realtime step recording continuously variable playback tempo and triggering individ ual notes on command Becausethis is a fairly complex patch it is also instructive as an example of how to organizeamazeof communications between objects by encapsulating thevarioustasks into separate subpatches Thefunctions of this patch are 1 torecord incoming MIDI notes 2 to play them back while varying the tempo or 3 to step through the recorded sequence one note at a time by triggering each note from the computer keyboard or the M IDI keyboard You can switch from one function to another by clicking
86. object based solution to a programming problem and a comparable solution using expr double click on the patcher expr_ example object For this example we want to solve the following problem as the modulation wheel progresses from 0 to 127 send pitch bend values from 64 to 127 and back down to 64 T he patch on the left showsa standard Patcher way of doing this The patch on theright shows the different tasks all combined into a single mathematical expression in expr ctlin ai 1 expr 127 abs i1 63 A single expr object performs the same task as 4 objects in the pateh on the lett Notice that the changeable arguments in an expr object include a letter asin i1 to tell expr what datatypeto use for that argument i for int f for float e Movethemodulation wheel on your MIDI keyboard from 0 to 127 and you ll see that both methods of stating the mathematical expression work equally well However it s a bit more memory efficient to use a single object instead of four if Another staple of C programming is theif se combination In Pascal thisis expressed as F condition TH EN statement ELSE statement In plain English this means if a certain condition is met do onething otherwisedo another thing Sometimes this way of thinking about the world just seems to makea lot more sense than a bunch of boxes connected together with wires M ax has an object called if which lets you express programming prob
87. occurs when an object attempts to allocatetoo much memory at interrupt level Unless it represents a bugin the object it may mean that you ll haveto modify your patch to usea defer object wherememory is being allocated Oneexample would be attempting to store large lists of datain acoll object Seethe defer object pagein the M ax Reference manual for more details check failed lt message gt Occurs when thereisa bugin the M ax application or in an external object Please report the con tents and context of any such message to Cycling 74 could not load QuickTime function W indowsonly A necessary QuickT imefunction was not found M akesure you haveinstalled QuickTimefor Windows and chosen acomplete install of all optional components Error loading external file lt filename gt Occurs when M ax isinstalling an external object in thestartup folder T he external object fileis damaged Try restoring a copy from the original disk funbuff bad file type funbuff file not found Occurswhen apatch isloaded or when afunbuff objectiscreated that readsin from aseparatefile Therewasan error in reading afileinto afunbuff either because the file was not in the proper for mat it must start with the word funbuff followed by a space separated list of numbers or because aM axor text filewith that namecould not befound Ensurethat thefileisin located in M ax s search path and that it isin the proper format grab can only connect to leftmost
88. of thevalue share objects by sending a bang to itsinlet All value objects with the same name share the same value even if they are located in different Patcher windows Summary Any message received in theinlet of asend object comes out the outlet of all receive objects with thesamename argument even ifthey arein different Patcher windows T hisisvaluablefor com municating between Patchers A message stored in avalue object is shared by all value objects with the same name even if they arein different Patcher windows W hen a value object receives a bang in its inlet it sends the mes sage out the outlet even if the message was received in another value object with thesamename See Also pv Sharevariables specific to a patch and its subpatches receive Receive messages without patch cords send Send messages without patch cords value Sharea stored message with other objects 91 Tutorial 25 M anagingM essages Using the message box So far we have used the message box to send asingle message triggering it either with a mouse click or with abang anumber or alistin itsinlet The message box has many additional features for constructing and changing messages some of which are displayed in this patch comma If a message box contains acomma messages are sent out one after another In this way messages can besentin rapid succession in responseto a single trigger pich velocity duration 3 sugeessie pitches
89. on any note offs it receives but in this case stripnote has filtered them out e Nowclick on thebutton to send abang to the left inlet of flush T heflush object keeps track of all thenote onsit has received that have not been followed by note offs and when a bang is received flush provides note offs for those held notes Theadvantage of sending pitch and velocity pairsthrough flush beforesendingthem to noteout is that flush hasno noticeableeffect until it receives a bang then itturns off any notes that arestill on Thisis useful for turning off stuck notes Summary A MIDI note on messagetransmitted by noteout should befollowed by acorrespondingnote off message so that the note played by the synthesizer gets turned off The makenote object combines pitch values with velocity values to besent to noteout After a cer tain duration thesamepitch issent with avelocity of 0 to turn off thenote Thestripnote object is theoppositeof makenote Itfiltersoutnote off messages pitch velocity pairsin which thevelocity is 0 and passes on only note on messages messages with a non zero velocity The flush object keeps track of thenotes that have passed through it and when it receives a bang it sends out a note off for any notes which are still on See Also flush Providenote offs for held notes makenote Generate a note off message following each note on poly Allocate notes to different voices stripnote Filter out note off messages pa
90. on buttons onscreen actually message boxes or by typing key commands on thecomputer s keyboard Using the Patch Beforeexamining the construction of this patch you may want to useit to get an idea of what it does e Click on the Record message box or typer and play a melody or some arpeggiated chords on your M IDI keyboard for at least fifteen seconds or so e When you havefinished playing you can hear your performance played back by clicking on thePlay message box or typingp You can vary thetempo of the playback from to 2 times the original tenpo by dragging on the horizontal slider in the tempo window e Return thetempo to 1 then click on the Step message or types You can now play each of the recorded notes one at a time by playing any key on your M IDI keyboard or by typing the Enter or Return keyson M acintosh or theEnter keyon W indowson your computer keyboard e When you havefinished click Off or typeo You can edit the recorded notes by double click ing on the detonate object Encapsulation of Tasks To keep thispatch neat and comprehensible it was necessary to think of itin terms of thedifferent tasksto beperformed asoutlined above and then try to encloseeach task in itsown subpatch 210 Tutorial 44 E ree So thereis one patcher for capturing key commands from the computes keyboard another for actually performing the commands one for getting M IDI input and sending it to detonate one for s
91. on thecoll object in Patch 2 to view its contents 162 Tutorial 37 Data structures Theformat we have chosen for our datastructurein thiscoll is metrocommand tenpo duration and note velocity Because each message stores the data in the same order we can access individual items in the data structure and usetheitem in a specific way The data structure is parsed as it comes out of the coll The message is first sent to route If the first item of themessageis 1 meaningmetroon weusetheremainingitemsin themessageto supply a duration to makenote atempo to metro and avelocity to makenote If thefirst item in the message isnot 1 in this case 0 isthe only other possibility nothing needs to besent so route ignores the message After the essential data is supplied to metro and makenote the first item is used to turn themetro on or off Other Features of coll These examples should give you a taste of what coll can beused for Theremany other command messages which coll understands too numerous to cover in detail in this Tutorial For example you can step through the different messages in coll with goto next and prev commands And you can select or alter individual items of stored messages with commands such asnth to get the nth item within a message sub to substitute an item in a message and merge to append items at the end of a message For details about these commands look under coll in the M ax Reference M an ual
92. onestateof thecontrol Thestate of a control includes its current value whether the user is clickingit with themouse and so on Atany given time theuser sees only oneimagefrom the array contained in thepicturefile e Allimagesin thearray arethesamesize T hissizemay correspond to thesizeof theobjectasit appearsin the M ax patcher or the object may alter theimage s size e Someparts of thearray areoptional For example the controls can optionally display a differ ent image when the user clicks them You do not need to create blank images in the array for optional images that your control doesn t use Just leavethe row or column out of thearray altogether e Themanne in which thecontrol chooses what portions of the picture fileto display is deter mined by theobject sattributesthat you set with its nspector and by theoverall dimensionsof the picturein thefile Picture File Construction Theeasiest way to understand how picturefiles must be constructed and how the corresponding object attributes must beset isto look at some examples W e ll look at several examples using pictctrl Thepictctrl objects use only onepicturefile so it sthe simplest to work with A simple button control has only two states either the user is clicking on it or not Thus apictctrl being used asabutton needsapicturefilewith two distinctimages onefor theclicked state and onefor theidlestate 314 Interfaces U sing picture based user interfac
93. p keycommands object to see its contents Ent Eet Esc ora In addition to the mnemonic key commands o r p and sfor triggering the message boxes the Escape key is used as a synonym for off and the Return and Enter keys on M acintosh or the Enter kay on W indowscan beused to step through thescore If thenumber 1 hasbeen received from the r keysteps object then Return or Enter on M acintosh or Enter on W indowswill trigger a next mes sage in another subpatch via thes bangnext object The Central Command Post Analysis of thedifferent functions of thepatch revealed that the user interfacecould really bevery simple four clickable commands with keyboard equivalents H owever each of thosecommands must actually trigger a variety of actions throughout the whole patch T he p commands subpatch is for ensuring that all of those actions are carried out in the proper order when a command is received e Closethe keycommands window and double click on the p commands object to see its con tents Theoutput of each of theclickablemessage boxes comesin the oneof theinlets of p commands and is converted to a bang with ab 1 object and that bang triggers everything that needs to happen for each command Each new command that comes in could potentially cause detonate to stop recording while a note isin the process of being recorded so the first thing each command doesis bang a flush object in thep input subpatch to turn off any incoming M IDI
94. patch and can either beused insidetheaction patch or sent elsewhere via asend object or atiout object Oncethe score of M ax messageshas been composed on thetimeline it can besavedin afile and then can beaccessed from a patcher by reading thefileinto atimeline object You play thetimeline by simply sending a play message in the inlet of thetimeline object You can also move to a specific time location in thetimeiine with the locate message or by searching for a marker event with the search message 192 Tutorial 41 TimdineofM axmessages An action patch can send messages out the outlet of thetimeline object that contains it viathe tiout object An action can also control thetimeline that contains it viathethistimeline object Thetempo of atimeline can becontrolled in real time by syncingitto asetclock object and sending messages to the setclock possibly even from thetimeline itself See Also setclock M odify clock rate of timing objects thistimeline Send messages from a timeline to itself ticmd Receive messages from atimeline timeline Time based score of M ax messages tiout Send messages out of atimeline object Timeline Creating agraphic score of M ax messages 193 Tutorial 42 Graphics The Graphics Window In M ax you can statethe vital information about amusical notein terms of integers specifying key number velocity channel and with makenote for example duration in milliseconds M ax also allows you to place p
95. pi oP Spies psp clock scalespeed timeline tutoriald4 ti 3 setclock scalespeed mul scalespeed eventsin thetimelinetrack arereceived by theticmd object in theaction patch and aresent out thefirst outlet of thetimeline object to setclock which changesthetimeline object tenpo The above exampleisa rather complex situation which is included here primarily in order to demonstratetimeline object s ability to control itself and to demonstratetheoperation of thetiout and setclock objects H owever thenumbers that go into setclock to change its tempo could come from any source such as aslider or aM IDI controller with the proper arithmetic to map the numbers to an appropriate range of floats e Ifyou want to revert timeline to following M ax s regular millisecond clock click on the mes sage box that says clock Thereisonly oneremaining part of the patch that has not yet been explained W hen thetimeline receives the message markers 3 as it does when the patch is loaded it sends the first word from 190 Tutorial 41 TimdineofM axmessages each of itsmarkersoutitsthird outlet to bestored in themenu object Thismenu can then be used to causetimeline to go immediately to any of the markers markers 3 prepend search timeline tutarial4d ti 3 e Try usingthemenu to jump to a specific section in thetimeline You can do this while the timelineis playing Editing the timeline Thetimelinein this t
96. pitch to becounted twice and the velocity 0 would be by far the most common velocity e Open thetable editing windows containing the histograms of pitches and velocities and play on thesynth to see how thedistributions are stored Rhythm Analysis In the patch we usea simple method of rhythmic analysis to keep a histogram of the rhythms played Weuseatimer to get the time between note ons and dividethetime by 30 to get the rhythm thenumber of 30ms pulses that elapse between notes If the time between any two notesislessthan 1 pulse 30ms we assume the second noteis virtu ally simultaneous with the previous note and should therefore not be included in our analysis If the time between notes is greater than 96 pulses 2880ms we assume that the performer has stopped playingmomentarily or isholdingan extremelylongnote n either case wedon twantto includeitin our histogram So thesplit object passes only rhythms that are between 1 and 96 pulsesin length and a histogram of theserhythms is stored in the table An Improviser with a Memory When themetro in thebottom left corner of the Patcher window gets turned on it sends bang mes sages to PassPct thepatch wewrotein Tutorial 29 and 95 of thebang messages get passed on to 134 Tutorial 33 Probability tables thethreetable objects A velocity a pitch and a rhythm are sent out with the choice of each being based on thestored probability distributions the histograms of what
97. point outlet 0 x_click y_click state x_click y_click output the coordinates and state of the clicked point bang draw and refresh display onclick local 1 make function private to prevent triggering from Max ondblclick pass buck to onclick function ondblclick x y ondblclick local 1 make function private to prevent triggering from Max onclick x y See also jsui JavaScript UI object js M ax JavaScript object Icd Draw graphicsin a Patcher window matrixctrl M atrix switch control router M ax message router 292 Tutorial 52 P atcher Storage What is pattr M ax hasawide variety of objects for storing and managing data O bjects such as table funbuff coll umenu and ubumenu all store information that you can set manually or via a mechanism within apatch itself Thepreset object which also stores data is useful for capturing and recalling the states of user interface objects within a patcher giving you the ability to rapidly restore set tings to multiple parts of your patch in onestep SeeT utorial 37 D ata Structures for a review of these objects H owever sometimesaprojectin M ax will requireamoresophisticated statemanagement system Thepattr family of objects pattr pattrhub autopattr and pattrstorage provides the functionality of the preset object and adds amoreextensive set of state management features e Wecan maintain sets of datafrom objects throu
98. precision pitch bend data received from midiin and for formatting extra precision pitch bend messages to be transmitted by midiout xhendoutz 1 pitch bend value pitch bend value pitch bend value pich bend value from Oto 16383 as two bytes from to 16383 as two bytes Because relatively few M IDI instruments have this capability we don t discuss the matter in detail in this Tutorial For more information look under xbendin and xbendout in the M ax Reference M anual Note Off Messages with Release Velocity In M IDI there aretwo ways to express a note off O ne way is as anote off message with a release key up velocity and theother way isas a note on message with a key down velocity of 0 Since most synths arenot sensitive to key up velocities noteout uses the latter method for note offs For synths that aresensitiveto key up velocity however M ax has objects for interpreting and for matting note off messages with release velocity To read more about these objects look under xnotein and xnoteout in the M ax Reference M anual keydown velovity oomotf indicator pitch oor key up velocity 1 or 0 pitch keydown velocity owoft indicator or key up velocity 1 or Oj Summary Themidiin object outputs each byte of M IDI data it receives The midiout object transmits any number it receives in itsinlet You can set these objects to transmit or receive through a specific port by typing in a letter argument a device
99. press the key and when you releaseit A note message with a velocity of 0 indicates a note off The patch on the left is for playing in parallel octaves Every note you play on the synth is received by thenotein object The pitch information issent to a object which adds 12 to thepitch value This of course raises the pitch by 12 semitones 1 octave Weve included extra number box objects so that you can see the pitch values both as numbers and as M IDI note names The velocity and channel information is passed on unchanged and is reunited with the trans posed pitch information in thenoteout object The new note an octavehigher than the one you played and with thesame velocity as you played is sent back out to thesynth by noteout Message Order Although the pitch velocity and channel information appear to come out of notein at the same time thenumbers come out in right to left order channa then velocity then pitch just like any other object Like most objects noteout is triggered by a message received in its left inlet the pitch number The pitch iscombined with whatever velocity and channel values were most recently received in the other inlets and a M IDI message is sent out to the synth Thisconsistency of messageordering outletsalwayssend right to left and objects aretriggered by the left inlet allows different objects such asnotein and noteout to communicate easily Because the velocity and channel numbers come o
100. problem labeled Patch 1 Notethat the order of the object and thepipe object could bereversed thetranspo sition could take place after the delay Let the User Type In a New Delay Time If that exercise was too easy for you try thismoredifficult one 2 In Patch 1 each imitation of the melody comes 3 seconds later than the previousone M akea version of Patch 1 which letsthe user typein anew delay time between imitations This presents two potential problens e What happensif theuser typesin aridiculous delay timesuch as 1000 or 3600000 e What happensif theuser typesin amuch shorter delay time while holding down anote and thenote off gets delayed less than thenote on and is played beforethenote on Theseproblemsrepresentthesort of extremeor unlikely casesyou must takeinto consideration to protect against your program malfunctioning or producing unwanted results Dealing With Potential Problems Theproblem of negative delay times is not serious because the pipe object will set any negative delay timeit receives to 0 The problem of extremely large delay times on the other hand can be moreserious 87 Tutorial 23 Test 4 Imitating a performance If thedelay timeis very long and you areplaying alot of notes the number of notes being stored could causepipe to run out of memory This would cause somenotes to belost and could con ceivably even causethe computer to crash Theway to deal with this problem isto limit thenum
101. right inlet will changethenumber of milliseconds between bang outputs that was initially set by theargument e Try turning the metro objects on and off and watch what is printed in the M ax window 17 Tutorial 4 sng na e Try sending different numbers to the right inlet of metro and notice the changein thespeed with which messages are printed Thespeed can bechanged whilethemetronomeisrunning but the change does not take effect until thenext bang is sent out Because it sends out the message bang metro is a useful object for triggering other objects repeat edly at a specific speed Summary After you typeanameinto an object box you can supply additional information by typing in arguments after the object name Arguments are usually optional but some objects have obligatory arguments If optional arguments are not typed in M ax usually supplies a default value A metro sends out bang messages repeatedly at regular intervals of time until it is stopped The number of milliseconds between bang messages is specified by the argument or by anumber received in theright inlet See Also metro Output bang at regular intervals 18 Tutorial 5 toggle and comment This is a bo Humber box comment Thetoggle object is the box with an X in itin the object palette It functions as an indicator or a switch between two states zero and non zero Toggle e Click onthedifferent messageboxescontainingnumbers and noticewhat
102. that you typed acommaor asemicolon character into an object box If thiserror occurs when reading in apatch it s likethat thefileis damaged 397 Erro rS Explanation oferror messages offscreen buffer couldn t be allocated Insufficient memory available when working with objects in a graphic window patcher unknown script keyword lt keyword gt A keyword argument to the script message to sent to thethispatcher object isnot recognized patcher connect inlet lt number gt out of range Occurs when editing thenameor arguments of an object that has already been created ina patcher and patch cords that used to be connected to the object can no longer beconnected Changing the contents of the object box may changean object s number of inlets or outlets or M ax may beunableto createthe object at all if you typein the wrong thing QT images not supported in 8 bit color mode Windowsonly You aretrying to load aQuickTimeimage but your display resolution is set to 8 bit color depth Changeyour D isplay Settingsto increaseyour Color D epth preferably to 24 or 32 bits read failed Occurswhen afileis read into an object M ax encountered an error readingafileand could not load in thedata Check to makesurethat thefileisin theproper format for the object readingitin rescopy failed to add XXXX N error N Occurs when installing an external object This message especially if you seea lot of them may indicateaproblem with theM ax T emp file
103. the object is another good way of looping Loops Can Create Cyclical Patterns Usingloopsin aprogram isa way of creating periodicities In this patch the parameters of dura tion velocity and pitch all haveadifferent periodicity of recurrence which makesthemusic seem to repeat itself while always changing slightly Actually the duration changes according to a 32 notecycle the velocity changes according to a 118 notecycle and the pitch changes according to a37 notecycle Thus theentire pattern is repeated every 69 856 notes about every 6 hours N ot a melody likely to get stuck in your head Overdrive M ax can get rather busy playing music running metronomes doing mathematical calculations and printing numbers on thescreen Checking Overdrivein the O ptions menu causes M ax to give priority to music making tasks and resultsin moreaccurate musical timing If you hear improper delays on notes or erratic performance try enabling Overdrive Summary Integer numbers can bestored in an int object and sent out later by triggeringint with a bang in its left inlet Numbers with a decimal point can besimilarly stored and recalled with afloat object Theaccum object can storeand recall either an int or afloat value and can add to or multiply the stored value without sending it out 81 Tutorial 21 Storing numbers Floatsareuseful for calculationsthat involvenumbers between 0 and 1 or for any calculation that requires additi
104. the Transposed Fitch Velocity Jeft inlet of Funbuff funbuff Anarrayisan indexed list of numbers Each number in thelist has auniqueindex number or address W e ll call theaddress x and the valuestored at that address y Thefunbuff object stores an array of numbers asx y pairs W hen anumber is received in theright inlet followed by anumber in theleft inlet thenumber in theright inlet y isstored at theaddress specified in theleft inlet x Then when an addressnum ber is received by itself in the left inlet x funbuff sends the corresponding y value out its left out let Thenumbers can also bestored in funbuff as alist an x address and ay value For moreinforma tion look under funbuff in theM ax ReferenceM anual Storing and Recalling Transpositions Thegate object in transposer is used to pass only the pitch of note on messages Beforethe pitch reaches theright inlet of gate thevelocity valuegoesto thecontrol inlet of gate and either opensit or closesit If the velocity is 0 note off the gate will beclosed and thepitch will not get through 102 Tutorial 27 Your object Thenote on pitch goes first to the object to betransposed then to theright inlet of funbuff The untransposed pitch then goes to the left inlet of funbuff so the transposed pitch is stored as they value with the untransposed pitch as the address x Assoon asthex y pair isstored theuntransposed pitch x issent by itself causing thetransposed p
105. the Display menu are saved as part of thetimdinefile Thetimelines clock can be synced to any setclock object in any currently loaded patch Double clickingon thelittleclock icon at thetop of thetimelinewindow displays a pop up menu contain ingthenames of all currently loaded setclock objects 0 00 Untitled 144 44 5 D b gt boil BA v internal 1 irom PEN F us a One Inch Four Seconds Choosing oneof those names from the pop up menu syncs thetimeine to that setclock object Choosing Internal from the pop up menu returns the timeine to following M ax sinternal milli second clock Holding down the Command key on Macintosh or Control key on Windows and clicking on an event sends that event s message to theticmd object s in the action patch allowing you test the effects of the message as you edit the timeline You can play through a segment of thetimeiinein a repeated loop also useful for testing atimelineas you edit it by selecting asegment of timein the timeselection area just under the ruler at the top of thetimeline window then clicking on the Loop button Thereisan additional event editor called a marker which functions similarly to a comment object in apatch Themarker allows you to typein comments and notes about events in thetimeline or moreimportantly to mark a specific point on thetimeline When atimeline object in a patch 372 TI mel Ine Creatinga graphicscoreofM ax messages receivesthemes
106. the entire lcd can be circumscribed by acirclewith a radius of 100 201 Tutorial 43 Graphics in a Patcher Since we know that the dimensions of the Icd are 160x120 we can easily calculate that the center point is at the coordinates 80 60 relativeto the left top corner of the Icd We can then calculate that aperfectly centered circlewith aradiusof 100 would bebounded by asquarewith thecoordi nates 20 40 180 160 180 160 So to createaprogression of diminishingconcentriccircles wewantthecoordinatesofthecircles bounding squareto progress from 20 40 180 160 acircle of radius 100 to 80 60 80 60 a circle of radius 0 asthe counter progresses from 0 to 100 Prepend color Thecalculated coordinates are packed asa list the word PaintOval is prepended to that list and the entire message is sent to Icd vias tolcd and rtolcd hidden in the main patch Thecolor with which thelcd will paint is specified by the word color followed by a number from 0 to 255 If a color number greater than 255 is received it is automatically wrapped around with a modulus operation to keep it in the correct range This modulus feature is taken advantage of in the concentrics patch Thenumbersfrom theleft outlet of counter aremultiplied by thecarry count from itsright outlet thenumber of times the counter has reached its maximum T heresultisthat aseach circleispainted thelcd object spen colorisincremented first by 1 s th
107. the problem persists contact Cycling 74 support ad_directsound can t create directsound object ad_directsound can t create directsoundcapture object ad_ directsound Failed to set cooperative level to priority ad_directsound Failed to create primary buffer ad_ directsound Failed to set format of primary buffer ad_directsound failed to create output DirectSoundBuffer ad_ ds No directsound input or output devices found ad_directsound unable to Play output buffer ad_directsound unable to Start input buffer ad_directsound stopping due to error Windows only Please check that you havethe latest driver update for your audio device Please exit all other audio applications rebootif necessary and try again Also pleasecheck your settings in the DSP Status window to insure appropriate choices are selected for Input Device Output Device Sampling Rate IO V ector Size and Signal V ector Size If the problem persists contact Cycling 74 support ASlOCreateBuffers error W indowsonly A problem was encountered initializingtheASIO device Please check that you have the latest driver updatefrom your audio device manufacturer Please also try different set tings for the device buffer sizes and latency in the control panel for your audio device provided by your device manufacturer Check that another audio application isnot using the audio device Also check that the audio deviceisnot the default audio devicefor W indows Sys
108. theM acintosh portnameisthenameyou assign to the port For example SM createoutport myOtherSynth midi_ dm 4M createoutport myOtherSynth augraph Deleting a DLS Port 45M deleteoutport lt portname gt lt drivername gt wheredrivernameismidi_dm on Windows and augraph on the M acintosh portnameis the name of your choice For example 45M deleteoutport myOtherSynth midi_ dm SM createoutport myOtherSynth augraph Loading a DLS Bank type 1 or 2 45M driver loadbank lt filename gt lt portname gt wherefilenameisthenameof an existing DLS bank file and portnameisthenameof the port that will usethis bank If portnameis omitted all DLS ports will usethe bank On MacOSX the folder Library A udio Sounds Banksis added to the search path when looking for a DLS bank file Loading the DLS Default GM Bank SM driver loadbank 0 lt portname gt Turning Reverb On and Off SM driver reverb 1 0 lt portname gt 405 M essages to M ax ControllingtheM ax application By default reverb is off in both augraph and midi_ dm Setting MIDI Output Latency midi_ dm only 45M driver latency lt time gt lt portname gt wheretimeisavaluein milliseconds and portnameistheport that isset to this value For example the following message would set the latency to 10 milliseconds SM driver latency 10 portname Adding Virtual MIDI Ports Macintosh only By default M ax creates two virtual M IDI ports for both input and output I
109. thesubpatch and enable 1 or any number other than 0 re enables them Bear in mind if you makea patch that automati cally disablesthe M IDI objects in asubpatch that you run the risk of causing stuck noteson the synth if you cause a note off message to be lost e EnableAll Windows Activeso that you can click in themain Patcher window without bring ingit to theforeground Then click on thetogglein the main Patcher window to disable MIDI Thesound stops but theled continues to flash led Theled object isan on off indicator similar to toggle but not identical W hereastoggle passes on anynumberitreceives led outputs only 0 or lindicatingthezero non zero statusof thenumber it receives W hen led receives a bang it flashes and outputs0 You can changethecolor and flash time of an led object by selecting it and choosing Get Info from theO bject menu active W hat makes the clicktrack and stopwatch objects run automatically when their windows are brought to the foreground They arecontrolled by another automatic control object active 180 Tutor al 40 Automaticactions e Toseethehidden objectsin thesubpatches you must open theactual filein which the sub patch is saved ChooseO pen from theFilemenu to open thefilenamed stopwatch e Stop thetimedisplay by clicking on thetoggle in the stopwatch window then unlock thewin dow to seeits hidden objects W hen a window ismadeactive i e brought to the front theactive object
110. to be sent out of the table with the likelihood of get ting anumber based on how frequently it has occurred in the past 136 Tutorial 33 Probability tables togedge is used to detect a change in thezero non zero status of incoming numbers W hen the numbers change from 0 to non zero a bang is sent out its left outlet when the numbers change from non zero to 0 a bang is sent out its right outlet Using route to detect specific selectors the first item in a message messages can be routed to dif ferent destinations See Also histo M akeahistogram of thenumbers received table Store and graphically edit an array of numbers togedge Report achangein zero non zero values Quantile Usingtable for probability distribution Tables Using thetable graphic editing window 137 Tutorial 34 M anagingRaw M IDI Data midiin and midiout M IDI objects such as notein noteout bendin and bendout transmit and receive specific types of M IDI data If you wantto transmit or receiveall types of M IDI dataasindividual bytes including status bytes usemidiin and midiout Themidiin object is useful for examining every incoming M IDI byte Aswewill seein Tutorial 35 itisalso used for recording M IDI from your gear into the sequencer object seq The midiout objectisused for sending any typeof M IDI messageto thesynth including system exclusivemes sages It is also used to send M IDI data that is played back from the seq object In thesimplest
111. to display the result asa Celsius temperature Hints Theformula for converting Fahrenheit to Casius is C F 32 5 9 The isthe multiplication operator You will first want to subtract 32 from the Fahrenheit tem perature then multiply the result by 5 then divide that result by 9 Using Sliders H ereis a second exercise abit more difficult than the first one 2 M akea patch that converts a temperature expressed in degrees Celsius into one expressed in degrees Fahrenheit Limit the temperatures between the freezing point and the boiling point In addition to using number box objects to show the temperatures useslider objects as ther mometers to show the temperatures graphically SincetheO ffset and M ultiplier features of theslider objectscan do addition and multiplication try using these features to do some of thearithmetic work Useas few arithmetic operator objects as possible Hints Theformula for converting C esius to Fahrenheit is F F 9 5 32 You will first wantto multiply theC elsiustemperatureby 9 then dividetheresult by 5 then add 32 to that result In degrees Celsius 0 isthe freezing point and 100 is the boiling point In degrees Fahrenheit 32 is the freezing point and 212 is the boiling point 36 Tu t 0 ri a 1 1 Test 2 Temperature conversion e UsetheM inimum and M aximum features of thenumber boxto limittheinput C elsiustemper ature between 0 and 100 L
112. to get through to the semitone transposer 107 Tutorial 28 Your argument Thevelocity of each played notesets theodds of thegate beingopened then gamble istriggered to open or shut thegate based on thoseodds If the gate isopen thepitch will get through and will betransposed down asemitoneand transmitted back to the synth Let ssay you play anotewith avelocity of 93 Theoddsof thegatebeing open are93 in 128 alittle lessthan 3in 4 so itislikely thatthe noteyou play will betransposed Ifyou play anotewith veloc ity of 3 however theoddsareonly 3in 128 of thegate beingopen so thenotewill probably notbe transposed The result isa probabilistic Thelonius M onk effect of adding lower gracenotesto moreand morepitchesasthevelocity increases N oticethat wedon tneed to usethetransposer object shown in the previous chapter because weare transposing only note on pitches and makenote provides thenote offs e Play with different extreme velocities on your MIDI keyboard and noticethedifferencein likelihood of agracenote being added to what you play In theleft sideofthePatcher window gamble isagain used to makeweightedrandomdecisions with twoslightlydifferentimplementations W henthemetro 1000 object isturned on ittriggersgamble every second and gamble turnsthemetro 60 object on or off it will beturned on approximately 40 of thetime Every 60msthelower gamble will send out either al or a0 with theodds depending again on the v
113. to our patch and bang which printsthecurrent value of x in theM ax window aretalking about the samething when they refer to x Commentouttheline varx 0 66 by placingtwo slashes atthe beginning of it Saveyour script and either recreatethejs object orreopen theT utorial patch Try to run thepatch W ith x undefined our js object reports reference errors when you send it afloat or abang Thisis becauseit istrying to access a variable that has never been initialized W ecould renovethese 256 Tutorial 48 BasicJavaScript errors by setting x to some value within each of our functions but we would then beusing x locally Not only would this prevent us from sharing the value of x between our two functions it would also reinitializex every timewesent afloat into js preventingour objectfrom maintainingx over multiple iterations of the function e Uncommentthe variable declaration for x All should be well again when you save your script Summary Thejs object isa powerful tool that lets you write code using a standard programming language within M ax You define inlets outlets and global variables in the global code section of thescript which resides outside of any specific function M ethods that respond to particular messages floats bang messages etc are written as functions below the global code and are executed in response to therelevant messages from the M ax environment You can usethepost function
114. to play a sequence will be started by the seqcontrol start event a Thisevent in thetimelinesends its message out theoutlet of thenamed ticmd object in thetrack s action patch But whereistheaction patch that will receivethese messages and do things with them T heaction patch isa M ax document on thehard disk like any other patch you have created and saved It can beanywherein M ax sfilesearch path In this case it sin thesame folder as the tutorial patch the M ax Tutorial folder Thereisalso a special folder called tiA ction in the M ax folder whereyou can keep action patches that thetimelinewill display in its Track pop up menu In any case thetime linefindsthefileand loadsitinto memory to beused by asingletrack of events You can view and even edit the action patch from within thetimeline Actions and ticmd e To seetheaction patch double click on thesmall M ax icon at theleft end of track 1 An action patch contains oneor moreticmd objects for receiving messages from thetimeline Each ticmd object hasaname its first argument and specifiesthe typeof message s it expects to receive Thenameof each ticmd object in the action will appear asa possible eventin the timeline track For example just by looking at portionsA and B of theaction wecan seethat thetimeine 184 Tutorial 4 TimelineofM ax messages may contain events named pitch volume and bend which would send int values to their respective ticmd objects
115. to the inlet of another A mes sage box contains any message you type into it W hen you click on a message box it sends its mes sage out the outlet A print object prints in the M ax window whatever message it receives in its inlet See Also message Send any message print Print any messagein the M ax window Objects Creating anew object in the Patcher window 12 Tutorial 2 ThebangM essage The bang Message Program 1 Program 2 Program 3 3 e This program is actually three separate printing programs Click on the button iconsin each program and notice what gets printed in the M ax window Thefirst thingto observeisthat two of theprint objects havenames x and y Sincetherecan beany number of print objectsin a Patcher window you will often want to make it clear which oneis actually printing a message You do this by putting a name after the word print in the box When theres no name the message is preceded by print asin Program 1 W hen thereisaname it pre cedes the message asin Programs 2 and 3 Thesecond important new thingin this window isthe button object It appears as a separate iten in the palette and is really very much like a message box that contains the message bang Button You see bang isa magic word in M ax It s a special message that means Do it which causes an object to do whatever it s supposed to do For example a message box sends out the message it contains in response to abang or amou
116. up asdifferent colorsin thegraphic editor window and thetrack number can beused asa criterion for selectively muting notes in detonate or selectively modifying then on playback The 7th and 8th inletsarefor any additional information you may want to record aspart of anote event For example each note could be assigned its own vibrato depth and pan position when recording and those data would be sent out when the notes are played back Extra Ho 1 Extra Ho z etlout a 1 etlout a 10 Additional data may be associated with each note event The detonate Editor Window D ouble clicking on thedetonate object in a locked Patcher opens a graphic editor window for viewing and modifying its contents The recorded notes are shown in theeditor window in a piano roll like view Timeis shown on thex axis pitch ison they axis the duration of notes is 377 Detonate GraphiceditingofaM IDI sequence proportional to their length and thevelocity of each noteappears asanumber on it Each track of a multi track fileis shown in a different color editing tools cursor location note parameters Untitled Tritch 0 W Vel64 t 53 Time 0 gt Dur 200 Chant Y Tracki Y 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 i a aa a ea et ya ne ai aaa oaa 84 620 g85 ogi my 67 icon ee iz 190 66 Ba z 1102 i54 571 153 52 64 SS gezos sas DECi iS i45 545054 i52 li6olsaeo sa i62 i59 1545157 i46 i55 I5 E
117. used to supply thenameof an object itself but can be used as an argument anywhereinside your object 352 Arguments and changeableargumentsto objects In the following example arguments typed into the limitNotes object boxes supply values to the objects insidelimitNotes W hen thehslider is moved onelimitNotes object plays a note every 300 milliseconds on M IDI channel 5 and the other plays anoteevery 200mson M IDI channel 7 The contents of the LimitHotes object look lt like this speedlim 1 makenote 127 1 To Tiatecut a 2 TheseareM ax objects When limithMotes is used as an object in another patch 1 ic replaced by the first argument and 2 is replaced by the 2nd argument limitHotes 300 5 limitHotes 200 7 limitNotes isa patch saved asa document A pound sign and a number can even be part of asymbol argument providing variationsona name provided thatthechangeableargumentisthefirst part ofthesymbol In theexample below the 1 part of the changeable argument inside scale is replaced by the argument in the patch that uses scale Thescale objects will each use a different pre saved table file producing different results The contents of the seale object look like this The argument is supplied in the pateh that uses seale table Gminorpitches aud the effeet is as if there were two seale objects that look like this Thesametechnique can beuse
118. valuesin thetable in the ways discussed or by drawingin a curve yourself Play a melody on your M IDI keyboard with longnotesand avariety of velocitiesin order to hear the different pitch bend speeds Summary Thetable object stores and recallsan indexed array of numbers You can graphically view and edit the stored numbers by double clicking on thetable object Thevaluesin atable are normally discarded when the Patcher window is closed but you can save them as part of the patch by selecting thetable choosing Get Info from the O bject menu and checking SavewithP atcher You can also saveatable as aseparatefile and can then useit in apatch by creating atable object and typing in the filenameas an argument To open anew Table window choose Table from the N ew menu or create a new table object in a Patcher window You can also just type the word table followed by alist of numbers into a Text window and saveit asa file To store values in atable object without opening its graphic editing window send thevaluein the right inlet then send the address where you want to store it into the left inlet Alternatively you can send the address and value in the left inlet together asa list A set message changes certain values in thetable and a size message changes thenumber of values thetable can hold 131 Tutorial 32 Thetable object Theuzi object sends out a specific number of bang messages as fast as possible in a single tick of M ax
119. we ve used in our JavaScript tutorials wedon tintend our myt ask function to betriggered by aM ax message from outsidethejs object By default any declared function in ajs object will respond to an appropriately named messagefrom theM ax environ ment Sincewedon twantmytask triggerable by amytask messagefrom our patcher weplace the following line of code after the function ends mytask local 1 This statement makesmyt ask local to thejs environment and inaccessible from outside Our task function accomplishes two things it sends out an integer to M ax triggeringaM IDI note and incrementsitsown timinginterval so that thenext run of myt ask will happen alit tlebit sooner Outside of thetask function wecan change our timing interval by setting theinter val property to the task eg tsk interval 250 Properties and methods of aT ask object can be modified within the task function by referring to the T ask as the calles e g arguments callee task interval 250 adjust timing of task to 250 arguments callee task cancel have the task cancel itself W eusethis reflexive capability to change our T ask object s timing interval from within thetask function W hen thetiming interval decreases to a suitably low value 5 millisecondsin our case wealso usethis feature to have our task function cancel theT ask that called it in the first place 276 Tasks A rgumentsand Tutor al 50 Global Objectsin JavaScrip
120. when theassoci ated graphics window becomes the active window or if All Windows Activeis enabled in the Options menu it polls all thetime The local coordinates of the mousein the graphics window aresent outthesecond horizontal and third vertical outlets of mousestate T his patch drawsan oval centered at the mouse location which changes color each timethemouseis moved Causes mowsestate to report the mouse 11 Displ position when the Display window is active mousestate Color index cycles from O bo 255 counter B55 graphic Display oval Display Any picturethat is saved asa PICT filecan bedisplayed in agraphics window with the pict object ThePICT isdisplayed in the graphics window at full size and the location of its upper left corner isdetermined by thenumbers received in the second and third inlets of the pict object So in most cases you ll want thearea of your PICT to beonly large enough to contain theimage you want to display with no extraneous whitespace around it Its placementin the window and its sprite priority can becontrolled similarly to the geometric shapes described above QuickTime Movies If you haveQ uickT imeinstalled on your computer you can play Q uickT imemoviesin M ax using theobjectsmovie and imovie Thetwo objects function very similarly Themovie object displays themoviein awindow of itsown and imovie is auser interface object which displays the moviein abox insideaPatcher window
121. will need to include the resource filein the script for making the collective Please refer to Apples D eveloper documentation for more infor 333 Groupingfilestocreate Col ect Ives a single application mation on howto createyour plist and icon resource Information can befound atthefollowing URL http developer apple com technotes tn tn2013 html If someof thesupportingfiles used by M ax M SP objectsin your patch will not beincluded in the collectiveitself check theSearch for FilesN otin theA pplication sC ollectiveoption Itischecked by default Unchecking this option can be useful for ensuring that you have included all necessary files in the collective that you are making into astandaloneapplication If you create your applica tion with this option turned off your application will not look outsidethecollectivefor any filesit cannot find such as missing sequences or coll files that your application attempts to load So you can make your application with Search for Files Not in theA pplication s Collective unchecked and then run it to seeif it works properly If your application isunableto find a file that it needs you will get an error messageto that effect and you will knowthat you haveto rebuild your standalone application In some cases however you may want your application to look for a file outside of the collective For example you may want it to look for aM IDI filethat can besupplied by theuser of your appli
122. you build acollective using that patch M ax includes in the collective any external objects or subpatches that the top level patch requires to operate You may also need to includesomeother datafiles explicitly data files used by objects such ascoll seq etc to completethecollective You will then haveacompleteworking program that originally consisted of many diverse files saved in asinglefile 326 Groupingfilestocreate Col ect Ives a single application Onceyou have saved a collective you can open it as you would any other M ax document by choosing the O pen command from the File menu or by double clicking on the collective in the Finder on M acintosh or theW indows Browser on Windows You cannot load itinto another patch asasubpatch by typingitsnameinto an object box nor can you load it into a bpatcher If you make changes to any patch that is being used as a subpatch in a collective those changes will not be updated in the collective the subpatch in the collective remains just as it was at the moment you saved the collective Steps for Building a Collective 1 With your top level patch in the foreground choose Build Collective Application from the Filemenu You will bepresented with ascript window in which you createalist of thingsM ax must do to create the collective M ax has already made the first entry in its script open thispatcher instructing itself to load in your top level patch A ny extern
123. 0 750 In theleft part of the Patcher window note on pitch and velocity values from your M IDI key board are packed in alist along with the number 750 and the list of pitch velocity delay is sent to the pipe Every note from the keyboard will be delayed 750ms even if the delay time of the pipe is changed by someother part of the patch becausethedelay timeissentin thesamelist asthenote on data swap Theswap object reverses the sequential order of numbers it receives It is triggered by a number in its left inlet just like other objects but it sends that number out its right outlet first then sendsthe number that was received earlier in therright inlet out its left outlet 116 Tutorial 30 Number groups In theexample patch swap reverses the order of thefirst two list items received from unpack and uses thefirst number in thelist 40 as a velocity and the second number 59 as a pitch It would not be sufficient just to cross the patch cords from unpack because the number 59 would arriveat the left inlet of pipe and trigger it beforethe number 40 got there This patch is not equivalent to the one shown above W hen swap receivesabang in itsleftinletit sendsout thesamenumbersagain T hetwo numbersto be swapped can also be received in the left inlet as alist In fact the unpack object in this patch is not strictly necessary becauseswap would understand thelist and swap thefirst two items but we included unpack to make th
124. 0 and play your sequenceagain T histimeall tracksstart at time0 even though you started recording data on onetrack before the others When you send mtr a mute message while itis playing it continues to play its stored sequence but it suppresses the actual output Use the unmute message to restore output Individual tracks can be muted and unmuted by followingthemute or unmutemessage with atrack number argument or by sending the messages into a specific track s inlet You can step through the messages stored in mtr by sending repeated next messages to the control inlet W hen mtr receivesnext it sendsoutthenext messagestored in each track It also sends atwo item list out the leftmost outlet once for each track reporting the track number and the duration the time between that message and the following onein thetrack e Check All Windows Activein theO ptions menu and bring the M ax window to the front so you can see what gets printed in it Then click on thenext message T he next value stored in each track issent out thetrack outlets and alist for each track consisting of thetrack number and theduration between messages is sent out the left outlet T herewind message is used in conjunction with next It sets thepointer back to thebeginningof the sequence so that the message next will start at the beginning again 157 Tutorial 36 M ulti track sequencing Summary The mtr object records and plays back up to 32 tracks of any mess
125. 08 00 00 12 00 to Y hr 1 E PrintThreeT printsymbol start d l meri At Select Event in Track 1 pay YZ You can choose the format in which you want timeto be displayed by clicking on the Display but ton and choosing Time Units from the pop up menu You can chooseto display timein millisec onds rather than the minutes seconds and frames for film or video shown in this example 365 TI mel Ine Creatinga graphicscoreofM ax messages Once you have completed the three steps of creating a timeline creating an action creating a timeline and creating timeline events you can play the timeline using the tape recorder like controls in the upper left corner of the timeline window The edetonate Editor An event editor called edetonate which works just likethe graphic editor window of a detonate object can beused in a timeline for sending list messages to ticmd Once you have placed itin a timelinetrack you can double click on it to open its graphic note event editing window For details of this graphic editor window see the Detonate Topic Because of the edetonate object s orientation as a sequencer of note events it is especially well suited to sending list messages that will be used as note events in the action patch W hen thetime lineis played edetonate sends out the note on events that you have drawn into it and also sends out corresponding note off messages after the amount of time specified by each
126. 3 N otethatsincenothingever getssent into thesecond inlet of pipe thenumber comingoutthesec ond outlet will always be 0 T hese delayed numbers go to noteout and provide the note off mes sage T his is a convenient method of providing note offs by specifying a note duration and using that number to delay a second note message with a velocity of 0 It s similar to using amakenote object but allows you to delay the channel numbe as well which makenote does not do Playing the timeline Now that you understand what the different events in the timelinedo you havea pretty good idea what will happen when you play it In the first four seconds the notes in thepitch table will be played and the volumewill be adjusted by the volume graph From time 4000 to 8000 the tutorial41 scsequencewill beplayed repeatedly until youmovethemod wheel of your synth T hen at time 8002 a chord will be played pitchbend messages will be sent out from the bend table and the QuickTime moviewill be played Thetimefrom 8001 to 10000 will repeat until you movethe mod wheel back to 0 Track isg a ee 1 RG terial action e UsetheWindows menu to bring the QuickTime movie window to the foreground You can drag it to the upper right corner of thescreen so that you can still seethe Patcher window Check theAll Windows Active command in theO ptions menu so that you can leave the movie window in the foreground and still click on objects in the Patcher wind
127. 47 DH pich bend range midiont a The next byte specifies the setting for the pitch bend range how many semitones up and down we can bend the pitch T his is the value we want to be able to change so we ve made this bytea changeable argument in sxformat The pitch bend range value must be from 0 to 12 semitones so we veincluded a 13 calculation to limit incoming numbers between 0 and 12 is 11 13 That s the end of the data portion of the message so the ending byte 247 comes next W hen anumber isreceived in theinlet theentiremessageissent out onenumber atatime using theincoming number as the pitch bend range value e If you haveaYamaha DX 7 you can changethe pitch bend range by dragging on thenumber box If you don t your synth will ignore this message Extra Precision Pitch Bend Data Most M IDI keyboards transmit and receive 128 different pitch bend values and M ax sM IDI objects do the same H owever aM IDI pitch bend message actually contains another byte for additional precision in expressing the pitch bend amount and some synthesizers take advantage of this capability If a synth does not havethe extra precision capability it always transmits a value of O in the extra precision byte and ignores the extra byte when it is receiving pitch bend mes Sages 144 Tutorial 34 Managing raw M IDI data For M IDI keyboardsthat do have the extra precision capability M ax has objects for interpreting incoming extra
128. 64 1 144 60 64 noteout miarowe In the above example the message box on the left sends out a single message 60 64 1 as alist The message box on theright sends out three separate messages first 144 then 60 then 64 A semicolon in a message box is used to send messages to remote receive objects W hen a semi colon ispresentin amessage box thefirst item after thesemicolon isasymbol indicatingthename of a receive object and the rest of the message or up to the next semicolon is sent to all receive objects with that name rather than out the message box s outlet 37 oneplace 96 r anctherplace r anotherplace anotherplace barng n pae metro S00 fl sy A Asin an object box the backslash in amessage negates the special characteristics of thecharac ter itimmediately precedes Thenumber letter combination Ox zero x allowsnumbers to betyped into object and message boxesin hexadecimal form useful for people who think of M IDI bytesin hex For example the message 0x9F 0x3C 0x40 is equivalent to the message 159 60 64 See Also Arguments and changeable arguments to objects 356 Quantile U singa Tablefor Probability Distribution The quantile message Oneof the messages understood by thetable object isthe word quantile followed by a number If you haveread the description of this message under table you may havewondered what utility this complicated calculation might have This section providessome
129. 72 60 4f 26 27 28 29 30 31 32 7 resize view of notes hide show tracks To select a specific note for editing choose the selection tool from the palette in the upper left cor ner ofthewindow then click on or dragaround thenoteyou wantto edit You can select mul tiple notes by dragging around them or by Shift clicking on them oneata time You can changethe starting time pitch or duration of the selected notes simply by dragging on oneof them with the selection tool or the tweak tool for finer resolution dragging The cursor will change depending on where you click on thenote e Ifyou click on theleft side of thenoteyou can drag horizontally to changethestarting timeof the selected note s e Ifyou click on theright side of thenote you can drag horizontally to change the duration s e Ifyou click in the middleof a note you can drag vertically to transpose the pitch es 4467 ETE ae change starttime change duration change piteh 378 Detonate GraphiceditingofaM IDI sequence You can also change the value of any of the parameters of the selected notes by dragging on the number box objects at the top of the window Ifyou wantto add new notesto thescore you can simply draw them in with thepencil tool W here you draw determinesthestarttime pitch and duration of thenote all other parameters aredeter mined by the values shown at the top of the window at the time you draw the note
130. 9 Test 5 Probability object How do wetranslate this into objects poe pich from kzlider x The pitch from kslider is sent into the formula and the percentage is sent to PassPct Your patch might look something like this FasePot 10 Use PassPct to make Random Choices Let s add one more element to the exercise 3 Add another PassPct object that receives bang messages from the same metro but triggers ran dom octavetranspositions of the selected pitch M ake the percentage of this PassPct object decrease from 95 to 5 as the selected pitch increases This part of the exercise presents two new problems how to create random octave transpositions of a pitch and how to express an inverse linear relationship Try to find a solution to these prob lems yourself before reading further Random Octave Transpositions of the Pitch To makearandom octavetransposition of anote you need to calculate the pitch class of thenote C C D etc then add 12 to that pitch class some random number of times You will want to 112 Tutorial 29 Test 5 Probability object limit therandom numbers so that they keep the transpositions within the range of the keyboard Thesolution might look something likethis hang from FassPot Pitch from kslider choose a random ae a tae get the piteh class 0 to 11 Place the piteh in the lowest octave of the keyboard add 12 to the piteh a random number of times send the transp
131. 92 bug debugging 386 389 error message 393 button 13 as a debugging tool 389 button appearance 222 C C function 173 C programming language 170 C74 path 310 capture 139 debugging with 388 change 54 changeable argument 92 351 355 characters special 225 355 checkpreempt 401 chord playing parallel chords 47 storing 160 transmitting 92 115 chord playing patch 160 clean 401 clicktrack patch 181 clocker 120 closebang 179 coll 159 349 editing the contents of 160 collective 220 326 color of a sprite 196 color of an object 69 combining comparisons 53 comma in a mathematical function 355 in a message box 92 356 Index command from the Mac keyboard 72 Command key bindings 225 comment 20 clicking on 69 commenting 392 comparison 51 using to make decisions 52 60 64 computational efficiency 341 conditional if then else statement 171 constant value 342 Continue 391 control change ctlin 57 ctlout 57 controller numbers 57 conversion of message type 341 correctness checking 386 389 counter 120 344 ctlin 57 ctlout 57 cyclical pattern creating 81 D data structure 159 348 coll 349 Data structures 159 debug 401 debugging 386 389 decimal number 15 decrementing 80 344 default scaling 380 default value 18 del 83 delay 83 Delay lines 83 delaying a bang 83 numbers 83 delta time 376 Designing the user interface 220 detonate 210 376 in a timeline 366 383 device list from OMS 226 dial 48 dialog e
132. AV are specified so that different applications can read and writesound data The fileformat tells the application whereto expect thesound data the sam plingrate and other information Just about every application you usewill storeinformation in oneor morefiletypes or formats File extensions are associated with filetypes by using the fileformat message to max Thestandard set of associations which you can modify if you want isfound in a file called max fileformats txt in theinit folder insidetheCycling 74 folder A second filefor audio filetypes audio filefor mats txt isalso present if M SP is installed These files consists of a series of messages that take the following form max fileformat lt extension gt lt filetype gt For example theentry max fileformat txt TEXT tells M ax that files ending with txt aretext files These four character filetype codes were originally used as M ac OS typeinformation but they are used internally by M ax on all platforms to specify file formats H ereisalist of the standard associations between filename extensions and filetypes Extension FileT ype Description spat maxb TEXT Maxpatchfile in either M ax binary or text format file help maxb TEXT Maxhelp file in either M ax binary or text format file txt TEXT Generic text file M ax patcher in text form or other M ax text file mxb maxb Cross platform M ax binary patcher format mxt TEXT Cross platform M ax text format patcher file mxf mx
133. Alternatively you could just typethe first few letters of theword print until it is selected in thelist Note If you want to typein thenameof an object without usingtheN ew O bject List typethe D dete Backspace key or click anywhere outside the N ew Object List and it will go away You can also hold down theO ption key on M acintosh or theA It key on Windowsas you placethe object box in the window if you want to temporarily toggle the New Object List option on or off You now havean object box with the word print in it Type the Enter key on M acintosh or the Shift and Enter keys on Windows or click anywhere else in the window outside that object box and aprint object is created with an inlet at the top Print Next click on the message box icon in the palette and click just above your print object to place anew message object in the window Type Good bye into your message object Good bye Toconnectthemessage objectto theprint object dragfrom the outlet of themessage object to any place insidethe print object 11 Tutorial 1 ayn Halo e Position the cursor on the outlet of your message box W hen thecursor is over an outlet the outlet expands Click on the expanded outlet and drag until the cursor isinside your print object and you see the inlet of the print object expand Then release the mouse button This will create a patch cord connection between the two objects Note If you are unable to connect a pat
134. Changing the View in the Editor Window You can zoom in and out on the view of the score by clicking on the resizing arrows at the bottom left corner of the window reduce view of x axis enlarge view of x axis A a w reduce view of y axis enlarge view of y axis To zoom in on a particular spot in the score choose the zoom tool and click on the spot you want to enlarge O ption click on Macintosh or Alt click on Windows on the spot to zoom back out Although the depiction of the note parameters is normally as described in this chapter you can changethedepiction by reassigning the way each parameter isshown W hen you click on theicon to the left of a parameter name the icon becomes a pop up menu letting you choose how you would like that parameter to be depicted So for example rather than showing velocity as a num ber on thenote you could chooseto show M IDI channel instead tur 700 Bl chan 1 Track 1 in Display on Y Axis Display as Number Display as Length Edit Parameter 3 r Icon becomesa pop up menu for changingthedisplay of a given parameter 379 Detonate GraphiceditingofaM IDI sequence Asa matter of fact by choosing Edit Parameter from the pop up menu you can change many other aspects of how the parameter is displayed Edit Parameter Parameter Name Time Display Mode maxis ak Minimum al ue Display Options Maximum Value 999999 Default Yalue AHL Graph Interval
135. Holding down the Shift and Command keyson M acintosh or Shiftand Control keyson W indowswhiledragging on abpatcher movesthe subpatch around within it allowing you to offsetthesubpatch sposition Theamountof theoffset shows up in theAssistance portion of the main Patcher window e Lock the Patcher window and hold down the Shift and Command keys on M acintosh or the Alt and Control keys on Windows as you drag on the button to moveit around within the bpatcher Notice the coordinate information shown in theAssistance area You can even make the subpatch inside the bpatcher reposition itself by sending an offset message to athispatcher objectinsidethesubpatch An offset messageconsists of the word offset followed by two numbers representing the number of pixels to offset the subpatch horizontally and vertically So by carefully designing the patch you want to useas abpatcher subpatch by carefully sizing your bpatcher object and by sending the proper offset messages to athispatcher object in the bpatcher Subpatch you can cause an entirely different image to show through the visible portion of the bpatcher In thefollowing example different objects in the subpatch shown on the left can be windowed insidea carefully sized bpatcher by sending the correct offset messages as shown on the right 5 69 63 65 118 68 thispatcher Volume Panning a pod Thecontentsofthissubpatch Can bewindowed threedifferentwaysinsidea Single b
136. I No Min LI No Max LJ Bold Draw Triangle Options O Output Only on Mouse Up Ol Can t Change _ Transparent Display Style Decimal ak Mumber Colors Set theSlider Rangeof theslider which isdepictingyour Celsius thermometer to 101 so that it will display values from 0 to 100 You can usetheM ultiplier feature of this slider to multiply the Celsius temperature by 9 Slider Range Offset jo Multiplier fs 37 Tu t 0 ri a 1 1 Test 2 Temperature conversion e Usea object to dividetheC esius temperature by 5 Then usethe Offset feature of the slider that s depicting your Fahrenheit thermometer to add 32 and you will havethe result Set the Slider Range to 181 so that it will range from 32 to 212 Slider Range Offset Multiplier Revert ii Your objects will be connected something like this multiplication by 9 is done in this lider Scroll the Patcher window to theright to see solutions to these two exercises Although tempera ture conversion isnot avery useful musical function these exercises exemplify how to solve a mathematical problen using operator objects In thesubsequent chapters you will usethese operators to manipulate M DI data Summary Arithmetic operators can belinked together to form acomplete mathematical expression The order in which the objects are linked is important for performing each operation in the proper order 38 Tu t 0 ri a 1 1 Test 2 T
137. I notemessages and when anotearrives notein outputs the key number the velocity and the channel number Similarly the bendin object looks only for incoming pitch bend messages and sends out the amount of pitch bend and the channa number receive MIDI mte messages raise the piteh by iz semitones 1 octave list in lett inlet of transposed pitch moteout also works trameInit WIDI note messages left inlet triggers note with mosh recently received velocity 40 Tutorial 1 Sending and receiving MIDI notes The notein and noteout Objects For the moment we will concern ourselves only with M IDI notedata receiving information about notes played on thesynth and transmitting messages to play notes on the synth e Play afew notes on your synth You should see the note data in the number box objects If you don t see anything happen re check your connections For the purposeof this Tutorial your M IDI interface should be connected to your computer If you have not already doneso you should usethe M IDI Setup dialog to assign porta with a channel offset of 0 to the input and output devices you want to use for the Tutorial Theletter argument to notein indicates the port in which it receives M IDI note messages If no argument is present it receives from all ports e Play afew notes and hold the keys down for a moment before releasing them You can see that a message is sent for each note both when you
138. In thischapter weoffer someadvice and afew tools for preventing or eradicating bugsin your M ax patches Planning Your Program Oneof the best aspects of M ax is the fact that you can improvise a program patching objects together and tryingthingsout without a clear idea of what you want theresultsto be W hilethisis a perfectly valid method of working and can result in some interesting new ideas it also often leads to the infamous M ax spaghetti patch Patch cord spaghetti is often indicativeofa lack of planning This patch works just about as well as a neatly organized patch but it s certainly more difficult to analyze what s going on or find bugsin such a patch If you want to ensurethat your patch works correctly it s best to plan it out conceptually before you begin to implenent it in M ax Even with careful planning you may think you know exactly what you want your program to do begin to writea patch in M ax and then discover that the problem was more complex than you at firstthought For example you might discover that your plan isappropriatefor somecasesbutnot for others Thefollowing exampleisa problematic patch for modifyingthevelocity of incoming M IDI notes and sending then back out on a different port Superficially it may seem like a rea 386 Deb U gg ng Tipsfor debugging patches sonable patch but it will malfunction in many instances A nalyze its problems and see if you can think of good solutions
139. L 35 SOqa MG TON OW dicho tase aay shunts E henner arene Ue wieder 147 Tutorial 36 M ulti track Sequencing yt aa c fc ca car ey nend ees eae an whevaa etna eds 155 Tutorial 37 Data SRW CE CS chests ct seta te ates ate ths aed a wna hectic any winston taal tes 159 Tutorial 38expr ANGI ene sesii daar naan ce tau a hee ry sah Meta eb heer bET E Aa 170 T torial 39 M OSA Control a irai courtesy chee iath ta Piette A A TAE 175 Tutorial 40 Automatic A dions ssassnnaeraerrae ranana 179 Tutorial 41 Timeline of M ax M G5SaQ6S cece cect eee eect eee teste tneneteeeenaes 183 Tutorial AZ Graphi ee oeda dell aha Ndi tid Nebel a a Moen sated Mla 194 Tutorial 43 Graphicsin a Patcher n tence caetcua netomat paren Nein eae ee goa eal Nees 200 Tutorial 44 Sequencing with detonate cc cece eee e cee eee eee teen teen een eeenaes 210 Tutorial 45 Designing the User Interface 10 ccc cece cece eet e teense eeeeeeaeeaes 220 Tutorial 46 Basic SC PUNO sis cedints wer as teanceian kiCaceis homers RY RSOuee Bie steels Pe enate waa 228 Tutorial 47 Advanced Scripting st edicctenor wliteh cortciitintuiet dake Retatieapetahane nee ated nae 240 T t rial48 Bade lavas Pts ce ae e a E A EEA E ian 248 Tutorial 49 Scripting and Custom Methodsin JavaScript cc cece esse eect eee eens 259 Tutorial 50 Tasks Arguments and Global Objectsin JavaScript ccc eee eee e eens 272 Tutorial 51 Designing User Interfacesin JavaScript
140. Theplayed pitches will rangefrom 36to 96 and thehorizontal rangeof pixelsisfrom Oto 512 We first subtract 36 from the pitch to bring it into the range 0 to 60 T hen if we offset each key of the ascending scale by 8 pixels to theright and make each rectangle 32 pixels wide the notes of the keyboard will precisely span the graphics window rig gogr coor Thereare256 available colors available to the shape drawing objects numbered 0 to 255 Using the modulo operator we can determine the pitch class as a number from Oto 11 Weadd 1 to each pitch classvalue to putitin therange1to 12 then weassign each pitch classa color by multi plying it by 20 to distributeit in the range 20 to 240 Finally we subtract 1 from it since the odd 196 Tutorial 42 Graphics numbered colors show up as black on monochrome monitors If we don t do that they will all be drawn in white on a monochrome monitor and will beinvisible Because the pitch and velocity values come out of poly before the voice number the rectangle characteristics can all be calculated and stored in pack before the voicenumber triggers the mes sage and sends it to route to pass it to the correct rect e ClosetheEightR ectangles window and open thegraphics window again then play somenotes to verify that the rectangles behave as described Animating Pictures and Shapes To give theillusion that a sprite is moving we simply draw it several different places in rapid suc
141. Thestandard QuickTimecontrols are availablein the form of a separate user interface object called playbar the outlet of which isto be connected to the inlet of a movie or imovie object You 323 Overview of graphics Graphics windows and objects can also control movie and imovie directly with messages such as start and stop you can changeits speed with therate message you can jump to any framein themovieimmediately simply by spec ifyingitslocation in themovie and you can shuttle back and forth with the prev and next messages rate 1 64 U singthepitchbend wheel to shuttle back Usinghslider to control thespeed of themovie and forth through the movie Graphics in a Patcher Window Thereareanumber of waysto design thegraphic appearanceof aPatcher window You can copy a picturein PICT format from another application and placeitin your Patcher by choosing the PastePicturecommand from theEdit menu in M ax You can also usethefpic object to load a sep arate PICT fileinto your patch U sing pictures in combination with thetransparent button object ubutton and thevarious graphical user interface objects provided you can giveyour user interfaceany appearanceyou wish You can even changetheappearanceof apatcher automatically whileit s running by sending an offset message to abpatcher object thus displaying a different por tion of its enbedded patch Theimovie and Icd objects allow you to build animation and drawing capabiliti
142. a value from Punbutt sel 035 6 11 14 17 20 22 24 sel 30 33 36 39 42 44 pich indexes to he passed on to Funbutt Contentsofthepatcher silencersubpatch Notice that sel objects can be linked together to select more than 10 numbers since the numbers that are not matched by the first sel object are passed out the rightmost outlet to the second sel object Theremaining index numbers are sent as addresses to funbuff which sends out an appropriate accompanying pitch value To makefunbuff respond properly we simply madea list of addresses and values and saved the list as a funbuff file named bourr e fb e Ifyou want to s the contents of funbuff choose O pen As Text from theFilemenu and open the file named bourr e fb W ecould havealso stored theaccompaniment pitchesin atable or in acoll object which will be explained in Tutorial 37 So far we have made the accompanist play somenotes that are simultaneous with the melody notes and we ve made the accompanist rest on melody notes that are unaccompanied but how about when the accompanist hasto play notes on its own in between melody notes This occurs twicein thescore onceattheend of each phrase 152 Tutorial 35 seq and follow To help the accompanist play notes on its own the patcher addnotes object measures the tempo of the performance and plays notes with a delay time based on its perception of the performer s tempo E pich indexes from Follow sel 24
143. aces U sing picture based user interface objects Sincethe control can havetwo values and the mouse button can either beidleor clicked the pictctrl object stoggle modehas four states W e might draw a chart to represent these four states Mouse Button Idle Clicked Ea Clicked Control 0 Value Clicked 1 Each of thefour quadrants in the chart represents one state of the control a combination of its current value and the position of themouse button Thischart is arranged thesameas the layout required for picturefiles for the toggle modeof the pictctrl object The picture is divided into four equal sized quadrants each of which contains the image displayed for the corresponding state of the control H ere san example picture which implements a toggle mode pictctrl that resembles the pushbut tons with embedded lights found on somehardware synthesizers Theimagesin theleft column will beused to draw thecontrol when itisidle and theimages on the right will be used when theuser is clicking the control with the mouse Thetop row of images will beused when thecontrol s valueis zero and the lower row will be used when thecontrol s valueis one So for example the upper right image will be displayed when the control s valueis zero and theuser is clicking it This pictureisin thefileLED button pctin the picts folder To useitin acontrol add anew pictctrl to your M ax patcher and set its modeto T oggle by clicking the radi
144. ach time a note of thescoreis played an index number is sent out that triggers some sort of reaction e Click on the follow 0 messageto start the score follower at the beginning of the score Play the right hand part of the bourr e excerpt and Patch 2 will play the left hand part alongwith you e f you veforgotten how the melody goes read the bourr e sc sequenceinto theseg object in Patch 1 and listen to it e Click on follow 0 again and play the melody with an occasional wrong note or skipped note If you don t mess up too much follow manages to account for your mistakes and continues fol lowing the score e Trythemelody again with ritardsattheend of thephrases T heextra notes thattheaccompa nist plays match your tempo Analysis of Patch 2 Sometimeswewantthelefthand to play anotealongwith theright hand other timeswewantthe left hand to do nothing new when theright hand is playing the second of a pair of aghth notes and the left hand is just holding a quarter note and occasionally we want the left hand to play a notein between notes played by the right hand How do weaccomplish each reaction 151 Tutorial 35 seq and follow Theindex numbers are first sent to a subpatch called patcher silencer This subpatch simply filters out the index numbers which we don t want to trigger a note of the accompaniment T hesel Objects select those index numbers and pass the rest on pieh indexes to be filtered owt so they dont trigger
145. ack lt variable name gt Toreally deactivate those number boxes named somewhere nowhere and anywhere we ve also added scripting messages that enable and disable object response to mouse clicks script respondtoclick lt variable name gt script ignoreclick lt variable name gt Summary You can usescripting to replace objects in apatcher and re establish their previous connections Oneimportant step in doing this is that all objects involved should benamed prior to executing thescript messages W hen performing scripting operations such as replacing an object placing all thescript messages insideamessage box can becomeunwieldy and placing script messages as lines in acoll object isa good solution 247 Tutorial 48 Basic avaScript What is avaScript JavaScript is an object oriented scripting language originally developed to facilitate the use of embedded softwarein websites TheM ax js object allows you to use avaScript as a language within the M ax environment writing program codefor your own object without the need for external developer tools compilers debuggers etc In this Tutorial we ll show a simple example of how you would usethejs object to createan objectin JavaScriptto respond to simplenumerical input from M ax and return a number to the patcher Thejs object gives M ax users the powerful ability to write an object using an embedded program ming language directly within M ax In anutshell it allows usto
146. ack name Thetrack nameis initially set to bethesameasthenameofthetrack saction but you can changethetrack nameto something else just by clicking on thenameand editing it without affecting the action assigned to that track 44 44 ol DB be ph F oo 00 00 i 00 04 15 Createa Track Display 00 00 00 OO0400 oooeoO o E Pesci en a e new track 7 o 1 Fal playmow ie Y Track name Time selection area for looping Adjust the window s appearance Double click to edit action Clock and hold to save of load track Toselectan entiretrack click on thetrack number To select multipletracks select onetrack then shift click on the track number of the other tracks Once you have selected oneor moretracks you can edit them with the commands in the Edit menu cut copy and paste them clear out all their events etc To rdocate a track select it choose Cut from the Edit menu then select the track after which you want to place the cut track and choose Paste from the Edit menu W henever you create a new track it will become track number 1if no track is currently selected if any tracks are currently selected though thenew track will beplaced after thehighest numbered selected track You can also adjust the visual height of atrack to allow you more vertical space for placing events just by dragging up or down on thebottom edge of thetrack 371 TI mel Ine Creatinga graphicscoreofM ax messages By double clicking o
147. ae pa 1 H 1 5 H fer gpa yah METAREN e e A wog Boei Tasar ota HUEN TANA et n te Gf Ae a ek EE ay Ve W PEs FLT W hen theseindividual curvesof progression for each of theparametersarecombined they create aconstantly changingyetstill quitepredictablemelody Panningmovesaccordingto 4 cycles of a cosine wave beginning panned to one side then moving slowly from sideto side and endingin the center of the stereo field Velocity is random within a restricted rangethat begins from 1 32 and increases according to an exponential curve ending in the range 96 127 Pitch moves in 480 cycles of a sinusoidal wave centered around key 66 beginning with an amplitude of 0 semitones and ending with an amplitudeof 30 semitones from 36 to 96 D elta time between notes changes accordingto 8 exponential curvesof acceleration repeatedly accelerating from 5 notes per second to 50 notes per second Duration isalways5 times aslong asthe deltatime of thenext note so that even the fastest notes last at least 100 milliseconds e Click on the button to compose record and play the melody Summary Thedetonate objectis useful for recording and playing sequences of notes and can read and write standard M DI files It is also useful for less commonplace sequencing tasks such as non realtime recording continuously variable playback speed and playing back the recorded notes in anew rhythm To record M IDI note messages in detonate atimer should beused to re
148. afilenameargumentto an object such astable or coll M ax will search for thenamed file H ereishow M ax searches for files Thefirst place M ax looks for afileis the default location If you have selected a patcher filefrom an Open Filedialog the default location will bethe folder containing that file If you havenot loaded afile yet the default location will bethefolder containing the M ax application T he default loca tion changes dynamically as you open filesin M ax Thedefault location is only asinglefolder if you open a patcher filefrom folder A subfolders of A arenot searched Thenext place M ax looks for afileis what we call the search path The search path is partially con figured using the File Preferences window T hesearch path includes files inside the folder contain ingtheM ax application you arecurrently using as well asthe entire contents of the Cycling 74 folder located at Library A pplication Support Cycling 74 on M acintosh and C Program Files Common Files C ycling 74 on W indows ThefoldersinsidetheM ax application folder are searched beforethosein the Cycling 74 folder Thestandard M ax installation contains patcher and datafiles inside folders within the M ax appli cation folder and external objects insidetheC ycling 74 folder See below for more details about sub folders of theCycling 74 folder M ore Details A bout Searching e Whenafolderislisted for searchingin theFilePreferenceswindow all subfol
149. age type numbers lists or symbols Tracks can be recorded played stopped muted and unmuted either individually or all tracks at thesametime The next message can be used to step through the recorded messages instead of playing then back at their original recorded speed See Also detonate Graphic score of note events follow Comparealive performance to a recorded performance mtr M ulti track sequencer seq Sequencer for recording and playing M IDI D etonate Graphic editing of a M IDI sequence Sequencing Recording and playing back M IDI performances 158 Tutorial 37 D ata Structures What Is a Data Structure A data structure is any collection of data that is stored in some arrangement that allows individual items to be found easily In Tutorial 32 we used the table object a data structure called an array where we used an index address to access the stored values In this chapter well use some objects that allow you to create your own collections of data and retrieve them with whatever addresses you wish coll Themost versatiledata structure objectin M ax isthecoll shortfor collection A coll object storesa collection of many different messages of any typeand length up to 256itemslong and can give each message either a number address or a symbol word address Anytimecoll receivesalistin itsinletit usesthefirst number in thelist asan address and storesthe renainingitemsin thelist at that address You ll recal
150. ages in its left inlet For a complete list look under table in the M ax Reference M anual Patch 2 shows afew of the different messages demon strating ways to alter atable without opening its graphic editing window To store values in atable send the valuein the right inlet then send the address where you want it stored into the left inlet You can also send the address and the value to the left inlet together as a list In Patch 2 we use an uzi object to send lists to table automatically filling all its addresses with the value 64 129 Tutorial 32 Thetable object e Double click on thetable object in Patch 2 then click on the button to seethe value64 being Stored at all the addresses W hen theuzi object receives abang or anumber itsendsa specific number of bang messages out its left outlet as fast as possible all within asingletick of M ax s internal clock It also counts the bang messages as it goes and sends the count out its right outlet It is particularly useful for sending out a series of messages at the same time such as a series of addresses and values for initializing a table Since uzi starts counting from 1 we send the0 separately triggered by the same bang Theword set followed by an address and oneor more values stores the values starting at the spec ified address For example the message set 23 65 68 79 stores the number 65 at address 23 68 at address 24 and 79 at address 25 e Send addressnumbersf
151. al objects required by your patch any subpatches used as objects in your top level patch or used in abpatcher and any nested subpatches sub subpatches used in subpatches of the top level patch will all be included automatically in the collective In addition certain objects such asjs fpic and hi copy files they use into the collective for you For thejs object the script text file is copied but not files the script uses Ifyou want your program to havemorethan onetop level patch you can add other patchesto the script by clicking on the Toplevel Patcher button and choosing another patcher from the filedialogbox M ax writesanew lineinto thescript indicating that it will also open that newly 327 Groupingfilestocreate Col ectives a single application selected file In the following example a patch named Arpeggiator is being saved as the top level patch in a collective and a second top level patch named Controls has just been added Script open thispatcher open lapdog Documents Maxs Patches Controls pat Include Folder Toplevel Patcher Patcher Include File Open Script Save Script When the collective is opened by a user top level patchers will be opened in the order in which they are listed in this window If you want to change the order in which they will be opened you can edit the script 2 Besides the externals and subpatches which are included automatically there may be other
152. ametro or resetting the contents of atable when a patcher is closed pcontrol Subpatch windows can be opened and closed by the pcontrol object W hen pcontrol receives an open or close message in its inlet it opens or closes the window of any subpatch objects connected to its outlet 179 Tutor al 40 Automaticactions In the left part of the main Patcher window you can seehow the stopwatch window was opened automatically The bang from loadbang triggered an open message to pcontrol which opened the window of thestopwatch object stopwatch Usingpcontrol you can produce multi window patches with each window displaying something different and you can makepcontrol show or hidewindows when appropriate N ote Becauseopeningand closing windowstakessometime it snotadvisableto do itwhileM ax is playing music unless you rein Overdrive mode e You can stop and restart thestopwatch by clicking on thetoggle in the stopwatch window To open and closethe stopwatch window send open and close messages to pcontrol e Closethe stopwatch window and open the clicktrack window by sending an open message to theother pcontrol object W hen the clicktrack window isopened a4 noteclick track auto matically begins to play atthe metronomic tempo shown in thenumber box Thepcontrol object can also enableand disableM IDI objectsin thesubpatch windowsit controls The messageenable 0 in the inlet of pcontrol disablestheM IDI objectsin
153. ammingtask in M ax and usually one way will be more efficient than another in terms of program size and speed Therearethree efficiency issues to consider 1 Theloaded sizeof aM ax program isafunction of thenumber of objects and subpatches and the complexity of each one 2 Theload timeofacomplex program is also afunction of thesametwo factors 3 The real time computational efficiency of aprogram isaffected by thefact that someobjects are moreefficient than othersin operation and communication Principles of Efficiency Sincethereare so many different kinds of messages that can be sent in M ax an object often has to look up the meaning of the message it sends or receives Computational speed is achieved pri marily by avoiding this message lookup Look at the description of theinlets and outlets of two connected objects in theO bjects section to see if they sharethesame message type In this case M ax will not haveto do any interpretation of amessage 341 Effi CI ency Issuesofprogrammingstyle gate switch Ggate and Gswitch haveno message lookup when avalueissentin aright inlet H ow ever these objects always do a message lookup on output Therefore it s better for integers to use something likeselect or if you relooking for aspecific number Three ways to send 127 to one place and everything else to another place The method on the right is marginally slower since it involves the graphic object Gyat
154. anced scripting list read from the created funnel object function list val if arguments length 2 thevalues arguments 0 arguments 1 bang steps through sequencer function bang if seqcounter gt numsliders reset sequencer seqcounter 0 if thereverse read from the array backwards outlet 1 numsliders seqcounter 1 send out our location in the sequence outlet 0 thevalues numsliders seqcounter 1 send out the current note else read from the array forwards outlet 1 seqcounter sound out our location in the sequence outlet 0 thevalues seqcounter send out the current note segqcountert increment the sequenc reverse changes sequence direction function reverse val if arguments length thereverse arguments 0 flip it See also js M ax JavaScript object D ata Structures W ays of storing datain M ax thispatcher Send messages to a patcher counter Count the bang messages received output the count table Storeand graphically edit an array of numbers 271 Tutorial 50 Tasks Argumentsand Global O bjectsin JavaScript Scheduling in JavaScript Thejs object allows you create avaScript functions that usethe M ax scheduler Thesefunctions can be triggered by M ax messages to thejs object Thetiming interval at which thefunction is called how manytimesit repeats inclu
155. ansparent allowing whatever is underneath the control to be visible For our stop go control weneed masks that havethe same outlineas the colored areas 318 Interfaces U sing picture based user interface objects Thiswill makethe white areas transparent The picture filewith masks added called stop go mask pct looks likethis Themasksareplaced below theimages in thesamerelative positions In many cases you can cre ate masks for your images simply by duplicating the images and using a paint bucket tool to fill theduplicates with black Try this picture by choosing stop go mask pct as your control s picture file Check the H asI mageM ask checkbox in the Inspector N ow thewhite areas of the control won t bedrawn Picturefiles for thepictslider and matrixctrl objects are constructed in much the same manner Refer to pictslider and matrixctrl manual pagesin theM ax ReferenceM anual for thelayoutsneeded for arranging their images Remember that not all of thei magesin the layout charts are necessary so that you can start by working with simple picturefiles and later add images to create more elab orate controls N ote Thepicture s dimensions must be exactly the size of the array of images and no more since thepicture based controlsusetheoverall dimensionsofthegraphicsfileto calculatethesizeofthe images Some graphics applications are known to add a one pixel widestrip of blank pixels to the lower and right edges of
156. arentor invisible Black pixelsin theimagedefinevisibleareas and whitepixels definetransparent areas The following illustration shows how rectangular images and masks combineto createa non rectangular image Source Image Mask Resulting Image TodemonstrateaM ax control that usesmasks we ll createatoggle button that lookslikean octag onal STOP sign when its valueis Zero and acircular GO sign when its valueisone To add alittle 317 Interfaces U singpicture based user interface objects visual interest we ll make its shape but not its color changewhen it is clicked with the mouse Its picturefilelookslikethis This pictureisin the filestop go pct To try it out create anew pictctrl open its Inspector choose thestop go pct fileasits picturefile and set its modeto Toggle After locking the patcher click the control afew times N oticethat it switches from thered octagon to thered circlefirst switching from the value 0 not clicked imageto the value 0 clicked image W hen you release the button it displays the green circle the value 1 not clicked image Everything looks fineas long asthe control is placed only upon a blank white window But sup pose wewant to put thecontrol on top of a colored panel object or apicture of afaux brushed aluminum surface W eseethe white areas of our images Thesolution to this aesthetic problem isto usemasksto definewhich partsof our imageshould be drawn and which parts should betr
157. art B of the patch shows how numkey interprets numbers typed on the computer keyboard ASCII values from thekey object aresent to numkey except for the keysx y and z which numkey ignores anyway because they arenot numerical digit keys number is sent out here when Return number is shown here as it or Enter is typed Tome E i being typed Asdigits aretyped numkey sendsthe current number out its right outlet The D elete Backspace key can betyped to erasethelast digit entered W hen you havetyped in thecompletenumber you can typetheReturn or Enter keyson M acintosh or theEnter kay on W indowsto send thenumber outtheleft outlet In general theright outletis used for showing what number is being typed and the left outlet is used for actually sending it e Trychangingthesound on your synth by typing in the program number on the computer keyboard Using a combination of key and numkey to typein numbersis different from typing numbers directly into anumber box because you haveto click on thenumber box beforetypinginto it The key and keyup objectsreceiveall typed keys so thereisno need to select any object beforenumbers are typed in via numkey 74 Tutorial 20 U singthe computer keyboard keyup Typing akey on thecomputer s keyboard just like playing anoteon your M IDI keyboard sends two messages to the computer onewhen the key is pressed down and another when thekey is released Thekeyup objects sends theASCII number o
158. ased on theticmd objects in the action that the track is using If thereis morethan onepossibleeditor for aparticular event for example an event of typeint can beplaced using an int etable or efunc editor the editors are presented in a submenu You choose the event you want from the pop up menu then enter the message you want that event to send to theticmd object e Try placing anote event in track 1 at time 4000 M ovethe mousein the event portion of the track until the indicator at the top of the window tells you that your cursor is at time 4000 Option click on Macintosh or Alt click on Windowsin the track in some white space where there areno other events in the way and choose a note event from the pop up menu You will get a messenger event editor into which you can typethenoteinformation As we have seen a note event should bea four item list in theformat pitch velocity channed duration so typein 28 96 1 1000 to play alow E on channel 1 for 1 second faa Ea Go You can play your timelinewithoutleavingthegraphic editing window by usingthetaperecorder style controls at thetop of the window Summary A timeineisa multi track sequencer each track of which sends messages to ticmd objectsin a specified action patch You place events messages in atrack in non real time by O ption clicking on Macintosh or Alt clicking on Windows at the desired location on thetimeline The messages comeout theoutlet of theticmd objectin theaction
159. ask then sends out messages The print object just prints whatever it receives Themessage box is connected to theprint object by means of apatchcord J ust likecomponentsof a stereo system the outlet of one object is connected to the inlet of another object You can t con nect an inlet to another inlet or an outlet to another outlet The program operates as follows 1 When you click on themessage box object the message Hello is sent out the message box sout let and through thepatch cord 2 Themessage reaches the inlet of the print object which prints the message print Hello in the M ax window Locking and Unlocking a Patcher Window A Patcher window can bein one of two states locked or unlocked W hen a Patcher window is locked itisaprogram ready to run and you can operatethepatcher by clicking on objects such as sliders that do things W hen it is unlocked you can edit the patcher by moving objects around creating new ones and connecting objects together Thelock unlock stateofthewindowisindicated bythepresenceofthepatcher paletteat thetop of the window If you see the palette then the window is unlocked Tutorial 1 anal Thereareseveral other ways you can lock or unlock a patcher e Choose Edit from theView menu or typeCommand E on M acintosh or Control E on Win dows e Command click on Macintosh or Control click on Windowson the white space in the Patcher window e On Macintosh there isa transpare
160. assed by PassPct to trigger notes sent to thesynth Usea5 octavekslider to choosewhich pitch will betransmitted M akethe percentage value of PassPct depend directly on thepitch selected with kslider Asthe pitch increases from 36 to 95 the percentage should increase from 5 to 95 Hints Thepitch valuesent out by kslider should bestored in sometypeof storageobject an int avalue a number box etc an int isthemost efficient T hebang messagesfrom PassPct can then trigger the storage object to send itsnumber to makenote and play anote Thehard part of this exerciseis using the range of pitches sent out by kslider from 36 to 95 to providea different range of percentages from 5 to 95 to PassPct Thisis known asmapping one rangeto another A directcorrespondencesuch asthisisalinearmap therelationship between the two ranges can begraphed asa straight line Pat 35 5 Fitch 36 a5 Asthepitch changesfrom 36 to 95 thepercentage changes from 5 to 95 Calculating a Linear Map Theproblem of linear mapping is given onerangeof numbers from xmin to xmax and another rangeof numbersfrom ymin to ymax and given somenumber x within the first range find the number y that occupies the same position in thesecond range H ere saformulafor finding they valuethat corresponds to any given x value y x xmin ymax ymin xmax xmin ymin W hen weplug our rangesinto the formula we get y x 36 90 60 5 111 Tutorial 2
161. at created the print objects in the patch weexamined above ln the case of the object box definition thefirst and second numbers after newex refer to the horizontal and vertical coordinates and thethird number refersto the object s width T hefourth number represents the font and font size infor mation After executing the scripting commands weobtain the result shown below N ow we ll usescripting to automate connecting the receive objects to thenumber box objects 237 Tutorial 46 Basic scripting Let s finish our patch and connect everything up i 0 objnamesz script new 3 newex i 2 48 1441902 r 3 pack 0 0 objname script new 3 number 1 2 35 10 0 0 0 220 0 0 221 221 221 Bee 222 eee oo D sprintf script connect Ks 0 s 0 thispatcher po bo po po J pe po J pe bo bo bo bo po Connectingnumber box objects to receive objects This may seem like alot of troubleto go to just to create and hook up 30 objects but now each object is uniquely named with a patcher specific scripting name and in the case of the receive objects aglobal symbolic name This means wecan continueto manipulatethen for the life of the patch U sing the basic technique shown above wecan create thousands of connected objects from aprototype 238 Tutorial 46 Basicscripting Deleting Objects To delete objects usethe script delete message script delete lt variable name gt This e
162. at receives bang messages in its left inlet and passes a certain percentage of them outits outlet Thepercentage should bespecified by atyped in argument or by anumber received in theright inlet Hints A percentageof probability isthenumber of timesan eventislikely to occur in 100tries For exam ple a33 chance means the odds are 33 in 100 that the event will occur Usethegamble object from the previous chapter as a model to give you an idea how to proceed Thepasspct object will besimilar except a Thenumber of possiblerandom choices will always be 100 b Instead of sending out al or a0 you want your object to send out bang whenever the condi tion ismet Solution to Exercise 1 W ehave saved our solution to Exercise 1 in afilecalled PassP ctin theM ax Tutorial folder W hen abang or any other message is received in the left inlet therandom 100 object chooses a number from 0 to 99 If itislessthan thenumber specified as an argument or received in theright inlet sel sends abang out the outlet F percentage of bangs to he passed bang or any message 7 hang a certain percent of the time N ext wewill usethePassPct object in a patch to make probabilistic decisions 110 Tutorial 29 Test 5 Probability object Pass a Percentage of bang messages from a metro 2 Useametro to send bang messages at a constant speed and use PassPct to pass only a certain percentage of those bang messages U se the bang messages p
163. atch 3 ThefileC major t is loaded into thetable object whenever the Patcher window is opened You might want to give your Table files names that includesome distinguishing characteristic such as t so that you can tell Table files and Patcher files apart e Double click on thetable Cmajor t object to seeits contents W ith theC major t table editing window in the front choose Get Info from the O bject menu to open thetable Inspector Table Size Table Range 128 LJ Save Table With Patcher Don t Save LJ Use Note Name Legend LJ Signed Values Options You can see that the Size of the table is 36 the number of notes in C major that areon a61 note keyboard Don t Save is checked because we don t anticipate wanting to save changes to this file and SaveT ablewithP atcher option isnotchecked becauseit s sufficient to havethetable stored ina separate file and read it in when weopen the patch e Closethetablelnspector and click on thebutton in Patch 3 to hear the use of line and table for readingthrough apredetermined set of pitches N oticethatline is also used to create avelocity crescendo from 20 to 125 127 Tutorial 32 Thetable object In order to go from 0 to 35 in exactly 3 5 seconds at arate of exactly 10 notes per second wehad to play a small trick on theline object by giving it atime slightly longer than desired 3501ms H eres why To producea perfectly timed ramp of all values from onenumber to another with line you
164. ate it properly A similar box is created when a user interface object referenced insidea file cannot be located lt objectname gt fragment file not found This error occurs when a collective references an external object that has been improperly stored in the collective It should not happen with the current version of M ax lt objectname gt lt filename gt file not found This error occurs when afilenameis either passed to an object as the argument to a read message or stored within an object saved within a patcher The file cannot be located either within M ax s search path or with its full pathname lt symbol gt bad arg types Occurs when a patch is running and asymbol is received in the inlet of a bitwise operator such as amp lt lt or gt gt M akesurethat only number messages are sent to bitwise operators lt symbol gt no such object Occurs when a message is sent to a send object or to a message box that contains a semicolon fol lowed by the name of a receiver and thereis no receive object with the name specified in the send object or message box lt number gt not a symbol Occurs when the dement that follows a semicolon in a message box specifying a receiver for the message isnot a symbol lt filename gt bad magic number lt filename gt corrupt binary format file The file you tried to open is corrupted or isnot a properly formatted M ax document Restore the filefrom abackup copy if available
165. atting MIDI Data In theexamplepatch wehaveshown acoupleof waysin which diverseM IDI data from midiparse may beused to control objects in M ax or may be given another meaning and transmitted with midiformat and midiout Thecontroller data from thethird outlet of midiparse is sent to route which selects only data from controller 1 the mod wheel The mod whea data from 0 to 127 is mapped to the range 64 to 0 then it is reassigned as pitch bend data by midiformat and transmitted to the synth The resulting effect is that the mod wheel of the keyboard also controls the pitch bend As the modulation increases from 0 to 127 the pitch is bent downward from 64 to 0 This typeof reassignment isa convenient way of correlating two different kinds of control data bed 140 Tutorial 34 M anaging raw M IDI data Another part of the patch shows how you can select data from agroup of M IDI channds The channel number is used to open or shut agate for the note data Only note data on channels 1 through 8 is sent on and the pitch data triggers a number from thetable midiparse e Playnoteson your M IDI keyboard and you will hear that each note on pitch isalso used asan addressto trigger a valuefrom thetable If you set your keyboard to transmit on a channa between 9 and 16 thenotes will not be passed by the gate Copying Captured Values into a table Theincomingpitch bend dataissent out of midiparse to a capture 128 object Theargument
166. ay If itislessthan thecurrent delay abang issent to theflush objects causingthem to send outnote offs for any notes that may beheld down on your M IDI keyboard 88 Tutorial 23 Test 4 Imitating a performance Thenew delay timeisthen sent to theright inlet of lt to bestored asthecurrent delay time Itis also sent to theright inlet of the two pipe objects N otethat it is doubled before being sent to the pipe on theright so that theright pipewill delay twice as long asthe left pipe pipe 0 3000 pipe 6000 lf thenew delay timeislessthan thecurrent one flush any held notesbeforechangingthedelay time Summary Delay and transposition can be combined to createimitation Always consider unlikely possibilities For example whenever you ask the user to supply a value check to makesure itis a valid value before usingit You can print an error message when an invalid number is received or you can just changeit to some valid value W henever you are pro cessing note data make surethat note ons are always followed by note offs 89 Tutorial 24 send and receive Sending Messages Without Patch Cords It s possibleto send any typeof message without using a patch cord with thesend and receive objects A message in the inlet of asend object comes out the outlet of any receive object that has the same argument In this patch wehaveredonethe imitating patch from the previous chapter using send and receive objects also
167. b patch you ll need to unlock the controls window pitch clear velocity clear rbytin clear OM r OFF clear memory CLEAR MEMORY Thedatafrom ctlin issent to thetoggle in the subpatch then back to the main patch This lets us usethe toggle both for displaying the on off state received from the mod wheel and for actually sending on off commands with the mouse mod 34 E onoge OM OFF clear memory 135 Tutorial 33 Probability tables Theon off state 0 or non zero is sent to togedge togedge sends a bang out one of its outlets only when thenumber it receivesrepresentsachangefrom 0 to non zero or viceversa T heleft outlet is for changesfrom Oto non zero and theright outlet isfor changesfrom non zero to 0 If wesentthe control datadirectly to themetro themetro would get restarted with every non zero number from themod wheel togedge lets us detect only the essential control data changes to and from 0 W hen togedge receives the on status from thetoggle it turns on the metro W hen it receives a0 it turns off the metro and sends a bang to all the message boxes in the controls window Each of the clear messages is routed to the proper histo and table objects with route Clearing the rhythm also resets the time of metro and makenote to 720 Thereason weused threedifferent message boxesto send theclear messages separately isbecauseit also givestheuser the option of clearing the memory of only one parameter by clicking on asp
168. bal object The argument to the global object bounce isthenamein the M ax namespace that will betied to the object Any message sent to bounce within M ax will attempt to set properties of the Global object using that name N otethat internally werefer to theGlobal object by a variablenameof our choosing glob not by thesymbol with which M ax and our js object communicate W e veadded a property starttime to our object simply by assigning itin our global block N ow any message beginning with starttime sent to bouncein our M ax patch will set that property to its arguments Furthermore this object istruly global in thesensethat not only can M ax set it from outside of a js object multiplejs objects sharethe specific instance of this object and its properties You could use this featureto have multiplejs objects share information as well as haveM ax broadcast infor mation to multiplejs objects Summary JavaScript allows you to schedule events dynamically using theT ask object You create aT ask and bind it to afunction that gets called by the Task You can activate and cancel thetask and set the Task s timing interval and how often it repeats Furthermore by using the callee property of the function called by theT ask you can set these things from within the scheduled eventitself All methodsin js objects whether called internally or by M ax messages are executed at low priority in thescheduler JavaScript hasa
169. be subpatches of one main patch so that they areall loaded when the main patch is opened Subpatches can communicate with each other viainlets and outlets or viasend and receive objects and they can share data by using coll table or value objects which have the same nameas an argument Thereisno reason that alargeand complicated program cannot becomposed of many smaller parts and the advantages of this approach areconsiderable Modularity Thereareseveral important reasons why itis a good ideato usea modular approach to program ming O nereason isthat it makes it easier to verify that your program actually works especially in extreme or unusual cases T his becomes harder and harder to do asa program growsin sizeand complexity By building small modulesand ensuringthat each oneworksasitssupposed to in and of itself you reducethe number of possible problem spots when the modules are combined in a larger context A second reason is that many tasks in a program areused again in different contexts Once you havebuiltasmall modulethat performsacertain task you can usethat modulewherever theneed for that task arises rather than rewriting it each time Another reason isthat many tasksin a program aresimilar to other tasks By writing a small gen eral purpose module usually onethat takes arguments so thatits exact function can bemodified by the argument you can usethat onemodulewith different inputs or arguments to do many similar things
170. berstheuser typesin asa delay time and only send them to pipe if they arereasonable Try usingasplit object or hslider to limitthenumbers between 0 and 15000 Theproblem of note offs being played beforenote onscould occur if theuser typesin a much smaller delay time whileholding down anoteon thesynth It would result in stuck noteson the synth Onesolution isto compareeach new delay timeto thepreviousone If thenew oneissmaller send anote off to pipe for any pitch being held down on thesynth This requiresrunning thenotes through aflush object before sending them to the pipe objects and also requires comparing the delay times and sending a bang to theflush objects if a smaller delay timeis typed in Solution to Exercise 2 Scroll the Patcher window all theway to theright to see Patch No 2 apossiblesolution to the exercise N ote W ehaveset Patch 2 to receivenotesonlyon M IDI channel 2so0 thatitwill not play whileyou aretrying out Patch 1 To hear Patch 2 set your keyboard to transmit on MIDI channa 2 W ehave used acombination of key and numkey to get the numbers typed on the computer s key board Thetyped numbersaresentto split and any numbersless than 0 or greater than 15000 will cause an error message to be printed in the M ax window must be from to 15000 print Delay Invalid numbers causean error message to be printed Thetyped delay timeisfirst sentto therelational operator lt to compareitwith thecurrent del
171. bject to open the subpatch window 160 Tutorial 37 Data structures e Playsomelongnoteson your M IDI keyboard Every key on thekeyboard hasaunique3 note chord assigned to it The chords are stored in a coll object using the key number the pitch of the played note asthe address e Doubleclick on thecoll object in Patch 1 to see how the chords are stored If you want to change some of the chords edit the numbers in the Text window then close the window to update the contents of the coll When a pitch value is received in the inlet coll sends out the 3 item list stored at that address The list is broken up into a series of numbers by iter and the numbers are sent virtually simulta neously to noteout where they are combined with the note on or note off velocity being played on aM IDI keyboard Therest of Patch 1 is for storing your own chordsin a coll W hen pitch data is routed out the right outlet of the Ggate the note on pitches aresent to athresh object Thethresh object is like iter in reverse Numbers which are received within a certain threshold of time are packed together in order Thethreshold isthe maximum number of milliseconds between any given number and the previous one When no new number is received within a cer tain period thenumbersaresent out asa list So when you play notes of achord simultaneously within 50msof each other they arepacked as alist and after 50msthey aresent out Theunpack object sel
172. bjects initially store thenumber 0 Using float Thepatch in theleft part of the Patcher window uses both int and float O nceweunderstand what the patch does the need for these objects should beclear 7 Tutorial 21 Storing numbers Thecombination of notein and stripnote should befamiliar to you It s the easiest method of get ting note on data from a M IDI keyboard without getting note off data Thevelocity is converted to three separate messages by thet trigger object afloat a bang and another float T he first float from the right outlet of t issent to theright inlet of the object whereitis stored Thebang then causes thefloat object to send out its stored number Thistriggers a series of calculations finally resulting in anumber being sent to theright inlets of makenote and metro Then the last float from the left outlet of t isstored in thefloat object W hat this meansis that each time anew velocity is received the previousvelocity is divided by the new velocity then thenew velocity is stored asthe previous one T heresult isthe ratio of theold velocity to thenew velocity N ote Thevelocity could just as well be stored in an int object butit is converted to float by the object in any case Sincethe conversion from int to float hasto occur somewhere wemadethe conversion with thet object W hy do weneed to dividethetwo velocities as floats C onsider the possible cases T he range of possibleratios
173. ble and efunc 366 TI mel Ine Creatinga graphicscoreofM ax messages When you create an etable editor it appears as a shaded box in the event area of thetrack The command name of the corresponding ticmd object is displayed in its upper left corner Double clicking on this box will display the familiar table editor lintit Kaja o D Db gt gt ph 00 00 00 00 08 17 Track Display 00 00 00 00 04 00 00 08 00 00 12 00 00 16 00 T i 1 PrintThree timeline 1 Any changes you makein thetable editor will appear in the etable W hen you play thetimeline the etable will send its stored values to the corresponding ticmd object in order from left to right The values from theetable being played by thetimeline are sent out theticmd object s middle out let By clicking and dragging the lower right corner of the etable you can resizeit Resizing the etable horizontally will change its duration on the timeline causing its values to be sent out at a different rate Resizing the etable vertically has no effect on the data sent to ticmd W hen thetimelineis being played and reachestheleft edgeof theetable abang issent out thecor responding ticmd object s left outlet The contents of an etable will ordinarily be saved with thetimelinethat contains it You can also link an etable to an existing table object By clicking on an etable and choosing Get Info from the Object menu you can enter a
174. board and movethemodulation wheel You will see thedial and kslider display your actionsin thetwo subpatch windows All Windows Active In computer applications the front window istheactive window whereyou apply menu com mands such as Save and Close and click and drag on objects To makeabackground window active you haveto click on it first to bring itto theforeground TheAll Windows A ctiveoption lets you use background windows without bringing them to the front To bringany window to thefront click on itstitlebar or chooseitsnamefrom theW indows menu You can also Command click on any visible part of the window in M acintosh or Control click on W indows e CheckAll Windows Activein theO ptionsmenu Thiswill let you click and drag on thedial and kslider in the background windows without bringing the windows to theforeground e Dragon thedial and thekslider They can send datato thesynth as well as display data received from your keyboard You can closeasubpatch window by clickingin its close box and you can reopen it by double clicking on the locked patcher object N ow let s examinethe contents of the patcher objects 98 Tutorial 26 T hepatcher object The modwheel Subpatch e Bring themodwheel window to theforeground and unlock it N ow you can seethehidden objects M odulation wheel data received from your M IDI keyboard with ctlin is sent to ther modin object in the subpatch T hecontrol data replacesthe 1 argume
175. box is ether of type int or float and will convert numbersto that type See Also number box Display and output anumber 16 Tutorial 4 U singmetro Object Names and Arguments metro 1000 metro iati In this chapter weintroduce a new object called metro which functions as a metronome You will notice that we havetyped in a number after the word metro in the object box T his isthe number of milliseconds between ticks of the metronome Thenumber after the word metro is called an argument We have already seen arguments used to givenames to print objects Arguments typically give objects information necessary to do their job object name argument N Some objects require typed in arguments in order to function M ore commonly an argument is optional to supply somestarting value asin thecaseof metro wheretheargument determinesthe initial speed of the metronome W hen metro is started it sends out a bang message every n milli seconds wheren isthe argument until the metronomeis stopped If no argument is typed in metro has a default value of 5 and sends out a bang every 5 milliseconds The metro object has two inlets A message received in the left inlet can start or stop the metro nome Themetronomewill start when it receives any non zero number in its left inlet and it will stop when it receives a 0 A Iternatively you can send it a bang message to start and stop to stop A number received in the
176. by asemicolon in amessage box thefirst word after the semicolon isthenameof areceive object and therest of themessage or up to thenext semicolon is sent to all receive objects with that name instead of out the message box s outlet Thecomma and thesemicolon enable a message box to send many different messages with a singletrigger Thedollar sign followed immediately by anumber such as 1 isa changeableargument When the message box receives atriggering messagein itsinlet each changeable argument isreplaced by thecorrespondingitem from thetriggering message 1 isreplaced by thefirst item 2 is replaced by thesecond item etc If no item is present in theincoming message to replace the value of a changeable argument the previously stored valueis used If no valuehas yet been stored ina changeable argument its valueis 0 by default A backslash used beforeaspecial character such asacomma asemicolon or adollar sign negates the special characteristics of that character A set message can be used to changethecontents of a message box without triggering any output An append message can be used to add things to theend of the message in a message box Theprepend and append objects attach their typed in arguments to the beginning or end of incoming messages then send out the combined message 96 Tutorial 25 M anaging messages See Also append Append arguments at the end of amessage message Send any message prepend Put one messa
177. called s and r pipe 0 0 6000 EE e Playon your M IDI keyboard Thenote data is sent to thereceive objects and r objects that havethe same name argument asthesend object Thenameargumentof asend object islikeauniqueradio frequency and any receive object with thesamenameis tuned in to that frequency Any typeof message can besent with s and r ints floats lists symbols etc Communication Between Patcher Windows Thesand r objects haveone particular advantage over patch cords in that they can communicate even if theobjects arenotin thesameP atcher window T hisisavery valuablefeature enabling differ ent patches to communicate with each other You must takecarewhen naming your send and receive objects though so you won t send amessageto another Patcher window unintentionally value Thevalue object also called v stores any message received in its inlet Themessage is sent out when abang isreceived All value objects with the same argument share the same storage location in thecomputer s memory so thenumber can bestored and recalled by any oneof the objects 90 Tutorial 24 send and receive W hen anew messageis stored in one value object all others that sharethesamenamewill also contain thenew message A message stored in onelocation can berecalled in another location e Useoneofthenumber box objectsto storeanumber in thevalue object named share Thenum ber can be recalled from any
178. cally editing a multi track sequence of M ax messages to be sent to specific objects at specific times Thetimeline object does not record M IDI data in real time itis for placing predetermined events in non real time H owever once you have entered messages in the timeline which the timeline could send to a patch containing M IDI output objects thetimeline object allows you great flexibility of playback of those stored messages See the Timeline chapter for details See Also follow Comparealive performanceto a recorded performance mtr M ulti track sequencer seq Sequencer for recording and playing M IDI timeline Time based score of M ax messages Timeline Creating agraphic score of M ax messages Tutorial 35 Sequencing 361 Timeline CreatingaGraphicScoreofM ax M essages Introduction A timeline is a graphic editor for creating a score likea musical score of M ax messages W hen you tell thetimelineto play that score it sendsits specified messages to thespecified patches at the specified times Therearethree basic steps in creating atimeine 1 Create or modify atleast onepatch to communicatewith thetimeline Thispatch must con tain at least oneticmd object Just as you would usean inlet object in a patch to receive mes sages from a parent patch you useticmd to receive messages from the timeline Such a patch which communicates with atimeline via theticmd object is called an action 2 Createa timeline and create a
179. ch 2 contains the horizontal slider hslider mm HEJA dial slider hslider EEuae E e Gwe Saar kslider pictslider uslider multislider rslider Various sliders and dials in the palette Therearea few important differences between these objects and theslider and number box objects seen in previous chapters 1 Theslider and thenumber boxsend outnumberswhen you drag them with themouse You can drag on the other sliders and dials but you can also changethem with a single mouse click e Click on theslidersand dials and noticehow they jump to thenew position and send out anumber even without dragging the mouse 2 Theslider and kslider objects resize themselves automatically depending on their range The hslider and uslider can beshrunk or enlarged to virtually any sizewith thegrow bar regardless of the range of numbers they send out T hedial has only one possible size regardless of its range 3 Although theslider and kslider may havea limited range of numbers that can be output by dragging they do not limit the range of numbers that can pass through them The dial hslider number box and uslider do limit the numbers received in their inlets Any incoming number that is less than 0 or the specified minimum in the case of number box or that exceeds the specified range will be automatically restricted within those limits Thelimiting feature can be put to use asisshown in Patch 2 Let s analyze what t
180. ch cord according to the method described in the preced ing paragraph it s probably because Segmented Patch Cords is checked in theO ptions menu For themoment that option should beunchecked If your message object and your print object arenot perfectly aligned vertically the patch cord will appear jagged This has no effect on thefunctioning of the patch H owever if you re a fastidious person and want to clean up the appearance of your patch select both objects just as you d select multipleiconsin the Finder by Shift clickingon each of them or by dragging across both of them with the mouse Then chooseAlign from theO bject menu You can also move objects by dragging them to the desired location O bjects and patch cords can beremoved entirely by clickingon them to selectthem then pressingtheD eletekey on M acintosh or the Backspace key on Windows or choosing Cut or Clear from the Edit menu e TypeCommand E onM acintoshorControl E onW indowsto lock thePatcher window Your program isnow ready to run Click on the message box containing Good bye and you should see print Good bye in the M ax window Summary W hen aPatcher window isunlocked itisin Edit mode and can bemodified W hen thewindow is locked the program is ready to run You can also run the program by holding down theCom mand key on Macintosh or Control key on Windows and clicking in the Patcher window A message is sent through a patch cord from the outlet of one object
181. ch cords and they can often make a patch neater and more comprehensible ae aa sn AAT Eea ooo m m The method of connecting objects is a little different when the Segmented Patch Cords option is in effect Instead of dragging from outlet to inlet the method isto click on the outlet then click at each of the points where you want the patch cord to bend then click on the inlet of the receiving object 4 5 6 1 2 3 Thepatch in theleft part of thePatcher window showshow segmented patch cords can beused to givethe patch a neater look making it easier to understand how the patch functions Tutor al 19 Screen aesthetics Of course sometimes segmented patch cords can make a patch less clear to the eye In the follow ing example the user cannot be certain where the top left number box is connected without actu ally changing the number to see which of the lower three values changes too Note that you don t need to turn the Segmented Patch Cords option on in order to makepatch cords that turn corners Shift clicking on an outlet will allow you to connect a patch cord in seg mented mode Hide On Lock e Unlock the Patcher window You will see several objects and patch cords that were not visible before When editing a patch you can select objects and or patch cords and choose Hide On Lock from the O bject menu T his sets those objects to be invisible when the Patcher window is locked Show
182. ch gets recorded along with the pitch velocity and channel and then restartsthetimer Theduration valuefor each noteeventiscalcu lated by detonate itself It measures the time elapsed between a note on and its corresponding note off uses the time difference as the duration value then throws away the note off message Itisnoteworthy that detonate doesn thaveanysenseof realtime Itdutifully recordsthereceived delta time but it doesn t really care how much time actually passes between received messages It simply stores note events in the order received For that reason it s very easy to record notes into 381 Detonate detonate in non real time as with the Step Record featurein many M IDI sequencing applica tions Use only note one to record the note events Duration GraphiceditingofaM IDI sequence Speci duration and delta time Valuer independently of real Hime Channel U singdetonateasanon real time step recorder And of course just as the rhythm and note durations can be manufactured artificially all the other note parameters can likewise be generated algorithmically within M ax rather than being played in viaM IDI Thefollowingexamplecomposesand recordsa1000 notemelody instantly at the click of a button using mathematical expressions to calculate different curves for pitch veloc ity panning and rhythm You can examineand hear theresultsin the examplepatch for T u
183. checked numbers cannot be entered by dragging or typing This is useful when you want anumber box to befor display only without being an onscreen controller 34 Tutorial 10 Number boxes Thethird patch shows some of these optionsin use The patch is for converting decimal numbers to their hexadecimal or notename equivalents or vice versa e Dragon thetop number box and you will seethe numbers displayed in different formats Summary Thenumber boxcan beused to display numberspassingthrough it and or asan onscreen control ler for sending out numbers Numbers can be sent out by dragging on thenumber box with the mouse or by clickingon thenumber box and then typingin anumber or pressingtheup or down arrow keys Therangeof numbers a number box can send out can be specified by choosing Get Info from the Object menu W ith the Inspector you can also change how thenumbers are displayed and how the number box responds to the mouse See Also number box Display and output anumber Tutorial 3 About numbers 35 Tutorial 11 Test 2 Temperature onversion Using Arithmetic Operators To be sure you understand how to use arithmetic operators and thenumber box try this exercise 1 Makea patch that converts a temperature expressed in degrees Fahrenheit into one expressed in degrees Celsius Use a number box to enter the Fahrenheit temperature send the number to arithmetic operator objects to convert it and use another number box
184. coll Store and edit acollection of different messages menu Pop up menu to display and send commands preset Store and recall the settings of other objects Data Structures Ways of storing datain M ax 169 Tutorial 38 expr and if CLanguage Expressions TheM ax application itself is written in theC programming language and many of theterms and object names such as amp amp and for and and or in M ax have a basis in C For programmers who havesome experience with C or Pascal and who feel comfortable using traditional programming language syntax M ax provides objects for evaluating mathematical expressions and conditional statements that are expressed in a C like way Even if you don t know a programming language you can understand and use these objects Often acomplex comparison or mathematical calculation that would require several Patcher objects can be expressed in a single phrase in asingle object Also you can do afew calculations with these objects that you can t do with any of the other arithmetic operators expr Thearguments to theexpr object makeup amathematical expression formula in aformatthatis similar to C programming language For example theC expressions X 67 y 96 2 x 12 1 abs y 127 can be expressed in an expr object as Without using expr you would perform the calculation with a patch with many objects that looks like this 170 Tutorial 38 exprand if e To seean example of an
185. command but because they haveno visible borders T hese objects are bpatcher and menu in Label mode which are discussed later in this chapter Playing a QuickTime Movie e Movethemodulation wheel on your synth to anon zero position W hilethemod wheel isin anon zero position themoviein imovie playsin aloop Thisparticular movieis only fourteen frames long so it lasts alittle less than half a second In those fourteen framesthereareonly four different frames so theeffectiveframerateis only about eight frames per second which explains why the motion is rather jerky By selecting the object and choosing Get Info from the O bject menu then choosing a Quick Time moviefilefrom thedialog box you tell imovie what movieto read in when the patch is loaded imovie responds to various control messages most notably start and stop which arethe only messages we use in this example 200 Tutorial 43 Graphicsin a Patcher e Stop the movie by returning the mod whee to its zero position Double click on the patcher playmovie object to seehow themovieis being controlled ctlin a 1 1 TogEdge d Contentsof thepatcher playmovie object A togedge object is used to detect changes in the zero and non zero status of the mod wheel It fil ters out the numerous non zero numbers themod wheel might generate and reacts only to a changein its zero non zero status It starts the movie and uses the metro to rewind it to time0 e
186. ctions Thisis not only helpful to the user of the program but is also very helpful to you the programmer You d beamazed how quickly you can forget how your own program works Getin thehabit of adding many explanatory comments as you build programs A comment box or almost any other object can be resized by dragging on the grow bar in the lower right corner of the box grow bar e You can also change the size of the text in a comment or any other object Click on the com ment box to select it then chooseadifferent font or sizefrom theFontmenu T rychangingthe font characteristics and the size of the comment that says T hisisa comment When you specify font characteristics with no objects selected you set the characteristics for any new objects you subsequently create in the active window W hen you specify font characteristics with theM ax window in theforeground you set the characteristics for all new Patchersyou subse quently create M ax stores these font characteristics in the M ax Preferences file and recalls them each time you use M ax Summary A toggle can beused to generatethenumbers 1 and 0 for turning other objects such asmetro on and off It can also beused asan indicator of numberspassing through it telling whether themost recent number was zero or non zero although any floats passing through will be converted to int A comment doesn t do anything but is useful for putting text in a Patcher window 20
187. d performing theaction again A loop generally involves some sort of a check before or after each repetition to seewhether the action should be performed again without the check the process would continue endlessly In M ax a bang message can be used to signal that an event has occurred In the example below a bang is sent each time the sustain pedal controller number 64 is pressed down or each timethe noteM iddleC key number 60 is released E pitch is 60 AHE velocity is 0 ctlin a 64 1 select 127 Sincebang isthe generic indicator that something has happened thereis an object designed to countbang messages called counter It countsthebang messagesit receivesin itsinlet and sendsthe count outits outlet You can set minimum and maximum output values for counter and set it to count up down or up and down In thefollowing example counter countsfrom 1 up to 5 then starts again at 1 The right outlet reports how many times the maximum 5 has been reached SaaS eee Count how a counter 0 1 3 aay Himes ro bo has been reached Itcan beuseful justto send out asuccession of numbersfrom acounter For example thenumbers could be used as addresses to get values from atable Other times in order to maketheloop use ful thereneeds to beauniqueevent when a certain condition is met Actually counter has its own built in conditions and reactions such as when the maximum is reached send thenumber of times it has been reach
188. d in this Tutorials and Topics M anual under Errors Comment Thereis probably no known case of a programmer complaining because a program contains too many comments Explanatory notes in acomment object can help others understand your patch and can help you remember what you have done when you go back and look at it later It is sur prising how fast you can forget why you wrotea program the way you did You may even want to usea Text window to makenotesto yourself or to jot down ideas for future reference Usingcolorsfor patch cordsand objectscan also beaform of commentingyour patch You could for example use a distinctive color to mark all the objects and connections where M IDI informa tion flows through a patch distinguishing it from objects and connections that handle the user interface An easy way to set thecolor of a patch cord or objectisto control click on itto getacon textual menu then choosea color from the Color submenu See Also Efficiency Issues of programmingstyle Encapsulation How much should apatch do Errors Explanation of error messages 392 Errors Explanation ofErrorM essages Error Reports in the Max Window M ax prints an error report in the M ax window when you make a programming mistake Below is alist of error messages you may encounter along with likely causes of each message variable out of range Occurs when you refer to an argument number out of the range 1 9 in a message sent to a mes
189. d to giveuniquenames to send and receive objects in asubpatch making the exchange of messages between them private local to that one instance of the sub patch 10n1y If these objects exist in a patch named private and thepatch isused for two subpatcheslikethis private ForYourEyes ForYourEyesOnly ForYourEars0nly private ForYourEars r ForYourEyesOnly r ForYourEarsOnly theobjectsappear withthis namein onepatch andwithauniquenamein theother 353 Arguments and changeableargumentsto objects W hen openingapatcher file automatically with theload messageto apcontrol object changeable arguments insidethe patch being loaded can bereplaced by valuesthat areprovided as additional arguments in theload message asin the example below load playscale Cmajor 7 filename anid arguments table lscale table Cmajorscale If these objects exist ina and thismessageis sent to a thepatch will open with objects patch pcontrol object lookinglikethis hasa special meaning It can be put at the beginning of a symbol argument transforming that argument into an identifier unique to each patcher and its subpatchers when the patcher is loaded This allows you to open several copies of a patcher containing objects such as send and receive without having the copies interfere with each other See Also expr Evaluatea mathematical expression message Send any message pcontrol Open and closesubwindows within apatc
190. d when you play hard when the velocity is greater than 64 and isbent downward when you play softly N oticetheway that sel isused to filter out note off velocities If thiswerenotdone thepitch would be bent down to 0 each time a key is released which might be bothersome in some cases On the other hand triggering pitch bends with note offs could bean interesting effect 56 Tutorial 16 M oreM IDI insand outs pgmin and pgmout MIDI program change messages change the sound a synthesizer uses to play notes Almost all synths can receive program change messages and many can send them as well Differentsynthshavedifferentnumbersof possiblesounds and havedifferent waysof numbering their sounds Some synths start numbering sounds from 0 whileothers start from 1 Others use uniquenumbering systems such as aletter number combination simulating base 8 arithmetic etc e Usethedial in the second patch to send program change messages to the synth e Thedial sends out numbersfrom 1 to 32 If thisisnot appropriate for your synth you can change theD ial Rangeand Offset Unlock the Patcher window select thedial and choose Get Info from the O bject menu ctlin and ctlout A control change message contains three vital items of information the channel the controller number and the control data The meaning of the data is dependent on the controller number For example controller number 1 is usually assigned to the modulation
191. d write tsk execute run our task function once If wewould liketo makeour task repeat every 250 milliseconds for 20 repetitions wewould write tsk interval 250 tsk repeat 20 Ifno argumentsaregiven to the repeat method theT ask will bescheduled indefinitely until wecance it as follows 274 T asks A rgumentsand Tutorial 50 Global O bjectsin JavaScript tsk cancel cancel our task Theexecute repeat andcance1 methodsgiveusall of the flexibility we need to schedulerepeatingeventsin JavaScript n addition to the interval property of theT ask object we can also find out whether a task is running or not running and how many times it has been called iterations for example Oneimportant thing to keep in mind is that all methods in thejs object whether triggered by M ax messages or scheduled internally through tasks are executed at low priorityin theM ax scheduler T his means that while they will always execute and send data to M ax in thecorrect order they cannot berelied on for critically accuratetiming if the scheduler is overloaded with other actions Oncewe vedefined our Task tsk wetrigger it through thebang method to our js object function bang tsk cancel cancel the bounce if it s going already count 0 reset the number of bounces decay 1 0 reset the initial decay tsk interval glob starttime set the initial task int
192. datesfrom thepat trhub object by clicking on themessage boxes again Instead of recreating the pattr object wecould havesent our newly unbound pattr object abindto message with the nameof thenumber box setting the bindto attribute to a valid object 296 Tutorial 5 Patcher storage More Ways Than One N aminga M ax object and explicitly binding a pattr to it with its bindto attributeis only oneway to get apattr to refer to an objectin our patch Ithastheadvantage of requiring no connecting patch cords between thetwo objects allowing them to communicatefrom spatially disparate parts of the patcher e Open thesubpatch notes by double clicking thepatcher object containing it This subpatch contains eight pattr object bound number box objects that definethe four pitchesin our pat tern generator as well asthenumber of beats between each trigger of thepitch Thisisthepart of the patch that allows us to construct a polyrhythmic pattern off of a single counter object driven by themetro object in themain patcher Click on themessage boxes back in themain patcher with this window open and notice that the number box objects in the subpatch update correctly when you click on thedifferent patterns 5 Tw tez 3 attr mod_d pattr val _d prepend set lprepend set prepend set prepend set Clickingon themessagebox updatesthesubpatch values too In addition to binding objects to pattr through explicit
193. default M IDI synthesizer Thenum ber box attached to themetro object controlsthe speed of the generated pattern Click on the 294 Tutorial 5 Patcher storage colored message boxes to theright of the patch and notethat they changethevalueof that num ber box even though there areno patch cordsor send forward or receive objects in the patch start metro 125 pattr speed Ghindta temporam counter 0 47 makenote 100 250 la 62 not cS imin 1000 3 notes mod_b 4 notes mod c 6 durs imax 4000 s imod_b 5 notes mod_c 7 ro yal b 46 ot Clicking in a colored message box changesthemetro object stimevalue Thepattr object to the right of themetro object is controlling the value in thenumber box aboveit In the language of patcher storage we say that our pattr object is bound to thenumber box W hen wesend messages to that pattr object it will at all times refer to the data stored in thenumber box allowing usto ask the pattr object what thenumber is currently set to as well astell thepattr object to set thenumber to aspecific valueremotely 295 Tutorial 5 Patcher storage Our pattr object hasaname speed which isset by the object s argument and allows other pattr family objects to communicate with it The pattrhub object at the bottom of the patch can receive messages and forward them to any pattr objects in the patch By sending the message speed 125 to thepattrhub wearetell
194. dersofthatfolder are added to thesearch path as well e Maxsearchesfor files in a depth first order if thereis an entry called patches in the search path followed by one called examples M ax will search all the subfolders of patches before it looks at examples What sin the Cycling 74 folder You can add foldersto the Cycling 74 folder and they will automatically be included in the search path thenext timeyou launch M ax But some folders have specific names that cannot be changed without affecting the operation of the software 308 FI les H ow M ax handles Search Paths and Files Themax startup folder contains external objects that are loaded at startup You can add anything to thisfolder including patchers that you want loaded at startup N otethat the contents of any folders insidethemax startup folder will not be loaded at startup Generally the max startup folder contains user interface external objects that need to be shown in the patcher window s pal ette Theinitfolder also executes all of its items at startup but it is generally not used for external objects Instead it contains text files that configurehow M ax works You can add additional items to theinit folder but you shouldn t modify the existing files unless you know what you are doing Theinit folder ishandled beforethe max startup folder and itis also used with the runtime ver sion Themax startup folder is not loaded by theruntime version Thead fo
195. ding whether itrepeatsindefinitely and whether it begins executing immediately or at some pointin thefuturecan all bedetermined by your code In thisT utorial we ll look at how scheduling worksin JavaScript Along theway we ll look at two other important features of the avaScript implementation in M ax js object arguments which allow you to pass arguments directly to your JavaScript from the object box and Global objects which allow you to share data between internal js data structures and M ax Aswith theprevious avaScriptT utorials you may wish to review howto connect your M IDI syn thesizer equipmentin order to hear M IDI generated by theT utorial patch Tutorial 12 Sending and receiving M IDI notes explains how to configure and test these connections e Open thetutorial patch 50 avascript Globals pat You ll see four js objects all of which usethe same avaScript source file called globaltask js which is saved on disk in the same folder as theT utorial patch send a boune 3 repeat gt C stop stop bouwing 272 Tasks A rgumentsand Tutorial 50 Global O bjectsin JavaScript Click thebutton object at thetop of the patch labeled send a bounce Thefour js objects should begin to generatenumbers that are then sent downstream to your M IDI synthesizer output viathemakenote and noteout objects Additional button objects are connected to the left outlets of thejs objects to provide visual feedback on
196. dragthewindowtoa new location and onceyou hidethescroll bars you may beunableto getto theproper placein the patch to make some necessary changes A good safeguard against these problems isto connect a receive object to the inlet of thispatcher so that you can send it messages from another Patcher if necessary modtrack modtrack tracha pict trackh pict ete 2 82 127 247 129 2 254 247 A messagein onepatch can changethewindow characteristicsof another patch Window size 2 3 4 5 vinilo notitle window flags nigro window exec thispatcher Customizing the Menu Bar Thestandard way for auser to givecommandsto an application is by choosing a command from themenu bar In our application wewant menu commands for turning each track on or off for opening and closing the keyboard window and for sending an all notes off message out on all channels in casethere are stuck notes on thesynth W ith themenubar object you can add your own menusand commandsto themenu bar T heargu ment to menubar tellsithow many menus you wantthereto be T heremust befour menus T hese aretheH elp File Edit and W indows menus Then you typein ascript that explains to menubar whereyou want it to put additional menus and commands See menubar in the M ax Reference M anual for details on writing thescript In our case we want to change the first item in the H elp menu fromAbout M ax to About NoteM odifier and wewant to add anew menu called
197. e cific message box Turning off theimproviser clears all memories at once If wereally wanted to makethisimproviser patch into acompleted M ax program for someoneelse to use we would probably hide everything except the controls plus a few comments to tell the user what to do We left most things visible here so you could examine the patch Summary histo keeps an internal histogram of the numbers it has received W hen it receives a number in its left inlet it adds thenumber to its internal histogram sends a report of how many times it has received that number out theright outlet and sends thenumber itself out the left outlet The output of histo can besent directly to a table so that the frequency of occurrence of each number as reported by histo is stored asa valuein thetable You can open thegraphic window of thetable to seethe histogram A clear message in the left inlet of histo or table sets all values to 0 A bang in the left inlet of table causesit to send out an addressrather than avalue Theprobability of a specific address being sent out dependson thevalueit stores compared to theother valuesin thetable Thegreater thestored value of an address the more likely that address is to be sent out when a bang is received This fea ture of table allows you to useit for probability distributions By sending bang to atable that contains a histogram a frequency distribution of past numbers received from histo you can cause numbers
198. e Range 128 LJ Save Table With Patcher LJ Don t Save LJ Use Note Name Legend LJ Signed Values Options Saving the Values in a table Its important to understand the different options for saving atable so you don t lose numbers you vecarefully entered N ormally thevaluesyoustorein atable object arelost when you closethe Patcher window If you check Save Table with Patcher however thenumbersin thetable will be Saved as part of your Patcher document Then when you reopen the patch thetable will still con tain the numbers We have checked Save Table with Patcher for thistable so that our masterpiece will be preserved If you change the values in atable M ax will ask you if you want to save the changes you made to that table when you closethe Patcher window If you don t want M ax to ask you that every time you close the Patcher window check Don t Save D on t Save does not cause you to lose any values 126 Tutorial 32 Thetable object you have explicitly saved with Save with Patcher it just doesn t remind you to save any subsequent changes Any timethetable editing window isin theforeground you can save its contents to a separate file by choosingSavefrom the M ax menu Then whenever you wantto usethefilein a patch just cre ate a table object and typein that file name as an argument T he contents of the filewill be loaded into thetable object An example of a table that s stored as a separate file can be seen in P
199. e and message lookup at the outlet of Grate M essagelookup isa factor in computation speed and redrawinggraphicobjectstakestime If you renotrunningin Overdrivemode graphic objects slow you down becauseit takes timeto redraw the screen If you arein Overdrive they don t slow you down unless there s a message lookup involved Thereisno message lookup with number box objects for example because they handleonly numbers A message lookup is always performed on the output of message boxes Therefore it s better to typeanumber into an object box which createsan int object if you wantto produceaconstant value in an efficiency conscious program Of course you have to send bang to such an object whereas amessage box can be triggered by a variety of messagesin its inlet but if this can be arranged it s abit moreefficient than using a message box In the vast majority of cases the differ encein speed isnegligible but if enough instances like this are added up they can haveanotice able effect If you send thesame messagerepeatedly through thesame outlet of amessage box or other object whose outlets can send a variety of messages a message lookup is generally performed only the first timethe message is sent dueto afeature called outlet caching 342 Effi cI ency Issuesofprogrammingstyle Ifyou want to filter M IDI messages according to channel it s better to usea channel argument in theM IDI receiving objects than i
200. e can usethe hslider to providethe exponent ranging from 1 to 1 By selecting thehslider and choosing Get Info from the O bject menu we set the Slider Rangeto 201 values and the O ffset to 100 so that it sends out values from 100 to 100 In the expr object we divide that number by 100 and use the result as the exponent in the pow function to get 2x Asamatter of fact though in order to double the tempo we need to halvethe delta times and durations conversely to halve the tempo we need to double the delta times and durations This 216 Tutorial 44 a means that we want to show the user numbers ranging from 0 5 up to 2 0 but actually send num bers ranging from 2 0 down to 0 5 to r tempofactor in the p output subpatch T he value we want to send isthereciprocal of the value we want to show so we actually send oneover the tempo factor Although the seq object permits playback at different constant tempi the use of detonate shown here is the best way to vary continuously the playback tempo of aM IDI file or other stored sequence of note events Non Realtime Recording Therhythm of asequence recorded in detonate is determined by the event starting times given to detonate that is the delta time received for each note event rather than by the actual time detonate receives the events For this reason a sequence can be recorded over any period of time or even in asingleinstant Thisis demonstrated in the subpatch p An
201. e note information to different locations such as different drawing objects See Also frame Draw framed rectanglein graphics window graphic Open agraphics window oval Draw solid oval in graphics window pics Animation in graphics window pict Draw picturein graphics window rect Draw solid rectanglein graphics window ring Draw framed oval in graphics window Tutorial 43 Graphics in a patcher Graphics Overview of graphics windows and objects 199 Tutorial 43 Graphicsin a Patcher Animation in a Patcher Window In order for thisT utorial patch to function correctly you need to makesureQ uickT imeisinstalled in your system You should also disable M ax s Overdrive option to give more of the computer s attention to screen drawing activities In Tutorial 19 it was pointed out that you can customizetheuser interface of your patch by importing pictures from other programs In this chapter we demonstrate various ways you can change the contents of a Patcher window dynamically and even includeanimation right in the Patcher window In the patch 43 Graphics in a Patcher you see two new large object boxes in the bottom of the screen Oneistheobjectimoviefor playingaQ uickT imemoviein aPatcher window and theother is Icd for drawing lines shapes and text The patcher objects contain subpatches that control these objects Thereareafew other objectsthat areinvisibleto you in thispatch not becausethey havebeen hid den with the Hide On Lock
202. e number swapping more evident visually T hereis also an object for swapping floats called fswap not demonstrated here Lists Can Be Managed with Message Boxes Aswasshown in Tutorial 25 amessage box can also beused to isolateand rearrangeitemsin alist H ere area couple of examples showing possible uses of message boxes for selecting individual items from alist These two patches are equivalent akhough the First waar is more efficient The message object can isolate items in a list 117 Tutorial 30 Number groups An Automatic Accompanist Now that we have seen how thelist management objects work let s see how they are used in the example patch Elements of the list 40 59 80 are rearranged and delayed in different ways to send different messages to makenote at different times When the metro is turned on theentire list is sent to makenote immediately playing thenote 40 E1 with a velocity of 59 and a duration of 80ms The pitch and velocity are reversed by swap and delayed 500ms before being sent to makenote playing the note 59 B2 with a velocity of 40 One second after the metro was turned on the numbers are all sent to makenote as achord E1 B2 and G 4 with the velocity of 40 from the previous note At the same time the bang that was delayed by the del object retriggers the noteB2 from swap and it is delayed another 500ms before being played After a total of 2 seconds the entire process is repeated
203. e objects Our pictctrl based button will look likethis when it isidle L Yes it sjust a boring grey rectangle with a squareinsideit which turns yellow and red when you click it and look likethis when itis clicked Thepicturefilefor this pictctr would look likethis je Theimagefor theidlestateis on the left and theimage for theclicked stateison theright The appropriateimageisshown based on thestateofthecontrol and theother imageishidden W e ve included this file called boring button pct within thepicts folder insidethe patchesfolder By default this folder isin the M ax search path To usethis picturein aM ax patcher you would add anew pictctrl object to your patcher and then chooseGet I nfo from theO bject menu to open the object s Inspector Click theO pen button near the bottom of thepictctrl Inspector to choosethis picture file That s all you haveto do since the default mode of pictctrl is button mode Making Toggles N ext we ll look at apicturefilefor apictctrl that uses thetoggle mode Thepictctr object s toggle modeemulates push on push off buttonsfound on somehardware you push and releasethen onceto turn something on and push and releasethem again to turn thesamething off again They toggle between two states off and on In amoregeneral sense they togglebetween two val ues Zero and one Thestandard checkbox you re used to usingin dialog boxes works this way too 315 Interf
204. e queried pattr 299 Tutorial 5 Patcher storage e Changethevalueoftheselected pattr by changing thenumber box next to theubumenu Check to seethat thevalue changed by looking at thenumber box controlled by that pattr Select some other pattr objects and changetheir values familiarizing yourself with how the system allows you to query and set thestates of objects anywherein thepatch Summary Thepattr objects provide a powerful way to manage data from multiple objects in aM ax patch Thepattr object can maintain itsown internal information sentand returned through itsleftmost inlet and outlet or itcan bind to aM ax user interface object either by naming that object and using thepattr object s bindto attribute or by using the middle outlet of the pattr object to auto matically name and bind to an object Each pattr object can only bind to one object at atime The pattrhub object allows you to control the state of all pattr objects within a patch including those within subpatchers which can be accessed through ahierarchical notation system of successive patcher names separated by double colons followed by thenameof the appropriate pattr object By sending a get message followed by thenameof apattr with no intervening space you can query the state of any pattr object within a patch from apattrhub In thenext tutorial we ll look at two other objects in the pattr family which allow you to automati cally bind multiple M ax objects to th
205. e rectangles to be drawn in thegraphics window T he voicenumber is used to route messages to one of eight differ ent rect objects Shapesand picturesareanimated in agraphicswindow assprites objectsthat draw themselvesin a single place and erase themselves from their old location when they are drawn somewhere else Each shape drawing object such asrect controls a single sprite so multiple objects are needed if you want to display more than one shape at atime We chose eight rect objects as a reasonable number to take care of most keyboard playing styles Therect object requires an argument telling it which graphics window to draw in It has inlets for specifyingthecoordinates of itsfour corners left top right and bottom relativeto thetop left corner of the graphics window s drawing area It also has inlets for the sprites pen mode for alist of pen modes see oval in the M ax Reference M anual and color WeusetheincomingM IDI data to calculate these characteristics of the shapes to be drawn and we pack the numbers for all six inlets as alist combined with thevoicenumber at thebeginning of thelist so that wecan routean entire rectangle description to the appropriaterect object Weuseonly rect objects for drawing shapes in this patch but the inlets of theframe oval and ring objects are exactly the same Correlating Graphics and MIDI You can make any correspondence you like between M IDI data and graphics data The most straigh
206. e the patcher bouncing object The color messages for the button are received by ther tobpatcherl object and the offset messages are received by ther tobpatcher2 object W hat appears to be a comment next to the button is actually a menu in Label mode T he menu contains text in menu item 0 and nothingin menu item 1 Thus the text can behidden by thenumber 1 being received from the patcher bouncing object via ther tobpatcher3 object You ve already seen that when you click on the button text is displayed in the menu objects in the lower left corner of the Tutorial patch In the following example you can see how that s accom plished inside the bpatcher Theurn object is very similar to random when it receives a bang it outputs a random number from 0 to the number oneless than its argument Unlike random however urn keeps track of the num bers it has sent out and will not output the same number twice Theurn object is used any time you want to generate all the elements of a set without repetition In this case it outputs numbers from Oto 11 which have 1 added to them to select items 1 to 12 of the menu objects Sinceall three menu objects receive the same number their messages can be correlated and be guaranteed to be displayed together When urn has output all the possible numbers in its range it does not send any morenumbers and instead sends a bang out its right outlet T his bang can be used to send a clear message back to urn clea
207. e the sequenceis playing 149 Tutorial 35 seq and follow follow The follow object is very similar to seq in its ability to record M IDI data But whereas seq only records M IDI messages follow can also record a sequence of single numbers that are not in the form of complete M I DI messages such as the pitches from M IDI note ons follow can record M IDI messages or singlenumbers eg justnote on pitches A sequencecan be stored in follow by recording M IDI data by recording a series of single num bers by readingin a file with a read message or by typingin afilename argument Onceit has a stored sequence follow can use that sequence as a musical score and follow along while a per former playsthemusic Each timetheperformer playsapitch that matchesthenextnote oninthe stored sequence follow sends the pitch out its right outlet and sends the index number of that notes position in the sequence 1 2 3 etc out its left outlet The particular utility of this score following feature is that the index numbers can be used to trig ger other notes or any other process such as say turning on ametro when the 15th noteis matched When the incoming notes have gt matched the first 15 notes of the sequence the metro is started select 15 metro 125 How follow Follows W hen follow receives the message follow with a number argument it begins to look for incoming pitches which match the notes in the score starti
208. e ve defined for our object If a particular state dement is 0 off it draws acirclein the color defined by vmrgb If an elementis 1 on thecircleis drawn in the vfrgb color Theposition of the circlesis determined by thenumber of rows and columns and is based 285 Tutorial 51 D esigningU ser Interfaces in JavaScript on boundaries of our OpenGL world which are setto be between 1 0 and 1 0 on both axes i e themiddleof our jsui window in OpenGL coordinatesis 0 0 Note Thesizeof theworld is not limited to coordinatesin therange of 1 0 to 1 0 our default viewport merely sets us at the center of thescenewhosey rangeis 1 0 to 1 0 and whosex range isscaled based on theaspect ration of the object Because our object box happens to besquare our ranges arethesame on both axes Changing theviewport by manipulatingthe position of our virtual camera for example will change what coordinates are visiblein thejsui object s box Setting Parameters e IntheTutorial patch changethenumber box objects that set the rows and columns N ote that theobject will dynamically add up to eight rowsand columnsof circles based on thosevalues Look attherows and cols functionsin theJavaScript code N otethat they call a bang function after setting their variables rows change number of rows in jsui function rows val if arguments length nrows arguments 0 bang draw and refresh display co
209. e vertical offset values using a cosine wave of decreasing amplitude and increasing frequency Since a cosine wave can represent harmonic physical motion the absolute value of this diminishing cosine waveis used to imitatea hard bouncing object being affected by gravity The value of the cosine wave over the course of timeis calculated as the sine of 27 6 2832 a com plete 360 arc times an increasing frequency f1 77 5 1 progressing from 1H z to 5H z times time f1 310 with time being considered the progression of input numbers from 0 to 310 plusaphase offset of 7 1 5708 a90 phase offset to changethesinewaveinto acosinewave The amplitude of that cosine wave is scaled by a continuously changing amplitude 310 f1 310 88 Theentireresultisconverted to an intand itsabsolutevalueisused Themultiplication by 1 at the beginning of theequation istherebecauseweneed to movethecontents of thebpatcher with aver tical pixel value between 88 and Oin order to givetheappearanceofthebutton comingto restata 0 vertical offset 207 Tutorial 43 Graphics in a Patcher Accessing Text Messages e Closethe bouncing window O pen the bouncingbutton filein theM ax Tutorial folder and unlock the window to see the contents of the bouncing button bpatcher r tobpatchers thispatcher r tobpatcher counter 15 r tobpatchers Click here for an epigram gt You can seether objects that receive messages from insid
210. eceived A num ber received in therightinlet setsthedelay time in milliseconds to beapplied to all numbers sub sequently received in theleft inlet A clear message received in the left inlet erases any numbers currently being delayed in thepipe e Send somemorenumbersto theleft inlet of thepipein Patch 1 then quickly click on theword clear Any numbers not yet passed through thepipe areforgotten delay e Click on thebutton at thetop of Patch 2 Thebang is delayed for 2000 milliseconds before being sent out the outlet of the delay object 83 Tutorial 22 Delay lines Unlikepipe which can keep track of many numbersat atime delay can keep track of only onebang at atime If delay receives a new bang whileit s already delaying a bang theold bang is lost and the new bang is delayed instead e Send many bang messages to delay in quick succession Each bang received within 2 seconds of the previous oneerasesthe previous one so only the last bang gets sent out the output A number received in the right inlet of delay sets the delay timeto be applied to any bang subse quently received in theleftinlet A stop message received in the left inlet stops any bang currently being delayed e Send another bang to delay then quickly click on theword stop T hebang is not sent out Delaying Groups of Numbers A singlepipe object can actually delay several parallel streamsof numbers such aspitch velocity and channel information from not
211. ecial meaning to certain objects such astheword bang Commonly amessagewill consist of oneor morenumbers M ax distinguishes integer numbers from decimal numbers with afractional part Integer num bers are stored in M ax in adatatypecalled int and decimal numbers are stored in a data type called float M ost of thetime you won t really need to worry about this distinction in how numbers are stored because M ax will take care of it for you and will even convert an int into afloat or vice versa if it needs to for instance if a float is received by an object that expects to receive an int The main thing you need to know isthat when afloat isconverted to an int its fractional part isnot rounded off but is truncated The fractional part is just chopped off For example the number 6 799999 does not become it becomes 6 A message can also consist of several numbers separated by spaces which are all sent together Thisis known asalist A list can consist of both ints and floats You ll encounter lists in later chap ters of the Tutorial Number box If you want to show a number in a Patcher window use a number box There are two number box icons availablein the object palette one for showing ints and one for showing floats Number box int Number box float A number received in the inlet of anumber boxis displayed and passed on out theoutlet Thisisan effective object to use as a wiretap to see what is the most recent numbe
212. ect that has the nameas atyped in argument in a patcher Explode Label vi Send Note Offs Cancel 384 Detonate GraphiceditingofaM IDI sequence You can also choose to have edetonate suppress note off messages by deselecting the Send N ote Offs option W hen Send Note O ffs is checked edetonate uses the duration information of the note events to decide when to send a corresponding note off message to ticmd See Also detonate Graphic score of note events follow Comparealive performanceto a recorded performance Sequencing Recording and playing back M IDI performances Timeline Creating agraphic score of M ax messages Tutorial 44 Sequencing with detonate 385 D ebugging T ipsfor D ebuggingP atches Catching Your Own Bugs You might occasionally make mistakes when writing a program in M ax and you will then haveto figure out why your patch is not working as you intended In someinstances a bug might come from an error in the conceptual design of your program that is you might simply be mistaken about what you want the computer to do O ther bugs might be errors of syntax specific to M ax such as a misunderstanding of how an object works a mistakein predicting what messages an object will receive and send or a mistaken analysis of the order in which messages are being sent M ax doesitsbest to prevent you from making such syntactical errorsand provides various means of analyzing and debugging your programs
213. ects the first threenumbers and stores them in pack Then when you select an address by entering anumber in thenumber box the address and the accompanying chord notes are all sent to coll asa list for storage The number box 161 Tutorial 37 Data structures has been set to send only on mouse up so that you can useit as a slider to enter an address Other wise thechord would bestored in the address of every number you dragged through Flay a 3 note chord then choose a storage address with the Humber box e Click on theGgate to point its arrow to theright outlet e Play a3 notechord that you want to store in coll Play it asa 4 notechord first to hear it along with the address note that will eventually trigger it then play it asa 3 notechord to storeit in pack e Usethenumber box to select the address where you want to store your chord e Repeattheabovestepsuntil you havestored all thechordsyou want then click on Ggate again to direct the played pitches back to coll Play the address notes to hear the results Ifyou wantto saveyour new chords you must open thecoll object sT extwindowagain and choose SaveAs from the Filemenu Parsing the Data Structures in a coll Patch 2showshow coll can beused to storemessages with symbol addresses and it also showshow complex messages can be stored in coll and then parsed when they aresent out e Click on the different messages in Patch 2 fast n loud e Double click
214. ecutesthe most important part of our JavaScript code which is to run asingleiteration of our cool formula N otethat unlikeour bang function our msg_float function hasan argument stated within the parentheses as r This argument tells thejs object to assign the floating point value coming into our object s inlet to the variabler W ecan then usethis value in therest of the function N ote generally speaking thename of the function in JavaScript will correspond directly to the name of the message that you want to call it For example werespond to a bang message with the bang function in our js object A function called beep would respond to aM ax message that began with theword beep Sincefloatand intarereserved wordsin avaScript however weuse msg_float andmsg_int respectively to definethefunctions which respond to floats and ints Themain body of our float method sets x to theresult of themultiplication of r thevaluecoming in theinlet theold valueof x and theold value of x subtracted from 1 0 This statement KS PRE C1 eK isan exampleof a powerful featureof using an embedded programminglanguagewithin M ax To accomplish this with the expr object for example we would haveto take the output of the object and feed it back around to an inlet in such a way asto prevent a feedback loop in M ax probably through the useof anumber box 255 Tutorial 48 Basic avaScript e Doubleclick thesubpatcher p done_with_exprt
215. ed in an offset message to thispatcher The other bpatcher containing the button is just for fun to demonstrate an extreme example of animatingthecontents of abpatcher It also providesan opportunity to introducesomenew useful objects e Playthehigh C on your keyboard key 96 onceto trigger theanimation of abouncing button If the animation is extremely jerky or you don t hear any sound check to make surethat the Overdriveoption is disabled and the computer s output sound is turned on in the Sound con trol panel Although it appears that the button is moving you know by now that the effect is actually being achieved by continuously changing the offset of the subpatch insidethe bpatcher e Toseehowthisisachieved firstdouble click on thepatcher bouncing objectto seeits contents er select 36 expr ltabs int 310 11 310 88 Feint 28324 1 77 541 1 1 310 41 570813 Contentsofthepatcher bouncing object 206 Tutorial 43 Graphics in a Patcher When anote on from key 96 is received it turns on a metro which causes a counter to send out numbers from 0 to 310 at arate of 50 numbers per second select 36 These numbers are used to calculate the horizontal and vertical offset of the bpatcher subpatch which gets sent to athispatcher object in the bpatcher via thes tobpatcher2 object prepend offset tobpatchers Therather complicated equation in the expr object calculates th
216. ed but they will also be displayed as they go through Use of Humber boxes to verify that the piteh is being transposed properly T henumber box has several drawbacks as a debugging tool It can only show asingleint or float value not alist of different values Numbers may pass through it too fast for your eye to follow them If the same number passes through several times in a row you won t seeany changein the display And finally there is no way to see previous numbers once anew number is displayed Thecapture object solves all of these problems by handling both numbers and lists of numbers and by storing an arbitrary number of values at atime H ook up a capture object off to the side at the point where you want to look at some numbers then double click on its object box to open a 388 Deb U gg ng Tipsfor debugging patches text editing window which displays the numbers that have recently been received The default number of values capture holds is 512 but this size can be adjusted with atyped in argument You can double click on the capture objects to see the last 912 numbers received at each point Another potential advantage of capture isthat you can copy numbers from its editing window and paste them into another file or into a table Even though capture continues to receive numbers they do not automatically appear in theediting window so you haveto re open itseditingwindow each time you want to view any
217. ed out the right outlet send thenumber 1 out theright middle outlet and go back to the minimum butsometimeswemay want another condition to causeacertain result 344 Lo 0 DS W aysto perform repeated operations Intheexamplebelow abang issent to random every timethe letter ristyped on thecomputer skey board W hen random producesthenumber 0 asequenceis played select 114 Look for the letter r Choose a random number from to 4 If it s D start the sequence In this case wearen t counting thenumber of times something happens wemight haveto type theletterr any number of times beforea0 ischosen at random we rejustrepeating until a certain condition isme When the condition wearetesting for is met something should happen as aresult agate Opened aprocessstarted anoteplayed etc and iftherepetitionsarebeing supplied by atimed process such asa metro sending abang every 100 milliseconds therepetitions should be stopped metro 100 random 100 Choose a random number from Oto 99 every lims If it s O hang the Gewiteh nd turn off the metro Timed Repetition Sincetimeissuch an important factor in music you ll want to haverepeated actions occur ata specific speed The metro clocker and tempo objects are used for producing output at regular intervals bang in the case of metro numbers in the case of clocker and tempo Of course metro can also producea succession of numbers
218. efinition found in the M ax text file after the and beforethesemicolon To createthe button object shown above thescripting command is script new mybutton button 65 98 15 0 To createthenumber box shown above thescripting command is script new mynumber number 94 75 35 10 0 0 0 22 0 0 0 221 221 221 222 222 222000 234 Tutorial 46 Basic scripting W ithout going into great detail about each object it s impossibleto explain what all of thenum bers after thename or class of the object button number message etc mean In most cases the first two numbers refer to thehorizontal and vertical position relative to thetop left corner of the Patcher window N otethat if you haveset anew Origin for your Patcher window by choosing Set Origin from theV iew menu thescript new message doesn t take it into account when placing objects at window coordinates Thewidevariation in object creation messages means that the most effectiveway to createobjects using scripting is often to simply create the object desired using conventional means and then copy the message used to recreate it from a saved patch edited as text Once you havethe correct message for creating the object try varying someof the numbers to see what changes For reference when scanning M ax text files the most common object types are object type object newex object box message message box number number box flonum float number box button button toggle toggle bpatc
219. ein with a separate pair of inlets and outlets for each stream To makeapipe with morethan one outlet typein onenumber argument for each stream of num bers you want to delay plus an argument for the delay time Thelast argument is always the delay time right inlet is for delay time Argumentsseinitial valuefor each delay line Last argument isthedelay time Aswith most objects it s the left inlet that triggers the pipe W hen anumber is received in the left inlet it is delayed along with whatever number was most recently received in the other delay line inlets If no number has been received in the other inlets pipe uses the initial valuenamed in the argument asin the example above Thenumbers can also be received together as alist in theleft inlet with an additional number included at the end of thelist to specify the delay time Patch 3 shows apipe that delays three streams of numbers Thechannel and velocity values from notein arereceived and then thepitch valuetriggersthedelay of all threenumbers Thedelay time can bechanged by sending anew number to the right inlet of pipe 84 Tutorial 22 Delay lines e Tryplayingon your M IDI keyboard using different delay times random Each timetherandom object receives a bang in its left inlet it chooses a number at random and sendsthenumber outtheoutlet Therangeofnumbersfrom which random choosesis determined by typingin an argument or by sendinganumber in theright inl
220. elocity of the played note W hen itis1 sel triggersrandom to choose a random ornamentation interval which is added to the played noteand transmitted to the synth 108 Tutorial 28 Your argument A little bit of additional calculation is performed to maketherange of the ornamentation interval also depend on theplayed velocity W hen thevelocity isatamaximum therangeof theornamen tation will vary from 7 to 7 semitones up or down asmuch asaperfect fifth W hen thevelocity is at aminimum the ornamentation will only be0 unison For example when thevelocity is 127 a random number is chosen between 0 and 127 8 9 1 that is 14 That number will then have 127 8 9 2 subtracted from it i e 7 setting the range of possibleornamentations from 7 to 7 e Turn themetro 1000 object on and play on your MIDI keyboard with extreme changes of pitch and velocity N oticethat the ornamentation is wider and moredense when you play harder The effects of the ornamenter are most comprehensible when you play very sparsely on the keyboard When to Use Arguments Thereason for supplying values to an object isto modify some characteristic of the subpatch If you always want thesubpatch to do exactly thesamething you probably don tneed to changethe values inside itin any way If however you want your object to do something slightly differently dependingon somevalueit receives the valuewill haveto besupplied using an inlet or atyped in ar
221. emperature conversion In some instances the O ffset and M ultiplier features of theslider object can beused to perform an arithmetic operation 39 Tutorial 12 Sendingand RecelvingM IDI N otes Verify your MIDI Setup Now that you ve gotten a feel for how applications are constructed by connecting objects well begin using M IDI datain our patchesso that theexampleshaveamoredirect musical application M akesure that your M IDI equipment is connected properly If you have any doubts review the section of the Getting Started manual titled Setup and review the first page of the Tutorial 1 for a discussion of MIDI equipment and connections MIDI Objects Therearemany objects for transmitting and receiving data to and from your M IDI equipment Objects that receive M IDI messages from your synth don t receive that data in through their inlet TheirM IDI inputcomesdirectly from thevirtual M IDI ports seethePorts chapter in theGetting Started manual rather than from other M ax objects O bjects that transmit M IDI messages have no outlets since they transmit their messages out from M ax Themost basic M IDI objects aremidiin and midiout which receive and transmit raw M IDI data byte by byte without analyzing the M IDI messages at all M ore commonly though you will use morespecialized M 1D objects which filter theraw M IDI datacominginto M ax and output only theinformation you need For example thenotein object looksonly for M ID
222. en by 2 s then by 3 s and so on Even though these numbers quickly exceed the range of acceptable colors Icd keeps them within range automatically The fact that the color value is always being incremented by a different amount makes the color pattern of the circles constantly change 202 Tutorial 43 Graphicsin a Patcher Drawing a Chaotic Image e Toseeanother exampleof drawingin Icd play noteson your keyboard and or movethepitch bend wheel TheM IDI notes and pitchbends draw linesin thelcd As you draw more and more lines you will notice that they are filling in an isosceles triangle in an unpredictable but fairly coherent pattern Each line segment is drawn by moving the pen exactly half the distance from its current position towardsarandomly chosen corner of thetriangle T hisisoneof many interestingalgorithmic pat terns proposed by the mathematician Waclaw Sierpinski e Closethe concentrics window and double click on the patcher Sierpinski object to open it Thenote on messagesand speed limited pitchbend messagesareconverted to bang messages with ab object shorthand for bangbang and trigger oneof threerandom numbers which designate the coordinates of the corners of an isosceles triangle Thecurrent pen coordinates are subtracted from the coordinates of the chosen corner and that distanceis divided by 2 to determine the length of theline segment The length is added to the current pen location to determine the endpo
223. ence 0 cece cece cece cnet eens ee eeeeees 376 Table of Contents Debugging Tipsfor D eougging Patches Errors Explanation of Error M essages Messages to Max Controlling the M ax A pplication Copyright and Trademark Notices This manual is copyright 2000 2004 Cycling 74 M ax is copyright 1990 2004 Cycling 74 IRCA M l Institut de Recherche et Coordination Acoustique M usique Credits Original M ax Documentation Chris Dobrian M ax 4 3 Tutorials and Topics M anual David Zicarelli Gregory Taylor Jeremy Bernstein Adam Schabtach Richard Dudas and R Luke DuBois M ax 4 3 M anual page example patches R Luke DuBois Darwin Grosse Ben Nevile JoshuaKit Clayton and David Zicarelli Cover Design Lilli Wessling H art Graphic Design Gregory Taylor Introduction Tutorials and Topics in Max This manual provides a step by step course on how to program with M ax and acollection of dis cussionsof certain topicsuniqueto programming with M ax T hismanual isastep by step course designed to teach you all about M ax beginning with the simplest concepts and building upon those concepts as you learn new ones The courseis primarily for new M ax users who don t have prior programming experience but even if you havesome knowledge of programming the Tuto rial isagood way to learn M ax T he tutorials are designed to beread in order Each Tutorial is accompanied by a sample M ax pro gram document in the M ax
224. ending messages 237 showing objects 251 using the coll object 247 scroll bars hiding 229 scrolling text 211 search path 314 Segmented Patch Cords 70 Select 55 semicolon 295 in amessage 99 296 semicolon for remote messages 327 send 94 send and receive 94 sendapppath 330 Sending and receiving MIDI notes 41 sendinterval 329 seq 152 seq and follow 152 sequencer of M ax messages 188 sequencing 152 detonate 215 graphic editing 317 multi track 160 saving a sequence 153 singletrack 152 Set received in amessage object 97 292 received in aslider 30 Set Breakpoint 337 setboxcolor 327 settings of objects storing 171 shapes in agraphics window 200 sharp sign 111 Show On Lock 71 showglobal 330 showmenubar 330 Sierpinski W aclaw 208 sinewave drawing 178 size 330 of aloaded patch 281 of objects grow bar 19 Slider 29 multiplier 30 offset 30 setting the range of 29 413 Sliders and dials 49 special character 295 speed of computation 281 speedlim 61 split 76 sprite 200 priority 203 stack overflow 127 286 346 standalone application 225 271 Step 337 step recording 215 323 stopwatch patch 184 storing settings of objects 171 Storing numbers 81 stripnote 47 stuck notes avoiding 45 subpatch 102 105 argument to 110 292 in acollective 271 opening the window of 184 view contents of 209 swap 121 switch 64 sxformat 148 symbol received in amessage object 291 synchronizing 128 synthesizer switching sounds 60 170 sy
225. ending thedatafrom detonateto theM IDI output and onefor varyingthetempo of thenotes played by detonate p keycommands A subpatch such as p commands needs to communicateto all of the other subpatches which would cause a tangled net of patch cords So wehad to decidewhich arethedirectcommunicationsto be made viapatch cordswith inlets and outlets commandscomingin from themessage boxes that theuser clicks on and going out to thedetonate object and which are the indirect ones to be maderemotely via send and receive objects such assupplyingvaluesto other subpatchesor con trolling the flow of MIDI messages Receiving Commands from the User M ost patchesrequiresomekind of controllingcommand inputfrom theuser In thiscasewewant to choose one of three mutually exclusive actions record play and step through the recorded notes plus a fourth action off This is accomplished easily enough with four clickable com mandsin message boxes For quick access to the commands wecan make keyboard equivalents by looking for specific ASCII values and banging themessage boxes when the keys are pressed D etecting key presses on the computer s keyboard has already been demonstrated in Tutorial 20 The key detection is very simple and is avery specific task so it is easily encapsulated in the subpatch p keycommands the outlets of which are connected directly to the command message boxes 211 Tutorial 44 ea aera e Double click on the
226. ends Seed 56 Tutorial 17 Gates and Switches eee eat heer ee ae eyeeiter st aed enna rnrn 60 Tutorial 18 Test 3 Comparisonsand DECISIONS c cece cece eect ee ee teen enees 64 Tutorial 19 Screen Aesthetics n aunan aana 66 Tutorial 20 UsingtheComputer Keyboard ccc cece cece tees teen eens en eteneneenes 72 Tutorial 21 Storing Numbers ica wt te Gainer tamer eae 77 T torial22 Daday Lini nene r E a T E te A T wae eases 83 Tutorial 23 Test 4 Imitating a Performance unnsseunrnrrrrrrrrrerrnrrrrrrrrrrrne 87 Tutorial 24 send and receive l 90 Tutorial 25 M anaging M esses n n acetate sh tennessee deuce Acad oa Mera 92 Tutorial 26 T he pakcherO diet texto eevee tater en ate ahatalaeuelayedas 98 TUE Fal 27 OUD DO CCl vated see cenmeut setae aaa ene atest me bat EEE EA EEE 101 Tutorial 205 Your Argument sn erg Sas wera apaa a a rE EE same eee eae 106 Tutorial 29 Test 5 Probability Abstraction 0 ccc cece cece cece test eeeeeeeneanes 110 TUCK al 30 NOMBEGIOUNS viperina nepi ere e tener errr a 115 T t rial SE MONG TS oe werk desist Stren eset a ED acer goes ice edule ducting eka baie ste 120 T torial 32 Th table Q Der renn ks uh ah oak elt stated ah phat Thy beni ota 125 Tutorial 33 Probability Tables eaticict sat hacen eectitice Wnt Muateeiaed Waele whence ak bs 133 Table of Contents Tutorial 34 M anaging Raw MIDI Data cece ccc cece cece eee ee ee een eeeeaes 138 TUCO a
227. enus Thetext Click anywhereto continue blinkson and off Thisis really just amenu in Label mode that is being switched between two menu items O neitem contains thetext and theother is empty W hen thewindow is broughtto thefront an active object starts ametro which togglesthe menu back and forth between thetwo items once each second Click anywhere to continue Blinkingtext by switchingbetween itemsofa menuin Label mode Input and Output Ports Each of the track windows contains pop up menus for setting the desired input and output ports for MIDI note messages These pop up menus contain all the devicesin the current M IDI setup as retrieved by the midiinfo object and they are used to reset the port of notein noteout and ctlout objects loadbang midiinfo reports all devicesin the current M IDI setup 226 Tutorial 45 D esigningtheuser interface W hen the patch is loaded loadbang sendsanumber in theright inlet of onemidiinfo object to report theinput devices and sends a bang to the left inlet of another midiinfo object to report the output devices W hen midiinfo gets one of theseinputs it first sends out a clear message to empty themenu and then it sends out a series of append messages to add each of the appropriate device names to themenu T his configuration of objects isthe way to get information about the current M IDI setup into a patch T he desired port can then bechosen from thepop up menu W hen thePa
228. eparated by spaces e Click on the different message boxes and observe what is printed in the M ax window Thenumber of outlets route has depends on how many arguments aretyped in Each argumentis an identifier for an outlet and an additional outlet on the right sends out any messages not matched by route Likeselect route looks only for certain inputs and if thereisno match it passes the message on unchanged O neimportantdifferencebetween select and route isthat when select receivesamatch for oneofitsarguments itsendsabang outthecorrespondingoutlet W hen routereceivesamatch itsends out therest of themessage U nlessthereisno rest of the message in which caseit sends out bang Summary Thegate and Ggate objects receive messages in their right inlet and send the messages out only oneof their outlets depending on which outlet has been specified as open The switch and Gswitch objects receivemessagesin only oneoftheir inlets depending on which inlet hasbeen specified as open 62 Tutorial 17 Gates and switches Theroute object triesto match thefirst item of each incoming messageto oneof itsarguments Ifa match isfound route sends the rest of the message out the appropriate outlet if thereisno rest of message route sends a bang to the appropriate outlet If thereis no match the entire message is sent out the rightmost outlet Routing objects can be used to filter messages coming from many different objects pass
229. epattr system and store and recall sets of data from pattr objects See Also pattr patcher specific named data wrapper pattrhub make your pattr objects work for you Patcher Create asubpatch within a patch preset Store and recall the settings of other objects thispatcher Send messages to a patcher 300 Tutorial 53 M orePatcher Storage Introduction In thelast tutorial we learned how to usetheM ax pattr object to help you manage data either by binding to an object and referencing its data or by storing the data itself Thepattrhub object allows you to remotely query and set the data stored in pattr objects throughout a patcher hierar chy In thistutorial we ll look at two powerful extensionsto the pattr family autopattr which sim plifies the binding of large groups of objects to the pattr system and pattrstorage which provides an extensive system for storing and recalling states of data stored in multiplepattr objects Automatic Binding e Open thetutorial patch 53 autopattr Bindings pat and start the patch by clickingthetoggle box attached to themetro object in the upper left corner of the patch The patch creates an algo rithmic drawing based on the parameters stored in therslider object and number box objects attached to the patcher named drawing The message box that sends a bang to thereceive object named reset allows you to clear thelcd display and reset the counter objectsin the drawing subpatch The objec
230. er and over unnecessarily the output of amp amp is first sent to a change object The purpose of change is to filter out repetitions of a number The number received in the inlet is sent out the left outlet only if it is different from the preceding number When metro is turned on it sends the number 96 to makenote at the rate of 8 notes per second onceevery 125 ms Summary Relational operators lt lt gt and gt comparetwo numbers and report the result of the comparison by outputting 1 or 0 The amp and objects test whether their inputs are 0 or non zero making them useful for combining two comparisons into a single test Theselect object also known assel looks for certain numbers or symbols If the input matches what it is looking for it sends a bang out one of its outlets O therwise it passes the input out its right outlet Theresults of any of these comparisons can beused by the program to makea decision whether to trigger other objects 54 Tutori al 15 M aking decisions with comparisons Thechange objects passes on anumber received in itsinlet onlyifthenumber isdifferentfrom the preceding one See Also change Filter out repetitions of anumber select Select certain inputs pass the rest on lt Is less than comparison of two numbers lt Is less than or equal to comparison of two numbers Comparetwo numbers output 1 if they are equal l Comparetwo numbers output 1 if they
231. er multiplication See Also hslider Output numbers by moving aslider onscreen kslider Output numbers from a keyboard onscreen rslider Display the range between two values Slider Output numbers by moving aslider uslider Output numbers by moving aslider onscreen Tutorial 14 Sliders and dials 30 Tutorial 10 N umber Boxes Onscreen Controller bed Liber box can decimal as default be used as a slider bold no triangle In the previous chapter we saw that a slider graphically displays the numbers passing through it and can also send out numbers when you drag on it with the mouse The number box has these same Capabilities e Try dragging on the number box at the top of the Patcher window and you will see that it can be used as an onscreen controller much liketheslider Unliketheslider thenumber box can havean unlimited range You can producevirtually any num ber with thenumber box if you keep dragging Type In Numbers You can also type numbers into a number box from the computes keyboard e Click on thenumber box at the top of the screen without dragging Notice that thetrianglein the left edge of the number box becomes highlighted showing that it has been selected bo e Typethenumber 64 on the computer s keyboard The number will befollowed by an ellipsis indicating that the number has not yet been sent out the outlet e When you havefinished typing in the number you can send it out the outlet with a
232. er s There aretwo mechanisms for doing this first there are additional collective script messages that apply only to standalone applications and second the standalone object can be added to your main top level patcher to configure certain options appsplash Theword appsplash followed by a full pathnameof a PICT Macintosh or BM P Windows specifies the image to be used as a splash screen in place of the M ax about box appicon Theword appicon followed by afull pathname of aplatform specific icon file Windowsicon resource or M ac OS X icns resource specifies the icon to usefor the application The standalone Object Inspector To control other settings add the standalone object to your main top level patch and editing its parameters with its Inspector Since the standalone object and its settings are stored with your patch you do not need to specify thesettings each time you saveanew version of your standalone application 332 Col act ves Groupingfilestocreate a single application H ereis an overview of the various settings availablein thestandalone object s inspector Application Rae Code four characters OI Use Own Property List Resource Mac only hf Search for Files Not in the Application s Collective C Utilize Search Path in Preferences File Prete alae Max 4 Preferences File Name File Options hf Status Window isible at Startup LI Prevent Loadbang Defeating Behavior O Overdrive Enab
233. erated by thesliders to be used by our JavaScript code as well e Asyou createsliders notethat thectlin objects are automatically numbered to listen to incre menting M IDI controller numbers Asaresult aM IDI control surfacethat sends M IDI con tinuous control valueson multiple controller numbers will send values to multiple uslider objects Also notethan when you decrement thenumber of sliders theexcess objects will dis appear actually everything disappears and is recreated again If you set thenumber of slid ers to 0 all the script created objects including the funnel will be deleted from the patch Set thenumber of slidersto something modest such as 5 Changethe valuesin theuslider objects either by clicking on them or by usinga M IDI controller input Turn on themetro object by clickingthetoggle attached to it Thevaluesin theuslider objects should comeout of thejs object in turn creating asequence of MIDI notes T he multislider object to the right of the patch will give you a running display of the current note out of our sequencer set at its appropriate position in thesequence nan select 2 1 j autosurface is 261 Tutorial 49 Advanced scripting e Click thetoggle attached to the message box containing the message reverse 1 N otethat the order in which the uslider values are sequenced isnow backwards Our multislider display runs backwards as well In brief our js object dynamically creates a scalab
234. erstands a countseconds event W hen thetimeline messenger event countseconds start occurs theaction beginsto send integers out the left outlet of thetimeline object until thecountsec onds stop event occurs shart amd stop tiCmd countsecends s select start ee metro 1000 f Feset with each start counter Teatro responds to Pang wok skart count the segonds elapsed ist leftmost outlet So in this case the timeline sends symbols start and stop to ticmd and theaction itself sends ints the count of the number of elapsed seconds sincea start message was received to tiout which sends them out the outlet of the timeline object 374 TI mel Ine Creatinga graphicscoreofM ax messages Asyou haveseen atimelinecan becontrolled either with thebuttonsin thetimelinewindow or by messages received in theinlet of atimeline objectin a patch T hereis athird way that atimelinecan becontrolled itcan control itself An action patch can contain an object called thistimeline which sends messages back to thetimelinethat isusingthat action A messagereceived in theinlet of this timeline in an action is sent to thetimeiineitself allowing an action to control the timeline that is using it This enables the timeline to relocate its Own current time hut sending a soto event to this action tiCmd goto i The goto event will have an effect only if the space har ASCII 32 is being held d
235. ersto an object with morethan oneinlet the numbers are generally distributed to the object s inlets one number per inlet You will see other examples of thisin future chapters Summary M athematical calculations are performed by arithmetic operator objects and The oper ands are received in the two inlets but only the left inlet triggers output A bang or alist in the left inlet can also trigger output The operators send out an int unless they havea float argument in which case they send out a float M ost objectsin M ax aretriggered by input received in theleftinlet A listcan be received in the left inlet supplying values to morethan oneinlet at thesametime Arithmetic operators are essential for any algorithm involving numerical calculation Their use will beshown in future programs See Also expr Evaluate a mathematical expression Tutorial 38 expr and if 27 Tutorial 9 U singtheslider Onscreen Controller Fange of 128 Fange of 99 from Oto 127 9 Mhdtiphler of 50 Olfset of 100 Poe Range of 64 Range of 64 from to 63 Multiplier of 2 Offset of 1 woes Crom 100 to 5000 by 50s Clicking on a message box is oneway of sending a number through a patch cord A nother object the slider lets you send any of a whole range of numbers by dragging with the mouse Theslider object looks likethis in the palette slider W hen itis placed in thePatcher window itresemblesaslider on amixingconsole
236. erval tsk repeat start the bouncing W hen any of our js objects receive a bang they cancel any previously scheduled tsk tasks reset some variables that are relevant to the task function set an initial timing interval for the task and then start it going again e Starta bounce in theT utorial patch by clicking thebutton at thetop Click the message box labeled stop Thenotes should cease Our stop function will cancel our previously scheduled task simply by callingthecancel method to tsk function stop tsk cancel cancel our task The Task at Hand Our Task object onceset in motion by our bang method calls thefunction defined in its ini tial declaration 275 T asks A rgumentsand Tutorial 50 Global O bjectsin JavaScript e Perusethecodeforthemytask function mytask the scheduled task output number and reschedule next task function mytask if arguments callee task interval gt 5 keep bouncing outlet 0 note send a note value decay decay Math exp count dcoeff increment the decay variable arguments callee task interval arguments callee task inter val decay update the task interval else bounce interval is too small so consider it floored arguments callee task cancel cancel the task outlet 1 bang send a bang out the right outlet to sig nify that we re done bouncing Unliketheother functions
237. es arehelpful to you and to others who may useyour patch See Also funbuff Storex y pairs of numbers together Encapsulation H ow much should apatch do 105 Tutorial 28 YourArgument Supplying Initial Values to Your Abstraction M any M ax objects take arguments typed in after the object name to supply someinformation to theobject such asa starting value You can design your own object to get information from typed in arguments too The gamble Object In the Patcher window you can see several instances of an object called gamble It snotaM ax object it sa patch we created and saved in adocument named gamble e Doubleclick on thegamble 64 128 object in the right part of the Patcher window to seethe contents of thesubpatch ang to the number of the mum her play the winning choices out of possible odds of all possible choices choices convert any input to hang pick randomly from x possible numbers if it if less than this it ic a winner 1 if the choice H is a winner O if the choice ic a loser Thegamble object functions as an electronic gaming table W hen it receives abang in its left inlet or anything else since the button insidegamble converts all incoming messages to bang it chooses arandom number limited by the 2nd argument or the number received in theright inlet If therandom number islessthan acertain other number specified by the 1st argument or received in themiddleinlet gamb
238. es right into your Patcher window Thelcd object understands messages similar to basic Q uickD raw commands such as moveto lineto paintoval paintrect frameoval framerect etc so you can writea patch that paints automatically directly into its own Patcher window The messages move and moveto are used to place the cursor the messages color and penmode govern the way pixels will be painted and the other commands draw lines shapes or lettersin thelcd object Prowide changing horizontal coordinate Use pitehbend for and color value vertiral coordinate counter 255 lex 64 1411 72 a E prepend color prepernd limeto Drawing with thepitchbend wheel in thelcd 324 Overview of graphics Graphics windows and objects Thelcd object also responds to mouse movements in the manner of a color painting program W hen theuser clicks or drags within it Icd draws using the selected color based on the most recently received color message and also reports the coordinates of the mouse with respect to theupper left corner of thelcd outits outlet Thus thedrawing motionscan beused to generate music as well as demonstrated in the following example Dragging out of the Dragging in the led draws and plays motes ration 256 makenote 127 100 prepend color X VO Hote number and velocity come from the vertical and horizontal coordinates Drawingin Icd to play notes with the mou
239. ession in the other expr is a simple exponential mapping function Click on Ggate to point itto the right outlet Drag on the number box to select an exponent for the curve to be calculated by expr An exponent of 1 producesastraight line an exponent greater than 1 yields an exponential curve and an exponent less than 1 yields an inverse exponential curve e Click on the button to draw the curve in the Table window Try different exponent values and redraw the curve Large numbers of exponential calculations especially with a large exponent require fairly intensive processing for the computer to calculate For this reason it s often better to perform such calculations in advance and store the valuesin atable to be accessed later rather than to calculate the values on thefly whilethe computer is performing music Oncethecurveisstored in thetable itisread through by aline object each timeyou play anoteon your keyboard T he values are sent to bendout to be transmitted to the synth as pitch bend The speed with which line reads through thetable depends on the velocity of the note you play e Play long notes on your keyboard with widely varying velocities and listen to the different speeds with which line reads through the curvein thetable D raw different curves in thetable to hear their sonic effect 173 Tutorial 38 exprand if Summary Theexpr object takes a C like mathematical expression as its argument including changeable ar
240. et Therandom values will always be between 0 and oneless than theargument choose random wwoobers ranging from O to 127 Different uses of random numbers will be seen in thecourse of the Tutorial Using Delayed Triggers In Patch 4 themetro triggersrandom to send out a random number between 0 and 60 onceevery 720 milliseconds 36 is added to thenumber to bring it up into the rangeof a61 key MIDI key board and it isthen transmitted as a pitch to be played on thesynth Thebang from metro is also sent to thedel object whereit is delayed a certain time before being sent to random A new randomly chosen number isthen sent out so actually two notes are played every 720ms Therhythm between thetwo notes depends on thedelay timesent to theright inlet of del from thehslider choose a ramlom mu ber from O bo 60 fs 450 e Turnonthemetro and experiment with creating different rhythmsby changingthedelay time of the del object 85 Tutorial 22 Delay lines Summary A singlebang can be delayed for a specific amount of time by the delay object also called del If a second bang is received while the first bang is being delayed thefirst bang is forgotten and the sec ond bang isdelayed Numbers or lists can be delayed by the pipe object A pipe can delay a series of numbers and out put them later in thesamerhythm in which they were received A pipe can also delay alist of numbers or numbersreceived together such aspitch
241. et it to G2 The Rangeis specified as the number of octaves you want the kslider to have The Inspector also lets you select one of two sizes for kslider Largeor Small Range and Offset refer only to the numbers displayed by kslider or sent out its outlet by clicking and dragging with themouse N umbers received in the inlet of kslider areunaffected by the O ffset and are passed through unchanged Playing Parallel Chords Suppose you wanted kslider to play parallel major triads H ow would you go about it In addition to sendingthenumbers directly to theleftinlet of makenote you can also send them to two different objects One object can add 4 to the number raising the pitch a major third and theother can add 7 raisingthepitch aperfect fifth Thesetransposed pitchesarethen sent to makenote along with the original pitch e Tryityourself Unlock thePatcher window and createtwo new objectsjust abovemakenote Then connect the outlet of the number box to the inlets of the objects and connect the out lets of the objects to the left inlet of makenote pe z z NowlockthePatcher window and click on anoteofthekslider to hear theresults You can also try changing thenumbers you add with the objects to create other types of triads 4 Tutorial 14 Slidersand dials dial hslider and uslider In Patch 1 the velocity values are displayed by a slider object named uslider and the durations are supplied by adial Pat
242. ethecodefor thesliders function Thecommentsat thetop of each section explain what s happening at each step in the process sliders generates and binds the sliders in the max patch function sliders val done this before get rid of the funnel if arguments length bail if no arguments parse arguments a arguments 0 safety check for number of sliders if a lt 0 a 0 too few sliders set to 0 if a gt 128 a 128 too many sliders set to 128 out with the old if numsliders this patcher remove thefunnel if we ve for i 0 i lt numsliders it get rid of the ctlin and uslider objects using the old number of sliders this patcher remove controlin i this patcher remove thesliders i e in with the new numsliders a update our global number of sliders to the new value if numsliders thefunnel this patcher newdefault 300 300 funnel a make the funnel objects connect them to one another and to the funnel Yot us For k 0 k lt a k create the new ctlin and uslider controlin k this patcher newdefault 300 k 50 50 lin k l thesliders k this patcher newdefault 300 k 50 100 lider this patcher connect controlin k 0 thesliders k 0 this patcher connect thesliders k 0 thefunnel k 264 Tutorial 49 Advanced scripting connect new objects to this js objec
243. examples H ereisthe description of what quantile does quantile In leftinlet Theword quantile followed by anumber multiplies the number by thesum of all the valuesin thetable This result isthen divided by 2 32 768 Then table sends out the address at which thesum of all valuesup to that address is greater than or equal to the result Astheargument of the quantile message progresses from 0 to 32 768 each addressin thetable occupies aportion quantile of the 0 to 32 768 range proportional to the weight given by the valuestored atthat address Repeated quantile messages using random numberscauseeach address to besent out with a frequency roughly proportional to the valueat that address The fquantile message T hefquantile message does the same thing as the quantile message but it accepts a float argument between 0 and 1 Rather than require you to calculate the proportion of 32 768 that represents a fraction of thetablelength fquantile allows you to specify it as adecimal number For example fquantile 0 5 isthe same as quantile 16384 and fquantile 1 0 is equivalent to quantile 32768 Examples Supposewehaveatable of 128 numbers all set to 10 Untitled H erearetheresults of some quantile messages on this table N otethat the total sum is 128 10 or 1280 357 Quantile Usinga table for probability distribution quantileQ A Iways causes an output of 0 quantile 16384 Returnstheindex up to which thesum of
244. f M ax messages Each track in thesequenceisaM ax Patcher referred to asan action patch and theeventsthat are placed in each track are messages which will besent to specific objects in the action patch at thedesired moment And just asa pre recorded sequence or imported M IDI file can beread into aseq object and played from within a patcher a prerecorded timelinecan beread into atimeline object and played back from within a patcher e Inorder for thetimelinein this Tutorial to work correctly you should makesurethat the Overdrivesettingin theO ptionsmenu is checked e When you open theexample patch for this chapter of theT utorial two other windows are Opened as well although they may behidden behind the Patcher window Oneisthegraphic editor window for atimeline and theother isaQuickT imemoviewindow Note If you don t havethe QuickTime extension installed in your system the QuickT imemovie window will not appear and you should disregard references to the moviewhen reading this chapter of the M ax Tutorial This patch hastwo main components On theright sideof thewindow is aseq object containinga prerecorded sequence which was read in automatically from afile named tutorial41 sc It can be controlled by messages sent from the menu object or by messages received remotely from a send seqcmd object somewhereelse N oticethat any message sent to seq also sends abang to midi flush to turn off any notes that may beheld at the moment w
245. f any key that is released In PartC of thepatch wemeasurethetimethat akey isheld down by measuring thetime between arrival of anumber sent by key and anumber sent by keyup timer In PartC weusesel objectsto look for specific ASCII values Both sel objectslook for thenumber 116 which isthekeyt W echosetasamnemonicfor tempo W hen tis pressed down abang issent to theleft inlet of atimer object W hen thekey tis released abang issent to the right inlet of the timer Thetimer object outputs the number of milliseconds between a bang received in itsleftinletand a bang received in its right inlet N ote timer isan exception to the general ruleof the left inlet being theonethattriggersoutput In this case abang in the left inlet starts thetiming process but theright inlet isthe one that causes the elapsed timeto be sent out Using Duration to Set Tempo This patch uses the duration that a key is held down to set the speed of a metronome When the key tisreleased abang issent to theright outlet of timer which reports the time that the key was held down W eused the message from key to start the timer Thetimeissentto the right inlet of metro and is also divided by 2 and sent to theright inlet of makenote In this way the duration of the notes played will be the amount of time between notes giving astaccato effect 15 Tutorial 20 U singthe computer keyboard Therelease of thet key also starts the metro N oticethat t
246. f arguments length bail if no arguments parse arguments a arguments 0 safety check for number of sliders if a lt 0 a 0 too few sliders set to 0 if a gt 128 a 128 too many sliders set to 128 out with the old if numsliders this patcher remove thefunnel if we ve done this before get rid of the funnel for i 0 i lt numsliders it get rid of the ctlin and uslider objects using the old number of sliders this patcher remove controlin i this patcher remove thesliders i in with the new numsliders a update our global number of sliders to the new value if numsliders thefunnel this patcher newdefault 300 300 funnel a make the funnel For k 0 k lt a k create the new ctlin and uslider objects connect them to one another and to the funnel controlin k this patcher newdefault 300 k 50 50 ctlin k l thesliders k this patcher newdefault 300 k 50 100 uslider this patcher connect controlin k 0 thesliders k 0 this patcher connect thesliders k 0 thefunnel k connect new objects to this js object s inlet ourself this box assign a Maxobj to our js object if numsliders this patcher connect thefunnel 0 ourself 0 connect the funnel to us else complain about arguments post sliders message needs arguments post 270 Tutorial 49 Adv
247. f asingle argument telling how many outlets there are the number of outlets atrigger object has depends on how many arguments are typed in Each argument in atrigger specifies what the output of an outlet will be i for int f for float b for bang or for list not shown in the example e Click on the message box 90 marked C The print objects receive the number in right to left order depending on their position e Click on the message box 90 marked D Each outlet of thetrigger has been assigned to send an int so thenumber 90 will besent out each outlet in order from right to left e Click on the message box 90 marked E In this example each outlet has been assigned to send something different Theright outlet sends an int the middle outlet sends a float and the left outlet sends a bang Note The names of bangbang and trigger can be shortened to b and t asin example E M ax will still understand these object names Summary An object with multiple outlets sends messages out its outlets in order from right to left W hen multiple patch cords are connected to a single outlet the messages are sent in right to left order depending on the position of the receiving objects If the receiving objects are perfectly aligned vertically the order is bottom to top When the bangbang object receives any message it sends a bang out each outlet W hen trigger receives anumber alist or abang it converts the message into the type assigned
248. f the velocity is not 0 In this way it filters out note off messages and passes only note on messages Thisis useful if you want to get data only when akey on your keyboard is pressed down but not when the key is released For example you might want to usea pitch value from the keyboard to send anumber to someobjectin M ax but you wouldn twantto recelivethenumber both from the key being pressed and from the key being released flush Theflush object is another object for generating note off messages Unlike makenote however it does not generatethem automatically after a certain duration Instead flush keeps track of the notes that have passed through it W hen it receives a bang in its left inlet it provides note offs for any notes that have not yet been turned off 44 Tutorial 13 Sending and receiving MIDI notes Both flush and stripnote receive velocity values in the right inlet and pitch valuesin the left inlet and passthesametype of values out the outlets T hey aretriggered by a pitch valuereceived in the left inlet and use the velocity value that was most recently received in theright inlet Both objects can also receive the pitch and velocity values together as alist in the left inlet e Play afew noteson your MIDI keyboard You can see that stripnote passes only thenote on messages and suppresses the note offs T he note ons get passed through flush and are received by the print objects A flush object will also pass
249. f you wish to add additional virtual ports to your M IDI system you can usethe same message box technique described aboveto send the createoutport and createinport messages SM createoutport lt portname gt lt drivername gt 45M createinport lt portname gt lt drivername gt whereportnameis thename you assign to the port and drivernameis thedriver to be used cur rently only CoreM IDI issupported For example the following two messages SM createoutport myvirtualport CoreM IDI 45M createinport myvirtualport CoreMIDI Would createa virtual M IDI input and output port each named myvirtualport These virtual ports arenot saved as part of the M ax M SP setup so they will haveto berecreated each time you restart M ax Examples Space har Bpare har used to hidelshow me nu bar Sec A E and fill sereen with TogEdge a graphe window Open close max hidemenubar max showmenubar graphic Arimation 0 1 640 460 Control thebehavior of M ax from within a patch max clean max guit 406 M essages tO M ax ControllingtheM ax application See Also pcontrol Open and closesubwindowswithin a patcher thispatcher Send messagesto a patcher 407 Symbols 54 26 l 54 in amessage box 96 291 in an object box 292 26 amp amp 56 26 26 Numerics Ox hexadecimal indicator 296 A About numbers 14 absolute path 255 abstraction 105 accompaniment patch 123 156 accum 83 act
250. fall behind the music theanimation automatically skips frames to keep up U ser interface objects such as slider objects do thistoo by theway Alltheobjectsthat draw graphics are external objects and additional graphicsobjectscan bewrit ten by C programmers Each object that draws in a graphics window isaspriteassociated with a particular window Sprites allow objectsto passin front of or behind each other accordingto apri oritynumber H igher numbered spritesaredrawn in front of lower numbered sprites Thepriority number of these graphics objects can be changed with the priority message Graphics In a Graphics Window You need agraphic object in your patch to open agraphics window Onceyou haveapatch con taining a graphic object you need oneor moredrawing objects T herearethree basic objects included with M ax for drawing in a graphics window members of the oval family oval rect ring and frame which draw shapesand pict which displaysPICT files T hefirst argument of any draw ing object isthename of thegraphic object whose window will be used for drawing The graphic object need not exist at thetimethedrawing object iscreated but thedrawing object will do noth ing until thereisa valid and visible graphics window with thesamename specified as drawing object s argument H ereisasimplepatch that draws a black oval within therectangular pixel area 50 50 100 100in the graphics window titled Display when the user clicks on the butt
251. falls in a gap between existing addresses it finds thenext smallest address and outputs the value at that address Thebag object stores a collection of numbers without any addresses N umbers can beadded to and deleted from thebag and abang in itsinlet sends out all of thecurrently stored numbers Complex Data Structures Thepreset object is also akind of array but each address in its array contains the settings of other user interfaceobjectsin aPatcher window W hen an addressnumber isreceived in preset sinlet or when you click on oneof the preset object s buttons the settings of those objects are changed to the values stored in thepreset In this way every user interface object in the same window asthe preset object has its settings stored and recalled Alternatively you can connect the outlet of a pre 348 Data St ru ct ures Waysofstoringdatain M ax set to some of the window s user interface objects making them the only ones affected by that pre set Thecoll object short for collection storesnumbers symbols and lists A singleaddressin coll can beeither anumber or asymbol You can also modify stored datain acoll with messages such as sub which changesasingleitem in astored location or merge which appends additional datato aloca tion You can also access an individual item in alist stored in acoll with thenth message A coll object is useful for recording and playing back a score that has lists of times pi
252. ff or to open and shut agate See Also mousefilter Pass numbers only when the mouse button isup mousestate Report the status and location of the mouse 178 Tutorial 40 A utomaticA ctions Opening a Subpatch Window Your programs can automatically open and close Patcher windows and detect when a window is opened or closed triggering someaction e When youopentheexamplepatch for thischapter of theT utorial thewindow of thesubpatch object stopwatch is opened immediately and begins to display thetime elapsed sincethe win dow was opened Asweexplained earlier in Tutorial 26 a patcher object will open automatically if you leaveits subpatch window open when you savethe Patcher that contains it A subpatch saved as a separate file however such as stopwatch will always have its window closed when the main patch is Opened To open the stopwatch window which would normally not beopen weused two objects load bang and pcontrol loadbang and closebang Theloadbang object sends out abang oncewhen thePatcher that containsitisopened loaded into memory Thisallowsyou to trigger certain actionsimmediatey when apatcher isloaded You can useloadbang to open gate and switch objects which areclosed when a patch isopened start tim ing objects such asmetro or supply initial number values to an object such asnumber box Thecounterpart to loadbang is closebang not shown here which can be used to trigger actions such as turning off
253. g is sent to the message box containing thenumber 40 that message is sent to the print object and A 40 is printed in the M ax window This illustrates the right to left order in which bang messages are sent from the outlet of button to other objects and also illustrates that theorder of messages continuesdown thelineuntil no more objects are triggered in this case until the print object does its job then goes back to thenext patch cord coming out of the button and the next bang is sent bangbang Thebangbang object sends abang out each of its outlets when it receives any message Thenumber of outlets is specified by the typed in argument Theorder in which the messages are sent out the outlets is still right to left the rightmost outlet sends first and the leftmost outlet sends last 23 Tutorial 7 Right to left order e Click on the button marked B and you will see that when an object such as bangbang has morethan one outlet messages are sent out the outlets in right to left order When multiple patch cords are connected to a single outlet asin examplesA and C messages are sent to the receiving objects in order of their right to left position but when a single object has morethan one outlet asin examples B D and E messages are sent out the outlets in right to left order regardless of the destination trigger Thetrigger object is very similar to bangbang but deals with numbers as well as bang messages Instead o
254. ge at the beginning of another receive Receive messages without patch cords send Send messages without patch cords Arguments and changeable arguments to objects Punctuation Special characters in objects and messages 97 Tutorial 26 Thepatcher O bject Subpatches A Patcher program can contain other Patcher programs as subpatches T hepatcher object lets you create a patch within a patch A new Patcher window openswhen you typepatcherinto an object box You can edit apatch in the newly opened subpatch window then when you saveyour mainpatch thesubpatch issaved as part of thesame document If thesubpatch window isopen when thedocumentis saved it will be automatically reopened thenext time you open the document Thesubpatch window can be brought to theforeground at any time by double clicking on thepatcher object You can even nest patcher objects that is put patcher objects within patcher objects within patcher objects etc A patcher object can be given an argument specifying the nameto beshown at thetop of the sub patch window If thereisno argument the window isnamed sub patch Thenameis enclosed in brackets to show that it s part of another patch This patch contains two patcher objects named modwheel and keyboard and their contents are shown in thesubpatch windows For aesthetic reasons wehavehidden most of the objectsin the subpatches with H ideOn Lock but wewill examinethem shortly e Playafewnoteson your M IDI key
255. get the same effect as we did using clocker W ith counter however the numbers can be easily placed in the desired range 0 to 127 in this case without a multiplication being performed each time M ul tiplication takes longer for a computer to perform than incrementing acount Themetro isset to aspeed of 47msso that theprogression from 0 to 127 will be completed in 5 969 seconds as closeas possible to 6 seconds using this method line Theline object also outputs numbers in alinear ramp from some starting valueto some ending valueover aspecific period of time T hefirst argument sets thestarting valueand thesecond argu ment sets the grain the time interval at which numbers will be sent out W hen atimeperiod is received in its middle inlet and an ending value is received in its left inlet line outputs numbers in alinear progression from the starting value to the ending value over the specified time period Thenumbersin theinlets can also be received together as alist in the left inlet If a number is received byitselfin theleftinlet without atime period being received at thesametime line jumps to and outputs thenew valueimmediately A starting valuecan besent to line without triggering any output by sending it aset message the word set followed by anumber Set starting valueto 0 then progressto 127 in 6 seconds outputting a number every 47ms 121 Tutorial 31 Usngtmes Stack Overflow H ave you ever been in the pos
256. ghout aM ax patch hierarchy For example with pattr you can control thestate of objects inside of patcher and bpatcher objects all from thetop level of the patch e Wecan storeany typeof data used by any typeof object including data simply stored insidea pattr itself without any other objects involved e Wecan usepattr objects to remotely set and query the state of objects controlled by thepattr system from anywherewithin the patch e Thepattrobjectsstoregroupsof settings as XM L files allowingusto easily read and edit saved data outside of M ax e Thepattrobjectscan recall thestateof objectsin aspecific order avoidingdifficulties with for example therecallingof atoggle object that startsa process beforeall thevariablesarein place for the process to function correctly e Notonlycan westorethestatesof many objectsunder asingleaddress wecan also interpolate between these states allowing for aseamless crossfade between multiple settings e Thepattr objects feature a high level interface for viewing and managing the current state of controlled objects and the states that have been saved In thistutorial we ll look at some of the basic features of pattr and pattrhub showing how the objects can be used to communicate remotely with objects anywherein aM ax patch Object Binding e Open thetutorial patch 52 pattr Basics pat and turn on themetro object with thetoggle object boxlabeled start You should hear somenotes out of your
257. gt gt pri lt 00 00 00 00 08 06 araok Diena 00 00 00 00 0400 00 08 00 001200 oD Erz ado a v v 1 E PrintThreeThings printsymbol ELLI Ser Cs ee One Inch Four Seconds 364 TI mel Ine Creatinga graphicscoreofM ax messages To place a single number as an event you will usethe int and float editors which look just likethe number box object 8 0 8 Untitled 144 44 0 D Db b gt pei 00 00 00 00 02 17 oe Disa 00 00 00 00 04 00 00 08 00 00 12 00 00160 Yv v 1 PrintThree Select Event in Track 1 EIGy Once you have placed an event in thetrack you can edit the event s contents change the message it will send to theticmd object or drag it to anew location in thetrack changethetimeat which its message will be sent You can also cut or copy events from onetrack and paste then into another track provided they are appropriate events to be placed in that other track If the action contains different ticmd objects as is the case with our example PrintThreeThings action then atrack can contain different kinds of event editors In the following example when thetimelineis played it will send an int 60 to be printed at time 0 a float 3 14 to be printed at time 1000 milliseconds 1 second and the symbol start to be printed at time 2000 2 seconds 8608 Untitled 144 44 0 a Db bb th 00 00 00 i 00 11 02 Trak Display 00 00 00 00 04 00 00
258. gument There sno hard and fast rule about when to supply values to asubpatch by using arguments and when to supply values via inlets Generally speaking if you will just want to supply the valueonce it can bemost easily given as an argument but if you want to changethe value of a single object often you will need to usean inlet Onesolution isto makeboth ways possible aswehavedonewith gamble Thearguments areused to set initial values insidethe subpatch but the values can be changed by numbers received in the middle and right outlets Summary You can enable your object to accept information from typed in arguments by including change able argumentsin the subpatch A changeable argument of 1 in thesubpatch is replaced by the first typed in argument in the object box 2 is replaced by the second argument and so on If no argument istyped into the object box the changeable argument is set to 0 Your patch can makeweighted random probabilistic decisions by choosing arandom number then testing to see if thenumber meets certain conditions See Also Arguments and changeable arguments to objects 109 Tutorial 29 Test5 ProbabilityA bstraction Create Your Own Abstraction Thisis an exercisein thecreation and use of your own abstraction one object that passes on a certain percentage of the bang messages it receives then usethat object in a patch First wemust create the object 1 Create an object called passpct th
259. guments W hen a number is received in the left inlet expr replaces the changeable arguments evaluates the expression and sends out the result Theif object evaluates a conditional statement in theform if x istruethen output y else output z Theconditional statement can contain changeable arguments The output can be sent to receive objects instead of out the outlet Both if and expr arecapableof combiningthecomputationsof several Patcher objectsinto asingle object which is usually morememory efficient The expression in the argument of expr can contain C math functions such as pow and sin and can also contain relational operators For details on the operators and functions you can use look under expr in the M ax Reference M anual See Also expr Evaluate a mathematical expression if Conditional statement in if then else form 174 Tutorial 39 M ouseControl mousefilter There may betimes when you want to see the exact value that is going to besent out of aslider or dial before it is actually sent The mousefilter object helps you do that It receives numbers in its inlet but passes them on only when the mouse button is up Consider the example below but send only when the mouse button is released Whileyou are dragging on thehslider the numbers are sent to thenumber box for display but mousefilter does not pass then on because the mouse button is down When you release the mouse button thelast number is sent
260. h 108 outlet Assistance description 100 outlet caching 342 outlet object 99 Overdrive 81 342 P pack 116 palette of graphic editing tools 129 panic command 227 PassPct patch 110 Paste Picture 68 patch cord receive messages without 90 segmented or straight 66 send messages without 90 wiretap in 388 patcher object 98 argument to 352 paths 403 pcontrol 179 354 periodicity 81 pgmin 57 pgmout 57 picture clicking on 69 in a patch 68 pipe 83 pitch bend 14 bit xbendin 144 14 bit xbendout 144 bendin 56 bendout 56 controlled with velocity 56 pitch velocity grid 175 pointer 142 poly 195 port changing dynamically 138 specifying in Max 138 port setting for MIDI objects 227 pound sign 355 pow function 216 preempt 403 prepend 93 preset 166 348 print 9 as a debugging tool 389 priority of a sprite 197 419 probability 107 133 357 Probability tables 133 program change pgmin 57 pgmout 57 punctuation in a message object 355 in an object 355 Q quantile 357 QuickTime movie 183 200 369 quit 403 R r90 random 85 random note patch 85 random number weighted randomness 357 without repetitions 208 range of a slider 28 receive 90 recorder patch 155 recording in non real time 217 381 rect 195 recursion 104 122 refresh 403 relational operators 51 relative path 310 repeat actions 344 repeated note patch 79 168 Resume 399 rhythm analyzing 134 creating with delay 85 118 Right to left order 23 ritard fol
261. h of thewindowsin this appli cation contains ahidden thispatcher object to set the window up with exactly the desired size location and characteristics W hen the application is opened aloadbang object triggers the mes Sages to each thispatcher to set up each window Hide the zoom box inthe tile bar lide the scroll bars set the corner coordinates the nemet allthree commands window flags nozoom window flags nogror window size 2 40 508 80 window exec thispatcher Set the characteristics size and location of a window with thispatcher 223 Tutorial 45 D esigningtheuser interface Thewindowsfor thefour tracks arefour instances of the same subpatch a separate file called modtrack Yet each instance can have aunique picture and aunique window placement because that information is supplied to thefpic object and thethispatcher object as arguments to the modtrack object in the main patch modtrack modtrack tracka pict trackbh pict ete 282 127 247 129 82 254 247 Argumentsto modtrack in themain patch provideuniqueattributesfor each modtrack subpatch window size 2 3 4 5 window motitle window flags mogrow window exec thispatcher Some caution is advised when changing windows with thispatcher For example it s possibleto give window size coordinates that are entirely outside the bounds of your screen making it invisi bleto you but still open Also onceyou hidethetitlebar you can no longer
262. hang causes the stored the nuiber is added bo bang causes the shored and is also sent out mher to be sent out Tut nothing is sent out 1 her to be sent out 79 Tutorial 21 Storingnumbers An initial valueto be stored in accum can betyped in asan argument If thereisno argument the object initially stores thenumber 0 The value stored in accum is normally an int but if the typed in argument contains a decimal point accum stores a float M ultiplication in accum is always done with floats even if the stored number isan int Using accum Theaccum object is most useful for storing a valuethat you wish to changeoften by adding to itor multiplying it For example you may want to continually increment a number by adding some amount to it over and over Thesecond patch in the Patcher window shows an example of incre menting e Click on thetoggle to start themetro N oticehow the pitch velocity and duration values sent to makenote changecontinually Theamount of changeis directly related to thenumbers being added or multiplied in the accum objects Each time theaccum objects receive a bang from themetro they send their stored values to mak enote and they also trigger message boxes which add somenumber back into thestored valueor multiply the stored value by some amount N ote U ntil now we ve usually triggered themessage box with abang but it can also betriggered with a number Theresult isthat theaccum objects changetheir own stored value
263. happensto thetog gle and thenumber box Thetoggle object can recavea number or abang in its inlet If the number isnon zero toggle will show an X and send out the number If the number is0 the box will be blank and 0 is sent out the outlet Thetoggle expects to receive an int so when it receives a float it converts it to int That is why thenumber 0 9 is understood as 0 by toggle Thetoggle alternately sendsout thevalues 1 and 0 each timeitisclicked with themouseor receives abang in itsinlet W hen it receivesabang or amouseclick it reverses itsstateand sends out thenew value This distinction between zero and non zero is M ax s way of turning things on and off or distinguishing between true and false e Thus you can useatoggle as an on off switch In our example themetro object can beturned on and off by clicking on thetoggle Try it This works because metro starts when it receives a non zero number like 1 and stops when it receives a 0 19 Tutorial 5 toggle and comment comment The dotted box in the palette to the right of the message box is a comment Comment A comment has no effect on the functioning of a program It s simply a way of putting text into a Patcher window T hemain reasons to add a comment are 1 To label objects in the patch such as on off switch 2 Togiveinstructionsto the user such as Click here 3 To explain the way a program works or how a particular item in a program fun
264. has been played by the per former The velocity and the pitch are sent immediately to the synth T he rhythm is translated back into millisecondsby multiplyingit by 30 then itissent to themetro to set anew speed and to makenote to set anew duration for the subsequent note rhyth pitch wel metro FEO PassPot 35 Theresulting improvisation bears some resemblance to what you played on your M IDI key board because it uses the same pitches velocities and rhythms but the improviser patch recom bines these parameters randomly Because of the PassPct object the improviser also rests about 5 of thetime The User Interface Wehad to decidehow much control the performer should haveover the improvising patch and how the control should be implemented We decided that the improviser would beturned on by moving the modulation whea to any position other than 0 or by clicking on a toggle object W ealso wanted theperformer to beableto erasetheimproviser smemory either all parametersor just one parameter so that its memory can befilled with new information This requires sending clear messages to the histo and table objects to set all their values to 0 We decided to have all mouse controls located in a separate window and have automatic on off control from the mod wheel as well We have hidden most of the objects and patch cordsin the controls subpatch window so if you want to seehow themain patch communicates with thesu
265. hat address out its left outlet The contents of a coll object can bestored as part of the patch that contains it or as a separate file A filecan be loaded into acoll object with the read message or by typing the filenamein as an argument 168 Tutorial 37 Data structures Themessagesent out by coll can be parsed by other objectsto select particular items from the data structure Also individual data items can besent out or altered by certain commandsin a coll object s inlet The menu object isa pop up menu in a Patcher window and the menu items commands can be any kind of message The menu may be used for selecting commands with the mouse and or for displaying messages W hen amenu command is selected either with themouseor by amenu item number received in the inlet menu displays the command optionally sends the stored message outtheright outlet and always sends the item number out the left outlet Thepreset object lets you storethe settings of every other user interface object in the window at a certain pointin time then recall those settings at some later time If the left outlet of preset is con nected with patch cords to certain objects preset stores and recallsthe settings of only those objects Thecontentsof atable can also beremembered by preset butthetable must beconnected to preset The preset object can store and recall up to 256 different collections of the settings of all user interface objects See Also
266. hat refer to thectlin objectsin our patch theslides An array of M axobjsthat refer to theuslider objectsin our patch thefunne A M axobj which references thefunnel object in our patch N otethat thereisno differencein JavaScript variable declaration with relation to thetype of value that the variable stores integers floats strings and objects areall considered equivalent when declaring avariable Similarly arrays are defined simply to refer to quantity of information rather than what typeof information will bestored in them Similarly JavaScript will correctly type vari ables following a calculation e g x 4 2 will set the variablex to 2 an integer whereas iS 3 2 will set the variablex to 1 5 afloating point value V ariables can switch types dynamically throughout their existence T hisuseof untyped variables only exists within the avaScriptenviron ment however which is why westill need independent methods msg_int and msg_float to deal with differently typed numbers comingin from M ax 263 Tutorial 49 Advanced scripting W ewill use various properties of the M axobj object classto perform our scripting all of which is accomplished by asinglefunction our sliders method Arguments Agreements Our js object responds to thesliders message via a method contained in the sliders function remember that the function name typically matches the message you want to trigger that func tion e Examin
267. he new M ax collective format is cross platform however included external objects are not cross platform so if your collective uses any non standard external you will have to supply these as separate files for each platform If you are going be giving M acintosh created collectives to Windows XP users you are strongly encouraged to use the mxf file extension Otherwise it won t be possible for Windows XP users to open the files Building a Standalone Application W hen you click on theBuild button in theBuild Collective A pplication dialog youarepresented with a standard SaveAs dialog allowing you to name your collective and save it to disk In the lower part of this dialog you are presented with a Format menu By default this menu is set to save aM ax Collectivefile butif you wantto saveyour patch asastandaloneapplication all you need to do isselect Application Macintosh or APPL Files exe Windows from this menu It s as easy as that M ax will automatically combine your collective with the M axM SP Runtime appli cation and save the result as a single file which appears and functions a standalone application requiringneither M axnor M axM SP Runtime If you havemultipleversionsofM axM SP Runtime in your M ax folder M ax will usethe application that has the word Runtime in its name and the most recent creation date 330 Groupingfilestocreate Col ect Ives a single application Windows Standalone Format A s
268. he expr and if objects In these objects the must be followed immediately by the letter i f ors indicating whether the argument isto be replaced by an int afloat or a symbol symbol OF if 2 lt 1 0 then set si expr powi Cl O bf275 3 7 i1 PERIERE Ifthemessagereceived in theinlet doesnot match thetypeof thechangeableargument for exam ple ifan intisreceived to replacea f argument the object will try to convert theinput to the proper type T heobject cannot convert symbolsto numbers however so an error message will be printed if asymbol isreceived to replacea i or f argument Other objectsin which a argument iSappropriateincludesxformat and vexpr in object and message boxes W hen you areediting a patcher which will beused asa subpatch within another Patcher message boxes and most object boxesin thesubpatch can begiven a changeable argument by typingin a pound sign and anumber for example 1 asan argument Then when thesubpatch is used insideanother Patcher an argument typed into the object box in the Patcher replaces the argu ment insidethesubpatch In thisway patcher objects and your own objects can requiretyped in arguments to supply them with information justasmany M ax objectsdo A symbol such as 1 isachangeableargument and isreolaced by whatever number or symbol you typein as the corresponding argument when you usethe patch as an object inside another patch A changeable argument cannot be
269. he patch does 48 Tutorial 14 Slidersand dials Analyzing Patch 2 e Play ascaleon your M IDI keyboard Notice that as you play you also hear a scale of short notes moving in the opposite direction When you play notes on thesynth the pitch and velocity are sent through stripnote which filters out all the note off messages passing only thenote ons Then 33 is subtracted from the velocity keydown velocity of a very soft note Lelider limits the numbers and alls 1 so that the velocity is always greater than e Play some notes very very softly so that your key down velocity is less than 33 This results in negativenumbers coming out of the minus object Thehslider limits the num bers it receives in its inlet so that none of them isless than 0 and the hslider object s O ffset of 1 ensures that all velocities are at least 1 The reduced velocity finally arrives in the middle inlet of makenote and is stored there Next the pitch value comes out of stripnote and has 127 subtracted from it This means that pitches which usually range from 0 up to 127 will range from 127 up to 0 If you havea 61 note keyboard your pitches range from 36 up to 96 and subtracting 127 from them causes them to rangefrom 91 up to 31 Thisnumber isthen sent to an abs object which sends out the absolute non negative value of whatever number it receives So now instead of your pitches ranging from 91 up to 31 they rangefrom 91 do
270. he scheduler Thetempo object isametronomethatlets you specify timingin traditional musical terms of beats per minuteand beat divisions Itsendsoutadifferent number for every pulsein ameasure so each pulsenumber can trigger a different action 123 Tutorial 31 Usnatines The metro line clocker and tempo objects can be synchronized to an external timing source such as a sequencer or atime code generator See Also clocker Output the elapsed time at regular intervals counter Count the bang messages received output the count line Output numbersin aramp from one valueto another metro Send a bang at regular intervals setclock Control the clock speed of timing objects remotely tempo Output numbers at ametronomic tempo timein Report time from external timecode source 124 Tutorial 32 Thetable O bject An Indexed Array of Numbers In Tutorial 27 weintroduced the funbuff object for storing an indexed array of numbers Number values are stored with an index number address then when you want to recall a value you just specify theaddress whereitisstored T hetable object storesand recallsnumberssimilarly buthas many more features Graphic Editing The most notable feature of the table object is that it allows you view and edit the stored numbers in agraphic editing window e Check All Windows Activein the Options menu so that you can view table objects and click in the Patcher window at thesametime e Double click on thetab
271. he state outlet 0 clear clear the router or matrix downstream bang draw and refresh display frgb change foreground clicked sphere color function frgb r g b vfrgb 0 r 255 vfrgb 1 g 255 vfrgb 2 b 255 vmrgb 0 0 5 vfrgb 0O vbrgb 0 vmrgb 1 0 5 vfrgb 1l vbrgb 1 vmrgb 2 0 5 vfrgb 2 vbrgb 2 bang draw and refresh display brgb change background color function brgb r g b vbrgb 0 r 255 vbrgb 1 g 255 vbrgb 2 b 255 vmrgb 0 0 5 vfrgb 0 vbrgb 0 vmrgb 1 0 5 vfrgb 1l vbrgb 1 vmrgb 2 0 5 vfrgb 2 vbrgb 2 bang draw and refresh display onresize deal with a resized jsui box Function onresize w h bang draw and refresh display onresize local 1 make function private to prevent triggering from Max 291 D esigningU ser Interf Tutorial 51 esigning 7 tae onclick deal with mouse click event function onclick x y worldx sketch screentoworld x y 0 worldy sketch screentoworld x y 1 colwidth 2 ncols width of a column in world coordinates rowheight 2 nrows width of a row in world coordinates x_ click Math floor worldxt 1l colwidth which column we clicked y_click Math floor 1 worldy rowheight which row we clicked state x_click y_click state x_click y_click flip the state of the clicked
272. hebang message in the left inlet of atable hasa special function Instead of sending out a stored value thetable sends out an address The probability of aparticular address being sent out isin direct proportion to its stored value as compared to the other values in thetable If the value stored in an address is greater than in other addresses that address is more likely to be sent out when abang is received For amore detailed description of the effect of bang on atable look under Quantilein this manual Thisfeatureofthetable makesit perfect for storing aprobability distribution Each addresscan be assigned a different likelihood of being sent out when a bang is received If the values in thetable have been supplied by histo as described above the likelihood of a number being sent out of the table depends on how many times it was received by histo With this combination you can base the probability of a number s occurrence on the past history of how many timesit hasalready occurred Themoreit has occurred in thepast the morelikely it isto occur in thefuture 133 Tutorial 33 Probability tables Keeping a History of What is Played In our example patch we have used histo and table to keep afrequency distribution of the pitches and velocitiesof notes played on thesynth T hesetable objects storehistogramsof thepitchesand velocities played Thestripnote object is very important here because without it note off messages would causeeach
273. hel nspector window menu will send thetext of theitem outthe right outlet If you check the Auto Size option the width of the menu will automatically adjust according to the length of the text in menu commands e Doubleclick on the patcher menu_ examples object to open the subpatch window Weve hidden many of the objects in this subpatch to give you a visual idea of how menus may be used to enhance the user interface of a patcher program e Record and play back a M IDI sequence using the Sequencer menu in the left part of the win dow stop s Start delay 0 read print It s easier to useasinglemenu than it isto click on abunch of message boxes it smoreaestheti cally pleasing and it has the advantage of displaying the most recent command e Unlock the menu_ examples window to see how the menu is connected in the patch Sequencer Theright outlet sends the actual text messages to seq In theother patch themenu has a dual purposeof sending values and displaying the values it receives Ifyou havealot of different sounds availableon your synth you may notbeableto mem orizeall the program change numbers A menu can help you associate the name of a sound the text of a menu item with a program change value the item number W hen you select a menu item with the mouse theitem number is sent to pgmout as a program change value Just as the names of sounds are specific to a given synthesizer so may bethenum ber
274. hen seq is stopped or restarted Begue mwer p J Seq tutoriald sc b miditlvush A bang received by midiflush turns off any held notes 1 183 Tutorial 4 TimelineofM ax messages On the left sideof thewindow is atimeline object containing a prerecorded timeline which was read in automatically from afilenamedtutorial41 ti T heother objectsaround itarefor sendingit control messages or for handling its output W e ll comeback to this portion of the patch presently The Timeline Window e Toseethecontents of thetimeline bringthetimeline graphic editor window to thefore ground by double clicking on thetimeline object or by choosing tutorial41 ti from the W in dows menu Thistimelinehastwo tracks T rack 1 containseventsto besent to an action patch track 2 contains only markers which mark specific important pointsin thetimeline T hefirst track contains avari ety of event editors each of which contains oneor more events messages to besent to thetrack s action patch at aspecific time Theaction patch containsticmd objects which receivethese mes sages as if they had comein through inlets and usethem in thepatch For example theevent edi tor containing the text seqcontrol start is called a messenger it sends the message start to aticmd object named seqcontrol in the action patch Theticmd is connected to aseq object which will receivethe start message from ticmd So four seconds after thetimeline begins
275. her Punctuation Special characters in objects and messages 354 Punctuation Special Charactersin O bjectsand M essages Punctuation in Object Boxes M any non alphabetic characters havea special meaning in M ax when included in objects and messages M any characters are object namesin their own right signifying arithmetic relational and bitwise operators for numerical calculations These object names are arithmetic operators lt lt gt gt amp 4 amp relational operators and amp lt lt gt gt bitwise operators Seethe descriptions for these objects at the end of the O bjects section for moreinformation Thedollar sign and the pound sign are used in object boxes to indicate changeable argu ments A changeable argument is replaced by a value supplied either in the inlet in the case of or astyped in arguments to a patch that contains the object in the case of TheArguments chapter has detailed information about and in object boxes Thesemicolon indicates the end of a message and isnot allowed in object boxes Semicolons are also away of forcing a carriage return in a comment object except in two byte compatible mode Thesemicolon indicates the end of alinein text files containing the contents of coll mtr and seq objects and in text files which contain ascript for thelib object A comma isgenerally another character to avoid usingin object boxes but may beu
276. her audio or MIDI support This means that Search for M issing Files is now of limited usefulness for standalones 337 Groupingfilestocreate Col ect Ives a single application Theformer role of Search for M issing Files was for testing the collective to make sure you were including all of the files you need With the advent of thesupport folder and its ability to contain audio and M IDI files this testing role now falls mainly to the Utilize Search Path option Utilize Search Path specifically allows you to check whether any files in the Cycling 74 folder are needed by your standalone application if after turning off Utilize Search Path you see errors indicating no such object or can tfind files intheM axwindow you know youaren tproperlyincludingall of the supporting files you need A tip that may help sort out path problems Put max paths in a message box in your patch so you can click on itwhen thestandaloneisrunning T hepaths messageprintsoutthefilepathscurrently in use See Also Encapsulation How much should apatch do standalone Configure Parameters for a StandaloneA pplication 338 Encapsulation H ow M uch Should a Patch D 0 Complex Patches Onceyou start writing relatively complicated programs try to build them out of different parts rather than oneenormous tangled patch in a single Patcher window T heway to do thisisto divide your program up into different Patcher files The different files can
277. her bpatcher Armed with thisinformation wecan useobject creation scriptingto automatethetask of creating of multipleinstances of asimilar object For instance let susethenumber box object wesaw above The object definition string for the specific number box was number 94 75 35 10 0 0 0 22 0 0 0 221 221 221 222 222 222 0 0 0 W ebegin by stripping off the and the semicolon W ealso know that thefirst and second num bersfollowingtheword numberrefer to theobject shorizontal and vertical positionsin thePatcher 235 Tutorial 46 Basic scripting window Thefollowing patch illustrates an approach to mass producing a flock of number box objects sprinti imynumbox pack O 0 objname script new 3 number 1 2 35 10000 22 0 0 0 221 Bel Sel Bee Bee eee oo 0 thispatcher M aking 15 number box objects automatically H ereit theresult an orderly series of 15 number box objects uniquely named from Omynumbox to 14mynumbox Dj S o 236 Tutorial 46 Basic scripting W hy would you want to do this Let s expand the patch le Lmyrmbox pack O 0 objname sprintf Bircy pack 0 objame script new 3 number 1 2 35 10 oO 0 0 22 0 0 0 221 221 Bel 222 BEE BEE Oo Oo oO script new 3 newex i 2 48 id4dd4isoe r 3 thispatcher M akingnumber box and receive objects N ow we ve added theability to create receive objects to the patch by copying the lineth
278. hetimer is triggered beforethe metro so that the time values will arrivein metro and makenote beforemetro is started Themetro sends the pitch 96 to makenote until the period key istyped to stop the metro e Hold thet key down for various lengths of time and listen to thechangein thetempo of the metro and the duration of thenotes Typethe period key to stop the metro Summary Thekey objectreportstheA SCII codeof keystyped on thecomputer skeyboard T hekeyup object reports theASCI codeof keys when they arereleased Thenumkey object interprets ASCII received from key or keyup and reports any numerical values being typed ASCII values from key or keyup can beused to send commandsto a patch opening agate or trig geringprocesses A relational operator such assel can be used to look for certain keys being typed Thesplit object looks for numbers within acertain range If an incoming number is within range itissent out the left outlet otherwiseit issent out the right outlet Theelapsed time between any two events can bereported with timer Thetimer is started by abang received in its left inlet and the elapsed timeis sent out when abang is received in therright inlet See Also key Report keystyped on the computer s keyboard keyup Report keys released on the computer s keyboard numkey Interpret numbers typed on thecomputer s keyboard split Look for arange of numbers timer Report elapsed time between two events 76 T
279. hetrack just under thetrack name 144 44 0 I pe ml lt E o Teak Display 2000 7000 Si 1 tulorishagtion 0 aeetrolatirt goto tag Locate T Event 0 bend int 0 efune int 0 etable flint scalespeed float 1000 scalespeed float 2000 scalespeed float 5000 scalespeed float 4000 scalespeed float 4001 seqcontrol start goton bang movie movie note 6812012000 L E O j 8002 note 641270 1 2000 8002 mote 59 120 1 2000 8002 note 52 120 1 2000 8002 etable int From thislist of events you can seethat thegotoA bang event occursjust beforetheother events You know from examining the action patch that this will causethe timelineto relocate to the SectionA marker located at time 4000 provided that themod wheel of thesynth isin the0 position The timeline will continueto loop from 4000 to 8000 until the mod wheel has been moved to anew position W hen thegotoA bang event is reached and the mod wheel isin a non zero position the message will not go out the left outlet of the Ggate in theaction so thetimelinewill be permitted to con tinueon its normal course It will then send thenote events from the messenger objects an emovie event astart message that is transmitted directly to the movie object in the action and an etable full of bend events a series of ints sent out one by one At time 10000 it will send agoto 187 Tutorial 41 TimdineofM axmessages 8001 event thusrelocating itself to that pointi
280. heuser interface object menu is essentially an array of symbols W hen thenumber of a menu item is received in theinlet the item textis displayed and can also sent out the right outlet if desired Item text is changed with a setitem message W hen you choosea menu item with the mouse you are specifying a symbol causing thesymbol s address to be sent out the left outlet Control record delay 0 wr ite read print Items can be accessed by index number or with the mouse See Also coll Store and edit a collection of different messages funbuff Store x y pairs of numbers together menu Pop up menu to display and send commands message Send any message table Storeand graphically edit an array of numbers Tables Graphic editing window for creating table files 350 Arguments and ChangeableA rgumentsto O bjects in a message box Thedollar sign isaspecial character which can be used in amessage box to indicatea change ableargument W hen themessage box contains a and a number in therange 1 9 such as 2 as oneof its arguments that argument will be replaced by the corresponding argument in the incoming message before the message box sends out its own message Freset Ho 1 print Received In the left example above the 1 argument in themessage box is replaced by thenumber received in theinlet in this case9 beforethe messages sent out Themessage printed in theM ax window will read Received Preset No 9
281. hows a configuration to record four separatetracks of MIDI note data separately then playthem all back together number box objects let you specify thetrack you want to record on and if you wish atrack to listen to while you are recording When you chooseatrack to record the gate opens that outlet to let the record message and the note data go only to that track e Set theopen gate outlet to 1 to record on track 1 and click on the record message Play some noteson your M IDI keyboard W hen you arefinished recording click theplay messageto hear what you have recorded 155 Tutorial 36 M ulti track sequencing e Nowopen gateoutlet 2 and enter the number 1 in thenumber box at the top of the patch so that you can listen to track 1 while you record track 2 sim ws ye play amp record track to listen to while recording When you click the simul sync button the message play 1 will be sent to the left inlet of mtr and the message record will besent to the inlet of track 2 e Click thebutton and record track 2 W hen you have finished click on play to hear both tracks You can continuein this manner to record all four tracks If there is some delay between the time you click play and the time the sequence starts to play it s because you took sometime to begin recording notes after you clicked record To eliminate this delay and cause the first event in mtr to begin at time 0 click the message first 0 Notice tha
282. i lt ncols i iterate through the columns for j 0 j lt nrows j iterate through the rows moveto i colstep colstep 2 1 0 1 0 j rowstep rowstep 2 0 move the drawing point if state iJ j set on color glcolor vfrgb 0 vfrgb 1 vfrgb 2 vfrgb 3 else set off color midway between vbrgb and vfrgb glcolor vmrgb 0 vmrgb 1 vmrgb 2 vmrgb 3 circle 0 7 Math max nrows ncols draw the circle bang draw and refresh display function bang draw refresh rows change number of rows in jsui function rows val if arguments length nrows arguments 0 bang draw and refresh display cols change number of columns is jsui function cols val if arguments length ncols arguments 0 bang draw and refresh display 290 D esigningU ser Interf Tutorial 51 esigning tte list update our state to respond to a change from Max function list v if arguments length 3 bail if incorrect number of argu ments state arguments 0 arguments 1 arguments 2 update our internal state based on the list outlet 0 arguments 0 arguments 1 arguments 2 echo the list out the outlet bang draw and refresh display clear wipe the state clean function clear for i 0 i lt ncols itt for j 0 j lt nrows j state i j 0 wipe t
283. ictures and geometric shapes of color onscreen using integers to state the position size priority foreground background level and color of the images Since both sounds and images are described with integers it s a simple matter to write patches that correlate the two In order to display animated graphics you need to include at least onegraphic object in your patch Each graphic object opens a graphics window automatically when the patch is opened e When you open the example patch for this chapter of the Tutorial a graphics window titled is opened by the graphic object molosse open CORDES left top right bottom graphic Atomation 0 20 Siz 342 window Date The first argument gives the graphics window a name which appears in the title bar of the graph ics window In this case the graphics window stitle bar is hidden behind the menu bar Other objects will usethe window name to refer to the window in which they are going to draw The four number arguments following the window name specify the four corners of thedrawing area of the window top left right and bottom in terms of pixels from the top left corner of your screen W ehavemadethewindow precisely fill a9 screen leavingtwenty pixelsatthetop for the menu bar Thegraphic object can receive open and wclose messages T he wclose message is particularly helpful in acaselikethis wheretheclosebox ishidden behind themenu bar O bviously theopen message is neces
284. iles We use sc at the end of thenameto identify the file as a musical score If you check Save as Text in the dialog box when you save the file you can view the sequencein a Text window by choosing Open As Text from the Filemenu Otherwise thefileis stored asa standard M IDI file Toload asaved fileinto aseq object send theread message to seq and astandard O pen Document dialog box will appear so you can choosethefileyou want to load in If theread messageisfollowed by afilenameargument seq loadsthatfileautomatically provided it slocated whereM ax can find it You can set seq to load a file automatically when the patch is opened by typing thenameof the sequence file as an argument to the seq object e Click on the message containing read bourr e sc to load in a brief melodic excerpt from a Bach bourr ein E minor Send astart messageto seq to hear the melody Processing a MIDI Sequence The output of seq isin the form of individual bytes of M IDI messages and can be transmitted directly to the synth with midiout It can also be sent to midiparse however and the parsed data can then be processed by other M ax objects before it is sent to the synth 148 Tutorial 35 seq and follow In the patcher transpose object we parse the raw M IDI data received from seq transpose the pitch of the notes by some amount then reformat the M IDI messages and send then to midiout e Double click on the patcher transpose object to see its
285. in that window sends out 1 When thewindow made inactive isno longer in front active sends out0 W ehave used active to turn aclocker object on automatically whenever thewindow isbroughtto theforeground clocker 100 Theactive object sends out anumber onlyin responseto achangein itsforeground background status and isnot affected by thesetting of All Windows Active W hen All Windows Activeis checked you can click in any window without first bringingitto theforeground butonly thefore ground window istechnically active W hen you moveawindow to thebackground an active object in that window sends out 0 but when you closethe window active does not send a0 because it s not actually being sent to the background Even though thestopwatch object doesn t get any messages from other objects it needs to havean inlet so that it can be controlled with pcontrol You can includeadummy inlet object in a patch for this purpose e Closethestopwatch patch and open the filenamed dicktrack Turn off thetoggle in the click track window and unlock thewindow to seeits hidden objects You can see that it contains an active object to turn on tempo whenever the window is madeactive Thenumbers0 to 3 sent out by tempo are multiplied and transposed to play the pitches C5 E5 G and C6 181 Tutor al 40 Automaticactions Thedicktrack object has oneinlet for receiving new tempo values but this same inlet can be used by pcontrol in themain patch to con
286. in this patch W hy can t the pitches be combined with velocitiesrightin noteout T hey can butthis would leave open thepossibility that some note off messages would not bereceived by thesynth Consider the following scenario Suppose you type the letter y to transpose pitches down an octave Then you play and hold down thenote C3 60 on your M IDI keyboard This will causethe note 48 to besent to noteout Before you releasethenote60 on your keyboard you typez to transposepitchesup an octave Now when you release the note 60 anote off for note 72 will be sent to thesynth Thenote 48 will not get turned off 73 Tutorial 20 U singthecomputer keyboard To solvethis potential problem thenotesaresent first to aflush object Each timeanumber is received in the left inlet of gate abang is also sent to flush to turn off any held notes In this way note offs are always provided for any notes that are being held when thestatus of gate is changed vate nium her W henever a gate control number isreceived a bang is sent to flush Of course if you never play notes and give commands at the same time this precaution is unnec essary AS a general rule though whenever you areprocessing notes for example transposing them it s good to makesurethat anote on message is always followed by a corresponding note off message Changing thetransposition closing agate etc whileanoteis being played can often causethissort of problem numkey P
287. in thismanual T hejsui object bases most of its graphicslanguageon OpenGL functions thespecifics of which are beyond thescopeofthisT utorial TheO penGL Redbook isthestandard referencefor thesefunc tions An onlineversion is available at http www opengl org documentation red_book_1 0 TheOpenGL API supported by jsui is contained in an object called jsui sketch T hisobject under stands most O penG L commands and symbolic constants Converting between OpenGL code e g asgiveninC in the Redbook codeexamples and sketch methodsand propertiesfor jsui Jav aScript codeis quite straightforward if you observethe following guidelines e AllOpenGL commands are lowercase in thejsui sketch object e g glColor becomes sketch glcolor e OpenGL symbolic constants in addition to being lowercase losetheir GL_ prefix so that GL_CLIP_PLANE1becomesclip_planel forexample A number of higher level drawing and shape commands are available which may speed up user interface development Thejsui sketch referencefound in the avascript in M ax manual and the help patch for thejsui object contain lists of these commands 281 D esigningU ser Interf Tutorial 51 esigning D jsui in Action e Open thetutorial patch 51 avascriptUI pat You will see ajsui object containing agrid of light red circles against a green background Clicking on acircleinside the object will changethe circle s color to adarker red Clicking on thesa
288. increasing thenumbersareless than 250 W hen thevelocityisdecreasingthenumbersaregreater than 250 Extremechangesin velocity result in extremely large or small numbers which areignored by split Using int W hat happens nextin our patch Thevelocity issent to the middle inlet of makenote whereitis stored Then the pitch valueis stored in theint object W ell so far we ve seen that alot of numbers get stored calculated and changed by playing on the synth but nothing elsehappens until weturn on themetro Thebang messages from themetro trigger theint object which sends out its number whatever pitch was most recently played to makenote Thespeed of themetroisdependenton thechangein velocity between successivenotes played on thesynth e Turnonthemetro and play on your M IDI keyboard N oticehow you can affect the speed velocity and duration of therepeated notes by changing the velocity with which you play accum Another storage object accum performs internal additions and multiplications to changeits stored value Theleftinlet of accum functions just likethat of theint and float objects a number received in the left inlet is stored and sent out the outlet and a bang sends the stored number out again H owever themiddleand right inlets ofaccum are used to add to the stored number or multiply the stored number respectively Thenumber is changed without anything being sent out the outlet 1 Z 3 d the number is stored
289. indow without hidingthescroll barsand zoom box N ow you can unlock thePatcher and enlargethewindow to seehow themenubar object triggers theubutton objects which in turn trigger all the other necessary actions for turning atrack on or off Changing Text Labels When you want atext label to changein a patch themenu object isa good substitute for a com ment In themenu Inspector window you can set themenu sM odeto Label In thismode menu appears as a borderless text label that does not respond to amouseclick very much likea com ment Unlikewith a comment however you can typein a series of different text messages as menu items and recall them by sendingtheitem number in theinlet In thisway you can causealabel to change to fit thenumber it is describing For example in thetrack window when thechannel of the M IDI noteisto beleft unchanged the Channeiization value is at0 Assoon asanumber from 1 to 16 is entered as the Channeiization value though thelabel changes to O ut Channa to show that that isthenew output channel 225 Tutorial 45 D esigningtheuser interface W hen thevalueischanged back to 0 thelabel changesback to Channdization to show thatthereis currently no channelization occurring Channelization o Out Channel 10 Changingthevaluein thenumber box changesthelabel Another use of menu for changing text can befound in theAbout N ote M odifier screen e ChooseAbout NoteM odifier from the A ppleor H elp m
290. inely working on long 242 Tutorial 4 Advanced scripting scripts you might consider writing them inside of acoll object U sing the previous exampleasa model thispatcher script delete mybpatcher 1 script new mybpatcher bpatcher 8 71 105 90 0 0 bpatche 1 2 script connect num _toplett mybpatcher 3 4 script connect num_topright 0 mybpatcher 1 script connect mybpatcher 0 mum_bottom Thereareseveral advantages to this method e A coll object takes up virtually no screen space e You can savescriptsto files or read them in as necessary e You can manage multiple scripts inside of a single object Moving and Resizing Objects Someofthemost exciting features of scripting arethecommandsto dynamically move resizeand hide elements of M ax patches U sing these features flexible interface designs are straightforward to implement Themain scripting command for moving objects is 243 Tutorial 4 Advanced scripting script move lt variable name gt lt top gt lt left gt Thehorizontal and vertical coordinates refer to the pixel location of thetop left corner of the object insidethe window To resize objects script size lt variable name gt lt horizontal size gt lt vertical size gt Again values arein pixels Consider the following patch r somedata r somedatal linestuti zel large small Script move myfunction 30 16 Script size myfunction 400 200
291. ing on only those messages which arrivein a particular inlet or they can beused to send incoming messages to oneof many destinations See Also gate Pass the input out a specific outlet Ggate Pass the input out oneof two outlets Gswitch Receive the input in oneof two inlets route Selectively pass the input out a specific outlet switch Receive the input in aspecific inlet 63 Tutorial 18 Test 3 Comparisonsand D ecisions Comparisons and Decisions You can write a patch that examines the notes being played on your M IDI keyboard and makes a decision about what to do based on the note information H ereis an exercise to test your under standing of theuse of comparisons to make decisions e Makea patch that receives the notes being played on your M IDI keyboard and if thenoteis M iddleC M IDI note60 or higher playsthenotes an octavelower and an octavehigher than the played pitch Hints A comparison is needed to find out if the pitch being played is greater than or equal to 60 Based on that comparison a decision is madeto play or not to play the notes an octave lower 12 semitones less and an octave higher 12 semitones more than the original pitch If the original pitch is less than 60 nothing needs to be done but if the pitch is greater than or equal to 60 two new pitches need to be generated The original pitch must have 12 subtracted from it to get the lower pitch and it must have 12 added to it to get the highe
292. ing system used by the synthesizer manufacturer You ll need to figure out exactly how M IDI program change values correspond to the sound numbers on your synth In this example we left 165 Tutorial 37 Data structures menu item 0 empty and used menu items 1 to 32 to store the names of sounds so selecting a sound will transmit a program change value from 1 to 32 e Look atthe menu Inspector for the Synthesizer Sound menu Notice how weleft the first menu item empty by starting the text with a comma so that we could use items 1 to 32 How did weget moreitemsin the menu than will fit into the dialog box We typed the itemsin a Text window then copied them and pasted them into the menu Inspector e You may want to replace our list of sounds with one that correspondsto your equipment W ealso wanted to display incoming program change values so wedirected them to theinlet of our menu However we don t want the program change to be sent out again so we use the set message to set themenu to thespecified item without causing any output Likewise wewantthenumber box to reflect numbers from the menu but we don t want it to send the number back to the menu because that would cause a stack overflow O nce again theset message is the solution 1 Acoustic Fiano Bynt hesizer Bound e Closethe menu_examples window and double click on the patcher preset_ examples object to open the subpatch window preset Thepreset object can sto
293. ing the object to find thepattr with thename speed Ifitfindstherel evant pattr object it will instruct the object to send the message 125 to whatever object itis bound to in this case ournumber box e Unlock the patch and click on thenumber box attached to themetro object Select Name from theO bject menu eee Name Object Set Object Name for number metro 125 pattr speed Ghindta temporum counter 0 47 Our pattr object is bound to our number box because the bindto attribute of our pattr object is set to thenameof our number box temponum For moreon naming M ax objects and the applica tion of thistechniqueto patcher scripting seeT utorial 46 Basic scripting N otethat thepattrhub object controls our number box viathename of the pattr object to which itis bound speed not thename of thenumber box itself tenponum e Renamethenumber boxto something elseand closetheN ameO bjectinspector Try changing settings for the patch by clicking on the message boxes again N otethat if werenameour referred object our pattr object can no longer bind to it In order to rebind it weneed to tell pattr to bind to ournumber box again Open the N ameObject inspector for the number box and nameit back to tenponum Close theinspector and recreatethepattr objectbindingto tenponum either deletetheobjectand undo thedeletion or createa new pattr object V erify that itisrecei vingup
294. int of the line segment A lineis drawn from the cur rent location to that endpoint and the endpoint is stored asthe new current location corner coordinates of the triangle handle horizontal and vertical separately subtract the cwrent pen location to find the distance halve the distance add to the cwrent pen location to gek Dew coordinates store these new coordinates as the next current location recombine horizontal and vertical coordinates draw a line to the new location prepend LineTo 203 Tutorial 43 Graphics in a Patcher Therandom number is also used to designate a color for thelcd object s pen so each lineis one of three colors depending on which corner of thetriangleit is drawing toward W hen the note 96 the highest C on the keyboard is received the contents of the Icd are erased with a clear message and threenew colors are chosen by putting anew random number into therright inlet of the object Displaying and Hiding Text Itis possible to display changing text messages that don t seem to be contained in M ax objects by using acontaining object that has no borders Onemethod isto display messagesin amenu object thatisin Label mode A menu isputinto Label modeby sending it the message mode 3 or by selecting it and choosing Get Info from the Object menu and setting its mode to Label Oncethis has been done the menu displays no bor ders and doesnot respond to the mouse Sending the menu an
295. ion timeline 189 302 active 185 active window 102 address of afunbuff 106 Align 11 All NotesO ff message 61 all notes off message 232 All Windows Active 102 and 56 animation 199 in aPatcher window 205 anti aliased text 227 append 97 received in amessage object 98 292 application written in M ax 225 argument 16 changeable argument 96 291 295 arithmetic operators 25 Index array 288 funbuff 106 of symbols 290 table 130 ASCII 76 Assistance 104 Auto Step 337 Automatic actions 184 automatic actions 184 autoscroll whileplaying atimeline 313 B b 23 background window 102 backslash 98 292 295 bang 12 284 received in atable 138 298 bang means Do It 12 bangbang 23 beats per minute 127 bendin 59 bendout 59 bent patch cords 70 blinking text 231 boot path 255 both numbers arenot zero 56 bouncing graphic effect 212 boxcolor 327 bpatcher 209 breakpoint 338 bug debugging 332 335 error message 339 button 12 as a debugging tool 335 button appearance 227 Cc C function 178 C programming language 175 C74 path 255 capture 144 debugging with 334 change 57 changeable argument 96 291 295 characters special 230 295 408 Index checkpreempt 327 chord playing parallel chords 50 storing 165 transmitting 96 120 chord playing patch 165 clean 327 clicktrack patch 186 clocker 125 closebang 184 coll 164 289 editing the contents of 165 collective 225 271 color of asprite 202 color of an object 73
296. ipt saved somewhere in thesearch patch Becauseitisa graphical object thereisno object box to typein thenameof thefile Instead weset the avaScript source file using thejsui object s Inspector 282 Tutorial 51 D esigningU ser Interfaces in JavaScript e Unlock theTutorial patch and highlight thejsui object U nder the O bject menu select Get Info An Inspector should appear with thenameofour jsui sourcefile mymatrix js inthe textfield labeled JavaScript File You can also set the sizeof the object in the Inspector as well as turn on or off a border around the object Disabling the object border combined with set ting the background color of your M ax patch to match that of your jsui object can help you design aseamless user interface ahah i a A AAE RT brgb i 2 t e0809 jsui Inspector Size width e4 Height Border Options f FAs Disable Override Javascript File Arguments to Javascript File p The Drawing Code e Thejsui object is graphical so double clicking the object will not open thetext editor asit does with thejs object Instead click the message box labeled open Thetext editor containing 283 Tutorial 51 Designing U ser Interfaces in JavaScript our JavaScript file mymatrix js will appear O ur JavaScript fileis saved on disk in the same folder astheT utorial patch Aswith ajsscript our codefor thejsui object starts with a global block that al
297. is post x ee it Sate TheM axjsobject allowsyou to edit avaScript codedirectly within M ax through abasic text editor thesametext editor in fact that you usewhen editing the contents of a coll or text object The sourcecodethat thejs object loads is determined by thefirst argument to the object which speci fies atext filein theM ax search path If you don t givejs an argument you can still writea ava script program from scratch in the editor but you ll haveto savethefilein order to useit The Global Code W hen you open thejs object s editor you ll seesome avaScript code T hecodebegins with acom ment block that tells us thenameof the file what it does and who wroteit Thejs object ignores theselinesbecausethey areprefaced with adoubleslash commonly used in C and other programming languages to define a comment C stylecomments to start and to end arealso allowed in JavaScript 251 Tutorial 48 Basic avaScript Thecodeafter theinitial comment block defines someglobal code for thejs object Thisiscode that will let us define variables and run any part of the program weneed to execute before any thing happens to the object within the M ax environment In our example weusetheglobal code to tell M ax how many inlets and outlets weneed for our js object and to defineand initializea vari able called x inlets and outlets inlets 1 outlets 1 global variables
298. is driver does not belong in the standalone folder if you wantto useit you ll haveto instruct usersof your application to copyitto thecorrect location or build you own installer that does this Custom Icons and the Property List for Mac OSX In order to use a custom icon for your standalone application follow these steps 1 Createa property list filefor your application Thisisatext file containing an XM L specifica tion of information related to your application such as its icons and version number You can usethe Property List compiler in CodeWarrior or some other tool such asApples Property List editor to create the file you need to create nfo plist not a resource For an example open an application packagein theA pplications folder for example Safari by control click ing on Safari s icon and choosing Show Package Contents from the pop up menu Open the Contents folder and you will see the nfo plist file 2 Changetheicons referenced in thefileto thenameof an icon file you will create Specifically for the application icon you need to change thisline key CFBundlelconFile value string property list compiler source or lt key gt CFBundleTypelconFile lt key gt lt string gt file icns lt string gt XML Thetext should read key CFBundlelconFile value string YourApplication icns where YourApplication icnsis thename of the icon file you will add to the bundle or lt key gt CBundlelypelconFile lt key g
299. is is another way that the timeline can communicate with patches other than oneof its own action patches thistimeline Let s look at onemorefeature that s availablein an action thethistimeline object Any message received by athistimeline object in an action gets transmitted to thetimelinethat contains that 185 Tutorial 4 TimelineofM ax messages action In this way atimelinecan actually send control messages to itself In portion E of this action therearetwo ticmd objects for handling goto and gotoA events from thetimeline cetlin a 1 1 titmd goto i ticmd goto b search Section locate 1 thisTimeline W hen agotoA event is reached in the timeline and the Ggate is pointing to the proper outlet it bangs thesearch SectionA message box sending that message to the timeline Thetimelinewill then look for a marker called SectionA and relocate itself to that marker if it finds it W hen agoto event is reached in the timeline and thegate is open it sends a number specifying a point on thetime line in milliseconds to the locate 1 message box which causes thetimelineto relocateto that point In either case the timeline will continueto play after it has relocated itself to thenew point In order to givetheuser some control over thetimeline s behavior the mod wheel of thesynth controller 1 is used in thisaction to block or let pass the gotoA and goto messages N otice that a gotoA message will be pa
300. it can be referenced using common bracket notation e g state 4 2 Following our variable and array declarations wefind threecommands that refer to the graphical behavior of thejsui object Thefirst sketch default2d telsour jsui object to initialize a number of default behaviors with theassumption that wewill begiving it graphicscommandsfor atwo dimensional scene It sets a default view upon theO penGL renderingcontext and performs anumber of utility routines to makeit easy for usto simply start placing graphical elementsin the window Thedraw command which could benamed anything refers to our main graphics 284 D esigningU ser Interf Tutorial 51 esigning Se function which wewriteto contain all the commands needed to draw theuser interface of thejsui object Therefresh command copiestheO penGL backbuffer wherethedrawingisdone initially to prevent flicker to the actual screen display Commenting out therefresh com mand will prevent our jsui object from ever showing us anything e Below theglobal block examinethe draw function Thisisthefunction that provides jsui with all the commandsit needs to draw our screen interface draw main graphics function function draw with sketch set how the polygons are rendered glclearcolor vbrgb 0 vbrgb 1 vbrgb 2 vbrgb 3 set the clear color glclear erase the background colstep 2 ncols how much to move over per column rowstep 2 nr
301. itch y to besent out When thenote off message comes later nothing goes through thegate and theuntransposed pitch is sent by itself to funbuff causing the transposed pitch to besent out again Sincethenote off messages get their transposition from funbuff rather than from the object thevaluein the object can change without affecting the note off transpositions e Closethesubpatch window Play on your M IDI keyboard and dragon theslider at the same timeto changethetransposition of what you are playing Storing transpositionsin thismanner is essential whenever theinterval of transposition isto be changed whilethe notes are being transposed For example thetransposition might be changed automatically by numbers generated in someother part of the patch Differences Between the Patcher Object and Your Object W hat arethedifferences between asubpatch in apatcher object and asubpatch you created earlier and saved in a separate file Onedifferenceisin the way they are saved T hesubpatch in a patcher object is saved as part of the filethat contains the patcher object Asa result of this you can edit a patcher object subpatch just by doubleclicking on the patcher object and unlocking the subpatch window W hen thesubpatch issaved as aseparate file however you can seeits contents by double clicking on the object but you can t edit the contents of the subpatch window M ax will not let you unlock it To edit the object you haveto ope
302. item number displays a new text message and if you leavean empty item in themenu you can hideitentirely by sendingitthenum ber of that item There are actually three such menu objects in the lower left corner of the Tutorial patch e Ifyou havenot already doneso closethe Sierpinski window Click on the button at the right edge of the Patcher window Click here for an epigram gt The button triggers numbers and sendsthem via hidden send and receive objects to the border less menu objects in the lower left corner Window into a Subpatch The button certainly appears to bein the Patcher window but it is actually part of a subpatch con tained inside abpatcher object A bpatcher is like a window into asubpatch You can load any pre viously saved patch into a bpatcher object and its contents are then visible through the bpatcher You can resize the bpatcher to control just how much of thesubpatch is visible and user interface objects inside the bpatcher such as the button in this example respond to the mouse just as if they werein the main patch 204 Tutorial 43 Graphicsin a Patcher e Unlock the Patcher window and you will see that it contains two bpatcher objects one that contains the button and along thin one a the top of the window that apparently contains nothing N otonly can you control how much of thesubpatch isvisibleby resizing thebpatcher you can also control what portion of thesubpatch shows through it
303. ith themouseand fed into the Note M odifier 220 Tutorial 45 D esigning the user interface e To begin modifying M IDI notes turn on onetrack by clicking on the Track A button You can also turn thetrack on or off by choosing Track A from theM odify menu or by typing Command 1 on M acintosh or Control 1 on M acintosh ak neam 15 out Channelization o Ng Transposition 12 Inversion ak Randomization 25 a Randora range Sh Delay time mz e Usetheln andOutpop up menusto choosetheinputportfrom which you wish to receivethe M IDI notes and the output port to which you wish to transmit the modified notes The pop up menus should contain the list of devices from your current M IDI setup e Aslongasanumber box in the Track A window shows 0 that particular modification will be bypassed and thenotewill besent on unchanged Drag on thenumber box objects with the mouse and or click on the Inversion toggle to set the desired modifications Then begin playing on your M IDI keyboard Try different combinations of modifications e Ifyou wantmorestreamsof modified notes turn on additional tracks and set different values for the parameters of those tracks e By choosingK eyboardfrom theM odify menu you can usean onscreen imitation M IDI key board which sends its notes to the Note M odifier tracks as well as directly to the output port you select This allows you to usethe application even when you don t havea M IDI
304. ition of feeling like the list of things you haveto do is growing faster than you can get them done Well it s possibleto overload M ax in asimilar way so that the list of things M ax has to do eventually overflows the amount of memory space available for its stack of things to do Thisis known as a stack overflow and it causes M ax to shut down its internal sched uler and stop performing timed operations until you fix whatever is causing the overflow Oneway to cause a stack overflow is to feed an object s output back into itsinput For example when you want to increment numbers as fast as possible you might be tempted to feed the output of an object like counter right back into itself repeatedly incrementing the count But such auto matic repetitions must be separated by at least a millisecond or two otherwise M ax will generate repetitions too fast for itself to keep track of and you will get a Stack O verflow error dialog W hen this happens you must chooseResumefrom the Edit menu to restart M ax s scheduler e Patches D and E show two examples of situations that result in stack overflow Click on the buttons if you want to make M ax very unhappy Go ahead you won t break anything Remember to choosethe Resume command to start M ax up again Eid do pot try this yourselves These may look like good ways to send ow Wumhers as fast as possible but they will result im stack overflow tempo Thetempo object is another
305. ive object named by the symbol Theword seteventinterval followed by an integer value sets thetime between invo cations of the event level timer The default value is 2 milliseconds The event level timer handles low priority tasks like drawing user interface updates and playing movies Macintosh only Theword setrefreshrate followed by a number sets the rate in framesper second atwhich thevisual display isupdated On M acintosh systems therate at which the screen is refreshed is unrelated to the rate at which you changeitscontents Better visual performance can beacheived atthecostofa slight performance decrease in Jitter and littleor no performance decrease for audio processing by specifying a higher frame rate W hen enabled using the enablerefresh 1 message the default rateis 28 57 FPS Refresh enable is off by default Theword setsleep followed by anumber setsthetimebetween callsto get thenext system event in 60ths of asecond Thedefault valueis 2 Theword setpollthrottle followed by an integer sets the maximum number of events the scheduler executes each timeit is called The default value is 20 Set ting this value lower may decrease accuracy of timing at the expense of efficiency Theword setqueuethrottle followed by an integer value setsthe maximum number of events handled at low priority each timethelow priority queuehandler is called T hedefault valueis 2 Changing this value may affect the resp
306. ject s range can betyped in as arguments and or they can be supplied in themiddleand right inlets In thiscase ASCII numbers 120 through 122 keysx y and z aresent out theleft outlet and all other numbers aresent out theright outlet keys 120 to all other keys 122 x to 2 are a sent out sent out here re Using Key Commands to Control a gate Let s seewhat happenswhen thekeysx y andz 120 121 and 122 aretyped First of all 120 is subtracted from the key number resulting in thenumbers0 1 and 2 Thesenumbers are used to n Tutorial 20 U singthe computer keyboard control agate The letter x closesthe gate the letter y opens the left outlet and the letter z opens theright outlet keys 120 to split 120 122 122 x to 2 are sent out here gate mum her Pitch information from notein is passed through the open outlet of the gate So if the letter y is typed pitches are passed to the 12 object and are transposed down an octave If the letter z is typed the pitches are passed to the 12 object and aretransposed up an octave If x istyped the gate is closed and no pitches are passed through Thetransposed pitches are combined with velocitiesin theflush object and are sent to noteout e Typethedifferent key commandsx y and z and listen to thechangein effect for each com mand when you play on your M IDI keyboard Turning Off Transposed Notes Atfirst glance theflush object may seem to be unnecessary
307. keyboard available TheNoteM odifier program is modeled after the PCL software originated by Richard Teitelbaum and coded in 68000 assembly language by M ark Bernard in 1983 see Richard Teitabaum The Digital Piano and the Patch Control Language T he Proceedings of the CM C Paris 1984 and later re implemented in M ax to Teitebaum s specifications by Christopher D obrian in 1990 Planning Your Application In order to design agood program and agood interface it pays to do some planning before you begin programming to makesurethat you know a what things you want theprogram to do and how you plan to do them b what information you ll need to give the user and how you plan to display it and c what information you need to get from the user and how the user can best pro vide it O ncewe decide what our application will do four tracks of MIDI routing channdizing etc and how that can be accomplished thenext thing to consider is W hat do weneed to tell the user 221 Tutorial 45 D esigning the user interface Theuser needs to be told which tracks are currently turned on an on off indication for each track and what the settings are for each track a set of parameter names and their values Four tracks with eight modifiableparameterson each track plusan on offindicator makes 36 different itemsof information weneed to show theuser pluslabelsto identify theitems Someinformation isnumerical someis asimple on off indicatio
308. king the patcher object containing it O bserve that thetwo pattr objectsin there min and max have been bound to two number box objects through their middle outlets One Hub to Rule Them All e Closethesubpatchers and go back to themain Tutorial patch Look at the message boxes again and notice the notation used in them to refer to pattr objects insidesubpatchers Because most of our pattr objects areinsidesubpatchers thepattrhub object refersto them usinga doublecolon separated notation that takes the form subpatcher pattr_ name W ecan communicateto pattr objects in nested subpatchers by the same convention e g apattr named yikes in a patcher called stuff in a bpatcher called things would be accessed through pat trhub with thename things stuff yikes e Using theubumenu object in themain Tutorial patch select oneof thepattr objects in the patch In addition to setting thestate of pattr objectsthrough pattrhub wecan also query thestateof pattr objects which will then tell pattrhub their internal state or the value of the object to which they re bound W edo thisbysendingpattrhub themessage get followed by thenameof thepattr object we want to query with no spacein the message e g getspeed will poll the state of the pattr named speed Thenumber box to theright of theubumenu reflects the current value of the selected pattr output by thesecond outlet of pattrhub as a message beginning with thename of th
309. l interpolate values between saved states N on adja cent states can beinterpolated as well using the message fade ab n whereaand b aretheslot numbers and n isavaluefrom 0 0 100 a to 1 0 100 b Note that interpolated values will italicize both of the participating slot in the storage window 305 Tuto ri a 53 M ore patcher storage Saving and Loading Files e After you vesaved a couple of states into preset slots click on the message box labeled write attached to thepattrstorage object A filesave dialog will appear asking you to saveafile with thesuffix xml Savethe file somewhere and open itin any application that can read text files M ax for example Look over thefile Thepattrstorage object reads and writes collections of preset states as XM L extended markup language files a format which uses nested tags as identifiers for different types of data in afile AnexampleXM L filefrom our Tutorial patch could look something likethis lt xml version 1 0 encoding iso 8859 1 standalone yes gt lt pattrstorage name u518000001 gt lt slot number 1 gt lt pattr name angle value 60 gt lt pattr name desynch value 7 gt lt pattr name offset value 0 gt lt pattr name range value 50 100 gt lt slot gt lt slot number 2 gt lt pattr name angle value 33 5 gt lt pattr name desynch value 39
310. l that alistisany space separated set of items beginning with anumber For example when coll receives the message 36 sequencer start 2048 it storesthemessage sequencer start 2048 at address 36 A fter that whenever coll receivesthenumber 36 alone it sends the address 36 out the second outlet and sends the message sequencer start 2048 out the left outlet You can also store messages with a symbol as an address instead of a number If you just send ita message beginning with asymbol coll will try to interpret thesymbol as another kind of com mand and won t store the rest of the message So to store messages with asymbol as the address you must precede the symbol with the word store W hen coll receives a message beginning with theword store it usesthefirst item after the word store as its address and stores the rest of the message at that address W hen coll receives that address alonein theinlet it sends it out the right outlet preceded by the word symbol and sendsthe stored message out the left outlet 159 Tutorial 37 Data structures H ere sthesamepatch usingasymbol asan addressfor the messagestored in coll instead of anum ber double time store double time sequencer start 2048 route sequencer metronome clock coll precedes the symbol address it sends out its second outlet with the word symbol so that the address will not be interpreted as a command by other objects For example a message box will
311. label for the etable Once labeled it will sharethe data of a loaded table object bearing the same name Thistable object may bein an open patch or in an action within thetimeline O ncean etable his been labeled you can still edit it graphically by dou ble clicking on it which will also alter contents of thetable to which it is linked 367 TI mel Ine Creatinga graphicscoreofM ax messages The efunc Editor When you create an efunc editor a shaded box similar to the etable editor appears By clickingin theefunc editor box you specify a point to be stored as an x y pair of numbers W hen you click in efunc theactual values of x and y for thepoint whereyou click areshown at thetop of thetimeline window Each timeyou click at a different point you create a new x y pair of numbers and efunc connects all the points with lines segments from left to right 8 0 8 Untitled 144 44 O P b bp poi JF 00 00 00 00 14 15 x 923 y 33 Track Display 00 00 00 00 04 00 00 08 00 00 12 00 00 16 00 v k h 1 PrintThree mint At Edit Event in Track 1 Se BID _ _ _ _ _ _ _ _ _ _ You can move any existing point simply by dragging it The coordinates of the point are displayed as you drag it W hen timeline plays back the datain an efunceditor it sendsthey vertical valueof each x y pair out of the middle outlet of the appropriateticmd object at atime corresponding to the value of x By default efu
312. lay those pitches by dragging on the upper hslider e When you have drawn a pitch curve that you likein the Table window enter a number in the number box marked Store and the table values will be stored in that preset location Bore el S Bae Table Presets e Repeat the process until you have stored several table presets Then you can recall different ones by entering a number with the number box marked Recall Fecall Fa a A EREE Table Presets e Nowunlock the preset_ examples window to see what s going on behind the scenes Thenumber box objects labeled Store Recall and Clear are actually sending messages to the preset Bore Recall lear ERE EREE Table Presets To store settings in a preset location you send the message store followed by the number of the preset location To recall a preset just send the number of that preset alone To clear a preset send the message clear followed by the preset number clearall will clear all stored presets You can save the contents of preset in a separate file with the write message and load a filein with the read message e Double click on the patcher another_ example object to seethe sub subpatch 167 Tutorial 37 Data structures Thepreset object in the another_ example window already has 16 presets stored in it as part of the patch To store the contents of a preset along with a patch rather than as a separate file you Select the preset object choose Get Info
313. lder included with M SP contains audio driver objects SeetheM SP documentation for moreinformation Themididrivers folder containsoneor moreM IDI driver objects Theexternalsfolder contains all of the external objects not in any of the other folder It can be renamed if desired Installers for collections of external objects such as Cycling 74 s Jitter may install additional foldersinsidetheC ycling 74 folder or place folders insidethe externals folder File Path Syntax A file path isa way to specify the location of afile You re probably familiar with these specifiers in URLs used in web browsers H ere san example http www cycling74 com products dimaxmsp htm This specifies that the filedlmaxmsp html is insidetheproductsfolder which isinsidetheroot level of the Cycling 74 web site In asimilar way you may want to tell M ax about afile or folder location on your hard drive M ax has several options for specifying file locations First you can choose to usethecross platform slash the M acintosh native colon or theW indows native backslash to separate folder names H owever the backslash is used in M ax as an escape character and may lead to unexpected behavior so weencourage you to usetheslash H erearesomeacceptable examples of filelocations C MaxFolder extras mystuff mypatcher pat cross platform using slashes Disk M axFolder extras mystuff mypatcher pat M acintosh specific using colons C MaxFolder
314. le M IDI control surface with clin and uslider Objects and uses those objects valuesto createasimpleM IDI step sequencer Thenumber of sliders created by our JavaScript code determines the length of the sequence e Turn offboth toggle objects stopping thesequenceand putting thesequencer transport back into forward mode Let s look at the codefor our js object The Global Block Arrays and Maxobjs e Doubleclick thejs objectin theT utorial patch The code for autosurface js should appear Atthetop of thecodeshould bethe familiar comment block explaining what thescript does Below that we should see our global code statements inlets and outlets inlets 1 outlets 2 global variables and arrays var numsliders 0 var seqcounter var thereverse var thevalues new Array 128 Maxobj variables for scripting var controlin new Array 128 var thesliders new Array 128 var thefunnel Io jo FINE Aswesawin theprevioustutorial our inlets and outlets at thetop of thecodetell js how many inlets and outlets we want in our object Thefollowing block of code defines some variables that our JavaScript code will need to use glo bally These variables include numsliders Storeshow many sliders ctlin and uslider pairs wehavein our patch Thisis set by thesliders message to our js object seqcounte Storesthecurrent pointin our sequence Thisisdriven by themetro object i
315. le name gt lt outlet index gt lt inlet variable name gt lt inlet index gt Inlets and outlets are counted beginning at 0 from left to right To disconnect objects the word connect is changed to disconnect script disconnect lt outlet variable name gt lt outlet index gt lt inlet variable name gt lt inlet index gt 230 Tutorial 46 Basic scripting H ere sa before and after illustration of these messages Jobn Script connect Jobn 0 Fhilip 0 Philip Script connect Fhilip 0 Sousa Sousa thispatcher Before sending thescript connect message In theabove example wehavethreenumber box objects named John Philip and Sousa T hescript connect messages to theright can beused to connect them to each other Script connect Jobn 0 Fhilip U Script connect Fhilip 0 Sousa thispatcher After sending thescript connect message To disconnect we simply changethe connec to disconnect John po script disconect John 0 Philip 0 script disconnect Philip Sousa philip Sousa thispatcher After sending thescript disconnect message 231 Tutorial 46 Basic scripting Sending Messages You can usescriptingto send valuesor messagesto any named object Thecommand to do this is script send lt variable name gt Script send mynumbox v4 thispatcher T hescript send message Thisis particularly useful when working with large groups of named objects where gate or send objects might be u
316. le object atthe bottom of Patch 1 A T ablewindow will open to showa graph of some numbers that we have stored there 6 Untitled Thistable contains 128 numbers with addresses from 0 to 127 Addresses always go from 0 to the number 1 less than the size of thetable Thistable shows arange of possible values from 0 to 127 and the values we have stored range from 36 to 96 e Turnonthemetro at the top of Patch 1 The counter counts up and down between 0 and 127 Thenumbers aresent through auslider just to show their progression graphically then they are sent to the left inlet of table 125 Tutorial 32 Thetable object A number by itself in theleft inlet of table specifies an address and thevaluestored at that address issentouttheleft outlet T heoutput of thetable is displayed graphically by thesecond uslider You can see and hear the numbers in thetable as counter steps through them value shored at that address Get Info e With theUntitled table editing window still in the foreground chooseGet Info from the Object menu to open the table Inspector Thetable nspector shows you the Size of thetable the number of storage addresses and the Range of displayed values It also has two options for viewing the numbers Checking Signed causes the Table window to display negative values as well as positive and checking N ote N ame Legend shows they axis values as M IDI note names instead of numbers Table Size 126 Tabl
317. le sends out1 O therwisegamble sends out 0 In effect the arguments to gamble state the odds of al being output each time a bang is received in the left inlet In this casethe odds are 64 in 128 even up e Closethesubpatch window and double click on thegamble 2 5 object to seethe contents of thesubpatch Theoddsare different in this subpatch becausethe arguments are different 106 Tutorial 28 Your argument The argument e Nowopenthedocument named gamblein theM ax Tutorial folder You can seethat in the original gamblepatch theodds are specified with changeable arguments W hen thegamblepatch isused asasubpatch in other patches thechangeable 1 and 2 arguments are replaced by the 1st and 2nd arguments typed into the gamble object If no argument is typed in the arguments are replaced by 0 The argument can be used with most M ax objects inside your object and can bereplaced by a symbol as well asa number For examples of its usage look in theA rgquments section of this man ual Using Weighted Randomness N ow that you have seen how arguments are used to set initial values for a subpatch object let s see how gamble is actually used in this patch Each timegamble receives abang in itsleft inlet it makes a probabilistic decision whether to send out 1 or 0 depending on thespecified odds In theright portion of thePatcher window gamble is used to decidewhether to open or shut agate louder notes are more likely
318. led O All Windows Active Enabled hf User Can t Close Toplevel Patcher Windows ina kl Audio Support kj MICI Support TheApplication Creator Codeisa M acintosh only setting It specifies a four character ID that the Finder uses to distinguish your application from others including M ax and M axM SP Runtime Thedefault creator is assigned for generic files and applications You can change this to any combination of four characters you like but if you choose one already in use by another applica tion your application will run when you double click on adocument for the application whose creator you used For instance if you used max2 for acreator double clicking on aM ax docu ment would launch your application instead of M ax If you want to guarantee your character combination is unique you will want to register it with Appleat thefollowing URL http developer apple com dev cftype The File Options section lets you customize some aspects of how your standalone application deals with files and the file system UseOwn Property List plist Resource is also aM acintosh only option and is somewhat out of date For a better solution see the Custom Icons and the Property List for M ac OSX section below Windows users should see the Custom Icons and Splash Screens for Windows section below If UseO wn Property List is checked any plst resource included in the collective is copied into the application being built Remember that you
319. lemsin an if then else for mat If thecomparison in theargumentsistrue doesnot equal 0 then themessageafter theword then is sent out the outlet otherwise the message after the optional word else is sent out So the conditional statement if the received number is greater than or equal to 64 send out 127 otherwise send out the received number 171 Tutorial 38 exprand if would be expressed as if il 64 then 127 else il Thethen and else portions of theif object contain a message similar to that you would typeinto a message box You can includechangeablearguments butnot mathematical expressionsasyou can in the portion of the message after theif If thethen or else portions of theif object begins with the argument out2 then the object has a sec ond outlet on the right and the message is sent out the right outlet Thethen portion and else portions can also begin with send followed by thename of areceive object In that case theoutputissent to all receive objects with that name instead of out the outlet e Double click on the patcher if_ example object to see the usefulness of if Theproblem in this examplewas If thenoteG 1isplayed with a velocity between 16 and 95 start a sequence otherwise increment a counter somewhere else T he example shows that a great many tasks can be combined into asingleif then dase expression In this instance oneif object does the work of nine other objects 172
320. let sending valuesto theright inlet of thepack object driving messages to amultislider object In addition ourjs object has a number of objects connected to its inlet A metro object is connected to our js object as are two message boxes that will send themes sages sliders n and reversen wheren in each case isthe value present in thenumber box connected to them From thepatch layout wecan infer that the avaScript codein our js object should haveat least three methods for bang sliders and reverse It actually hasonemore which will become apparent when weusethe patch Patch Auto Generation e Select thenumber box attached to the message box containing thesliders 1 message T ypein or scroll to thenumber 5 and watch what happens Changethevaluein thenumber box Try set tingit to alargenumber like50 Set it to 0 and see what happens Boake some sliders seen ion f reverse the sequence TEEN BS In responseto our sliders 1 message our js object dynamically creates M ax objects and connec tions through scripting It creates pairs of ctlin and uslider objects to match thenumber of sliders you request through the message to thejs object Furthermore it creates afunnel object with the fz autorurface je 260 Tutorial 49 Advanced scripting appropriate number of inlets for theuslider objects and makes the appropriate connections between them T hefunnel object isthen connected to our js object allowing the values gen
321. listindividually in order from left to right out asingle outlet The changeable argument in a message box can be used to isolateindividual elements of alist This is especially effective if thelist contains symbols in addition to numbers Theswap object reverses the sequential order of two numbers W hen a number is received in the left inlet itissent out theright outlet then thenumber that was received earlier in therightinletis sent out the left outlet See Also buddy Synchronizearriving numbers output them together fswap Reverse the sequential order of two decimal numbers iter Break alist up into aseries of numbers pack Combine numbers and symbols into alist swap Reverse the sequential order of two numbers thresh Combinenumbers into alist when received close together unpack Break alist up into individual messages 119 Tutorial31 U singT imers Timed Processes So far we have used two different timing objects metro for sending a bang at regular intervals and timer for reportingtheelapsed timebetween two events In thischapter weintroducesomeobjects for producing timed progressions of numbers clocker T heclocker object isthesameas metro except thatinstead of sendingout bang at regular intervalsit sends out the time elapsed since it was turned on With this information you can cause values to changein somemanner correlated with the passing of time In the part of the Patcher window marked A a clocker reports the elap
322. lled from different Patcher windows functioning likea global vari able Theaccum object stores a single number which can beadded to or multiplied A data structure stores a group of information together in aconsistent format so that a particular item can be retrieved using the address location of theitem Arrays Thetable objectisan array of numbers whereeach number stored in thetablehasauniqueindex number its address W hen an address is received in the left inlet thevaluestored at that address issent out the left outlet Storing numbersin an easily accessible way is the main utility of such an array but thetable object has many powerful features for modifying and usingthenumbersit stores Thevaluesin atable aredisplayed graphically in the table editing window showing the addresses on thex axis of a graph and the valueson they axis You can change the values displayed in the table window by drawingin thegraph with drawingtools or by cuttingand pastingregionsof the graph Other messages sent to atable can storenew values changeits size report thesum of all its values step forward or backward through different addresses report the address of a specific value and providestatistical information about its values Thefunbuff object stores addresses and values but unlikeatable theaddresses can beany num ber and gaps can exist between addresses If funbuff receivesin itsinlet an address that does not actually exist anumber that
323. lowing a performer 153 route 62 routing messages to different destinations 52 60 72 runtime 404 S s 90 Save Track As 372 Saying Hello 8 420 Index scheduler 399 402 score of Max messages 183 score of timed messages 362 score reading object 150 Screen aesthetics 66 script for menubar 225 scripting basic overview 228 bring to front 247 command syntax 230 connecting objects 230 creating objects 233 deleting objects 239 disconnecting objects 230 hiding objects 246 moving objects 244 offset messages 245 replacing objects 240 resizing objects 244 response to mouse clicks 247 send to back 247 sending messages 232 showing objects 246 using the coll object 242 scroll bars hiding 224 scrolling text 206 search path 373 Segmented Patch Cords 66 select 52 semicolon 355 in a message 95 356 semicolon for remote messages 401 send 90 send and receive 90 sendapppath 404 Sending and receiving MIDI notes 40 sendinterval 404 seq 147 seq and follow 147 sequencer of Max messages 183 sequencing 147 detonate 210 graphic editing 376 multi track 155 saving a sequence 148 single track 147 Index set received in a message object 93 351 received in a slider 29 Set Breakpoint 391 setboxcolor 401 seteventinterval 404 setpollthrottle 404 setqueuethrottle 404 setrefreshrate 404 setsleep 404 setslop 404 settings of objects storing 166 shapes in a graphics window 195 sharp sign 107 Show On Lock 67 showglobal 404
324. lows us to define inlets and outlets for theobject and global variablesfor our code Itis also wherewetypecom mands that we want to occur when the objectis initialized inlets and outlets inlets 1 outlets 1 global variables var ncols 4 default columns var nrows 4 default rows var vbrgb var vmrgb var vfrgb ply 03 87 O51 5 0 pos Ory O22 ot al Pos initialize state array var state new Array 8 for i 0 i lt 8 i state i new Array 8 for j 0 3 lt 64 j state i j 0 set up jsui defaults to 2d sketch default2d initialize graphics draw refresh Our JavaScript code defines two global variables ncolsand nrows which can be accessed by all functions as well asa number of global Array objects that definecolorsfor thedrawingand astate array that wewill useto hold information about which circlesare on and which are off in our user interface Note M ulti dimensional arraysin JavaScript are allocated by an Array object in which each element of the Array is itself an Array object and so on if morethan two dimensionsare needed This may seem somewhat unusual if you ve worked in other programming languages where multi dimensional arrays can be declared directly e g C The for loopsin our glo bal block accomplish this allocation and initializeall the elements of thestatearray to 0 Oncea multi dimensional array is created
325. ls change number of columns is jsui function cols val if arguments length ncols arguments 0 bang draw and refresh display rows and colum is clear the object tied Pa 221 331 a sel a POW across click the eggs 286 D esigningU ser Interf Tutorial 51 esigning a Thebang function which we call after nearly every change madeto the object from M ax including mouse events simply callSaraw and refresh aswedid in our global block causing thejsui object to updateits window to reflect any graphical changes bang draw and refresh display function bang draw refresh By only doingthedrawingwhen necessary weareableto reducetheamount of processor timethe object uses e IntheTutorial patcher changethe swatch objects that set thefrgb and brgb messages to ourjsul object Look atthe corresponding functions rgb and brgb intheJavaScript code N otethat the array for the off circle s color vmrgb ismidway between the colors set by frgb and brgb messages frgb change foreground clicked circle color function frgb r g b vfrgb 0 r 255 vfrgb 1 g 255 vfrgb 2 b 255 vmrgb 0 0 5 vfrgb 0 vbrgb 0 vmrgb 1 0 5 vfrgb 1l vbrgb 1 vmrgb 2 0 5 vfrgb 2 t vbrgb 2 bang draw and refresh display brgb change background color function brgb r g b vbrgb 0 r 255 vbrgb 1 g
326. m making 387 Deb U gg ng Tipsfor debugging patches that sort of error It just dutifully performs what you ask it to do The best way to protect against such bugsisjust to plan your program carefully try to account for as many eventualities as possi ble then constantly test the correctness of your plan as you implement it in M ax Test As You Go Itisinfinitely easier to debug a small patch than it isto debug a big complicated one It is also much easier to debug a large complicated patch when you know for surethat certain parts of it work correctly At every single stagein the development of a patch test everything as you go along Try sending extreme and unusual messages to your patch as well as normal expected ones to make surethat your patch doesn t malfunction in situations you haven t considered Once you are sure that a por tion of your program works properly you may want to encapsulate that portion by savingitina separate file and using it asa subpatch in alarger patch Viewing Messages T hereareseveral good ways to see exactly what messages are passing through the patch cords of your program so that you can be sure its doing what you want The best way to view messages is to include extra objects in your patch temporarily which intercept the messages as they are sent For viewing numbers the number box can be used asa kind of wiretap in any patch cord Num bers will pass through the number box unchang
327. m the O bject menu to display thenumber box Inspector Range hf No Min No Max C Bold Draw Triangle Options Output Only on Mouse Up Can t Change LJ Transparent Display Style Decimal Number Colors Inspector for a number box When you create a new number box it hasan unlimited range You can limit the range by typing a number into the Minimum and M aximum boxes in the Inspector Unlock the Patcher window select the number box located above theslider then choose Get Info from the O bject menu e Click on the checkboxes for No Min and No M ax to disable them Type the number 0 into the Minimum box and typethenumber 127 into theM aximum box You can movefrom onebox to the other by typing the Tab key Click OK then re lock the Patcher window e Nowwhen you dragon thenumber box it will not exceed the range of 0 to 127 TheM inimum and M aximum settings of a number box limit the range of numbers that can besent out by dragging on it or by typingin anumbe and also limit the range of numbers passing through it Incoming numbersthat exceed thespecified M inimum and M aximum will bechanged to stay within the limits 33 Tutorial 10 Number boxes Display Options Thelnspector has check boxesfor toggling on and off variousfeatures Someoftheoptions affect the way the number box functions while others only affect the way it looks TheDrawT riangleoption isalready checked so that thetrianglein theleft edge of
328. me circle again will changethe color back to light red rows and columns lopen view the souce pa b o RE Looki PEREAT TT Pr E 001 111 221 331 clear the object eee metro 250 set a row across yY click the eggs a router 44 oa 4 e Click on somecirclesso that they are highlighted in dark red At theright of the patch manipulate some of the uslider objects above the router object N otethe correspondence between which circles areclicked and which uslider objects below therouter echo the values from above Click on themessage box labeled clear attached to thejsui object Thecircles should all go to light red and therouter object will no longer pass messages from theuslider objects above Click on the message box containing thelist 001 111 etc Thejsui object should updateto show adiagonal row Therouter object will now pass messages from the first uslider aboveto thefirst uslider below and so on Our jsui object uses avaScript code to emulate some of thefunctionality of the M ax matrixctrl object Thecolumns represent the input to therouter object the rows specify the output O ur jsui communicates with the router object by sending lists in the format input output state that tell the router object to pass messages received at an inlet to all the appropriate outlets given thejsui object s current configuration Likethejs object thejsui object getsits program from afilewritten in JavaScr
329. me elapsed between events 75 214 Index timed progression of numbers 120 W timed repetition 18 345 weighted randomness 107 timeline 183 362 window size and placement 223 editing events 191 Y Timeline Action Folder 363 Your argument 106 timeline editor window 363 Your object 101 Timeline of Max messages 183 timer 75 tiOut 185 374 title bar hiding 224 TogEdge 136 toggle 19 toggle and comment 19 toggle mode for ubutton 222 top level patch 326 top level Patcher 335 Trace Enable Disable 391 Trace menu 391 track in a timeline 184 362 transposed note turning off 73 101 149 transposing 41 101 trigger 24 triggering 25 truncation 15 type of message 341 U ubutton 69 222 umenu 225 unpack 115 urn 208 user interface 220 Using metro 17 Using the Macintosh keyboard 72 Using the slider 28 Using timers 120 uslider 48 Uzi 346 V v 90 value 90 variable 77 variable global 90 varispeed playback of sequences 210 360 376 422
330. metro So you can see that comparisons can be used in a patch to decide when to trigger another object Patch 3 shows the use of sel to look for a certain pitch being played on your M IDI keyboard look for the note play ao Major chord 52 Tutori al 15 M aking decisions with comparisons The pitch is first sent to an object which divides it by 12 and sends out the remainder Sincethe noteC alwayshas aM IDI key number which isa multiple of 12 such as 36 48 60 etc the out put of the 12 object will be 0 whenever thenoteC is played Each time thesel object receives the number 0 from it sends a bang to the message boxes which send thenotesC 2 G2 and E3 48 55 and 64 to noteout T hese pitches are combined with the velocity of thenoteC that is being played on the synth so the chord has the same velocity and duration as the note being played In this example wetest to seeif thepitch being played is equal to C When thisistrue thechord is triggered Combining Comparisons with Or or And The object means or If either the left operator or the right operator is non zero true Sends out thenumber 1 If both operators are0 it sends out 0 The object amp amp means and If the left operator and theright operator are both non zero amp amp sends out thenumber 1 Otherwise it sends out 0 and amp amp are used to combinetwo comparisons into asingle statement such as a is greater
331. mostof thefilesnecessary for aprogram that you writeinto a single group called a collective Once you have donethis you can be assured that all the necessary subpatches and data are available to your patch You can also give your col lective to someone ese to use without worrying whether you ve included all the necessary files If the person you give your collective to doesn t own M ax you can give but not sell them the M axM SP Runtime application along with your collective This will allow them to run but not edit your program Finally you can combineacollectivewith acopy of M axM SP Runtimeto createastandaloneappli cation which requires neither M ax nor M axM SP Runtimein order to run Making Your Own Program A program written in M ax most commonly consists of one main patch aM ax document which contains other subpatches as objects insideit A Iternatively you might choose to design the program so that the user keeps two or more different patches open at once for doing different tasks In either case at least one patcher window has to be opened by the user and this is referred to as a top level patch A collective can have morethan onetop level patch and each onewill be opened when the collective is opened Other patches used as objects within a top level patch are called subpatches To make your own program into a collective you ll need to determinewhich patch or patches will bethetop level patch for the program W hen
332. mouse click event function onclick x y worldx sketch screentoworld x y 0 worldy sketch screentoworld x y 1 colwidth 2 ncols width of a column in world coordinates rowheight 2 nrows width of a row in world coordinates x_ click Math floor worldxt 1l colwidth which column we clicked y_click Math floor 1 worldy rowheight which row we clicked state x_click y_click state x_click y_click flip the state of the clicked point outlet 0 x_click y_click state x_click y_click output the coordinates and state of the clicked point bang draw and refresh display Our OpenGL graphics world is defined in terms of floating point coordinates in our case between 1 0 and 1 0 Thejsui mousefunctions return coordinates based on which pixel count ingawayfrom theupper left hand corner of theobject box themouseeventoccurred W eneed to convert between these two systems of world coordinates and screen coordinates respectively in order to properly evaluate the mouse events for our grid of circles Thesketch methods world toscreen and screentoworld perform theseconversionsfor us worldx sketch screentoworld x y 0 worldy 1 sketch screentoworld x y r r Onceweknow thewidth and heightwhere we clicked we can subdivide it based on how many cir cleswehaveon each axis colwidth 2 ncols width of a column in world coordi
333. mrs y a ey Serra a0 ot H i Tutorials and Topics Table of Contents Introductio Mren aa he R artes deed stents deed 4 etnad E T 6 TUCO al TsSaying Hallol ic ite chee ach abuts aaah area ate seen E Waren mew ere Mate eared ape eh 8 T torial 2 The bang Meig eieiei pie tual corners edu E EE Oca how EEEN 13 Tutorial 3 About Numbers cas caves ta ete cane aed ge ge used Pace nern eee oa nant aan tas 15 PULO al ASSN Metro enn eree enei kaha ned ona ra reu ea eR a ERT EA DETETA 17 Tutorial 5 toggl and COMMENT ssie iaa A E TE E 19 T torial 6 Test Printing es n T A T a a vue Mon noes 22 T t rial 7 Right to left Order 5 Sedition neon aa a a la Medes 23 Tutorial 8 DoingMathin MaX s tiered nt sua icdal sek du deobean ll sea tcdn ia ts Ween als Waleed ad 25 TU EO rial OU SMG MS SIDED ssania neal a E E A EE A AA MENS 28 T torial LO NUMDE BOX oe ies bane iai onioni pa Mater taney AAE anaes 31 Tutorial 11 Test 2 Temperature Conversion 0 cece ccc c eee e eee eee e ee ee teen enees 36 Tutorial 12 Sendingand Receiving M IDI Notes cece ccc c eee eee eee e teen ene 40 Tutorial 13 Sendingand Receiving M IDI Notes ccc cece cece eee e teen tesa eens 43 Tutorial 14 Slides and Dial ciican coreeearnoree eewihea tear ieremrremieers 46 Tutorial 15 M aking Decisions with Comparisons cece cece ccc e eee e eee eee e ee eees 51 Tutorial 16 M oreM IDI Insand Outs acs irs de ouete een ered ee ie
334. n and some the port names and labels is text All of it will potentially need to bevisibleat onetime and thereshould beaway for theuser to change any of the values at any time All of the above considerations will affect your decisions of screen layout which user interface objects to use and what combination of typing and mousing menus dialogs pop up menus buttons toggles sliders etc is best for getting information from the user You can be guided in these decisions by observing other effective applications and by considering any real world mod els that might provide a good example Designing Your Own Buttons Aswasdemonstrated in Tutorial 19 you arenotrestricted to using M ax sbutton object or message box for respondingto mouseclicks You can design your own button in apainting or drawingpro gram place it in a Patcher window with thefpic object or by copying it and using the Paste Pic turecommand in theEdit menu and then cover it with atransparentubutton T hat sthemethod used for the track on off buttonsin this program We drew a picture of four buttons used fpic to display the picture and placed four ubutton objects on top of it To be surethat the fpic is behind thetransparent ubutton objects so that the mouse clicks will go to the ubutton objects and not thefpic we simply selected the fpic and chose Send to Back from the O bject menu If you select aubutton and choose Get Info from the O bject menu yo
335. n issupplied in theright inlet Transposition in semitones Thetransposer isnot a built in M ax object It s a patch that we created and stored in afile named transposer e Doubleclick on thetransposer object to seeits contents In previous patches wehavesimply sent thepitch to a or object to transposeanote W hy do we need asubpatch likethis just to transpose notes T he advantage of the transposer over asimple operator isthat thetransposer ensures that note offs are transposed by thesameinterval as their corresponding note ons even if theinterval of transposition changes whilethe note is being held down If anote off message is transposed by a different interval than its note on was transposed the note on will never get turned off and thenotewill bestuck on thesynth T hetransposer solvesthis 101 Tutorial 27 Your object problem by keepingalist ofthenote onsand their transpositionsin an object called funbuff then looking up thetransposition when thenote off is played This patch trans poses Pitch Velocity Transposition motes ald makes sure Ej that mote offs get the same transposition as Only mote ons note ons even if the get through the interval of transposition ert ae aml changes while the note store gate Sree Hote on wntrans posed pitch and transposed pitch are shored as an x Y pair Hote on and note off the transposed pitch is sent ow triggered by the f l vntrans posed pitch in
336. n mode for the objects which can bechanged to fine tunethe order in which the objects are recalled to a saved state and how objects respond to an in between state see below e Click on themessage box labeled storagewindow attached to thepattrstorage A window with alist of the control objects should appear Createa setting you like with the four objects that control the drawing machine Once you haveasetting you re happy with click the button object attached to theint object abovethe pattrstorage This will send the message store 1 to pattrstorage Sending astore message followed by an integer value tells pattrstorage to capture the current state of all exposed objects and savethem asa preset or state in anumbered slot insidetheobject The slot will then recavea column in thestorage window showing usthenumber of theslot as acol umn header with all the appropriate values tabulated below it State 0 is a special slot that allows you to savea state temporarily without having it savein afile see below 304 Tuto ri a 53 M orepatcher storage e Now that you vesaved a preset change oneof the pattr exposed objects W atch how the stor age window responds aan client list name o prior ity interp data E angle 0 lin 44 5 desyvnch 0 lin ba offset 0 lin 3 645 range a lin 61101 W hen you makeachangeto an object that deviatesfrom themost recently saved or recalled preset slot thevaluefor the appropriate object
337. n our patch and thereforeis changed by abang method in our code thereverse Sets whether or not our sequencer isrunning backwards This is set by the reverse message to our js object thevalues An array see below of values reflecting the state of the uslider objects in our patch Thefunnel objectin our patch sets these values by sending lists to our object 262 Tutorial 49 Advanced scripting Thenew Array constructor creates arrays in JavaScript The array variable thevalues above has 128 elements which are accessed by bracket notation following the array name e g k thevalues 5 will set the variable k to the value of thesixth element starting from 0 of the array thevalues thevalues n 55 will set the elementn of theour array thevalues to 55 N otethat JavaScript treats A rrays as objects so that k thevalues length will set the variablek to thenumber of elements in the array thevalues For more information on this consult any good JavaScript reference After our variable declarations wehave variables that wewill useto referencedynamically created objects in our M ax patch These variable names are used internally in our JavaScript code so that wecan create connect delete and modify objects all through properties to these objects O bjects in jsthat refer to M ax objectsin apatcher arereferred to asM axobjs W ehavethefollowingM axobj variables in our script controlin An array of M axobjst
338. n the little M ax icon next to the track name you can view and even edit the action patch for that track If you have morethan onetrack using the same action any changes you make and save in that action patch will immediately affect all of those tracks You can save the entire contents of an individual track in a separate file its track name action name and all its events then reload that track into atimelineat a later time If you click onceon the little M ax icon in atrack and hold the mouse button down you will be presented with a pop up menu which gives you two choices O pen Track File and Save Track As for saving and reloading an individual track The Display pop up menu lets you alter the look of your timeline window to suit your needs You can display the Time Unitsin one of several different formats M illiseconds M idi Clock or SM PTE format of M inutes Seconds Frames 24fps 25fps or 30fps You can collapse tracks down to asingleline of vertical space thus allowing you to see many tracks at once or you can expand them back outto their full height to seeall of their contents You can chooseto Show M ute Buttonsin theleft part of thetracks thesebuttons are useful for suppressingtheeventson individ ual tracks A nd with the Autoscroll W hile Playing option you can choose whether thetimeline display should follow the progress of time or remain stationary when thetimelineis being played All settings you specify in
339. n theseparatefilein which it was created 103 Tutorial 27 Your object Theseparate file containing your object must bein afolder where the patch that usesit can find it M ax looks for filesin the following places e Thesamefolder asthe patch that is using thesubpatch e Thesamefolder astheM ax application e Anyother folder you havespecified in the File Preferences dialog under Look for filesin For moreinformation about File Preferences seethe M enus chapter of the Getting Started manual Theother main differenceis that if you save your patch whilethesubpatch window of thepatcher object isopen it will beopened automatically each timeyou open themain patch Thisisnottrue of asubpatch that is saved as aseparatefile Beware of Recursion A patch that is used as an object in another patch can itself contain subpatches For example our transposer object could havebeen written to contain asubpatch object called splitnote which sepa rated note on messages from note off messages A subpatch object may not contain itself however sincethis would put M ax into an endless loop of tryingto load a patch within itself ad infinitum For example our transposer object could not itself contain atransposer object or any subpatch that contains atransposer object Documenting Your Object You can see that thetransposer object has been copiously commented and all of its inlets and out letshavebeen given Assistancemessages Such thorough doc
340. n thetimeline provided thatthemod wheel hasnot been returned to its 0 position EAE io eenia POC CE c Footed bang So at time 8002 the timeline will start the movie play afour note chord and begin bending the pitch then at time 10000 it will relocate itself to time 8001 and continue playing until the mod whee isat 0 at time 10000 Note because you have the Overdrive option checked which is nec essary for theM IDI datato besent out with theproper timing theQuickTimemoviemay move jerkily or intermittently depending on thespeed of your CPU You may recall thatin the action patch thenote messages received from thetimeline thefour item lists in the above example get passed out the second outlet of thetimeline object T ticmd note 1 ti ut 2 e Bringthe41 Timeline Patcher window back to the foreground to seewhat happens to those note messages Theliststhat aresent from thetimelineasnote messages comeout thesecond outlet of thetimeline object where they are broken up into individual numbers by an unpack object The first three numbers in each note message go directly to anoteout object to be used as the pitch velocity and channel information of aM IDI note on message The 1st 3rd and 4th numbers of the note mes 188 Tutorial 41 TimdineofM axmessages sage also go to a pipe object wherethe 4th number is used as the number of milliseconds to delay before sending on theother numbers timeline tutorial4i ti
341. n which messages will be sent 390 Deb U gg ng Tipsfor debugging patches Tracing Messages When you reworking with a complex patch it may be difficult to analyze the order of messages at aglance going into and out of subpatches memorizing what has happened so far etc Fortu nately M ax has a message tracing feature which displays the order of messages to you by blinking the patch cord through which a message is about to be sent By choosing Enable command from the Trace menu you enable M ax s message tracing feature Note You cannot enable message tracing if Overdrive is enabled in the O ptions menu and you cannot enableO verdriveif messagetracingison You then set thepatch into action causea mes sage to be sent by sending ita M IDI event entering a keystroke on the computer s keyboard or clicking on a user interface object with the mouse M ax will blink the patch cord through which themessageis about to besent and will reportinformation in theM ax window about thesending and receiving objects and the message that is being sent From that point on each time you choose Step from the Trace menu M ax moves on to thenext message to be sent flashes the patch cord through which it will travel and reports about it in the M ax window In this way you can step through the workings of your patch at your own pace 0 O Max 1990 2003 Cycling 74 IRCAM int 94 from hslider to number gt int 94 from number t
342. naming and the bindto attribute pattr objects can control other M ax objects through patchcord connections 297 Tutorial 5 Patcher storage Thenotes subpatch shows two possible ways to do this 1 Usingthepattr object itself to storethedata 2 Automatically binding apattr object to an object using the pattr object s middle outlet Internal Storage If apattr object is unbound it will store any messages sent in its left inlet and recall them from its leftoutlet M essagessentto an unbound pattr object from apattrhub object will echo out of the left outlet as well e Unlock thenotes subpatch and attach an hslider object to the left outlet of one of thepattr objects named val_a val_b val_c or val_d Recall thepattr objects states by clicking on themessage boxes in the main patch Scroll thenumber box attached to thepattr object The hslider object should move as well pattr mod_d Prepend set Thepattr objects controlling our pitches arenot bound to any single object and are maintaining thevalues of thenumber boxobjectsattached to them not by referringto theobjectsdirectly but by receivingtheir valuesas messages A saresult thenumber box objects attached to thesepattr objects can bedeleted and replaced with other objects or morethan oneobject Becausethepattr object outputsits valueswhen changed either directly or remotely wecan easily attach multiple objects to thepattr object to set and display
343. nates rowheight 2 nrows width of a row in world coordinates W ecan then plugin thecoordinates of themouseclick to figureout which circleweclicked nearest to x_click Math floor worldxt 1l colwidth which column we clicked y_click Math floor 1 worldy rowheight which row we clicked W ethen reverse the element of the state array corresponding to thecircleweclicked state x_click y_click state x_click y_click 288 D esigningU ser Interf Tutorial 51 esigning ett After we ve set the statearray correctly we send out alist corresponding to thechange out our jsui object s outletinto M ax W ethen bang our own jsui object updating the graphics to reflect the change outlet 0 x_click y_click state x_click y_click bang N otethat wehaveset our onclick function to belocal so that it can t betriggered from an onclick message sent from our M ax patch e Familiarizeyourself with the avaScript code and how it relates to the behavior of thejsui object in the patcher Click on thetoggle object to activate the metro object at the right of the patch T hiswill simulatesomeinput from theuslider objects Placepost statements in the JavaScript codeto help navigate the values as they are passed from mouse click to list output Summary Thejsui object isa powerful tool to allow you to design and implement customizable user inter faces using JavaScript as a programming language T
344. nc does not interpolate between points that is it does not supply intermediate points along theconnecting linesegments In order to make timeline interpolate the values between points fill in the ramps between points select the efunc choose Get I nfo from the Object menu and enter a nonzero value for Interpolation Time Grain T hisnumber will deter minetheresolution of theinterpolation A valueof 1 will providethehighest resolution interpola tion causing efunc to report its current valueto theticmd object every millisecond A value of 100 will cause efuncto report every tenth of a second and so on Choosing Get Info from theO bject menu also allows you to set therange of the x y graph by specifying maximum x and y values for efunc coordinates You can also enter a label which will link the efunc editor to afunbuff object of the same name Oncean efunc editor is linked to afun buff object you can still edit the funbuff through the efunc editor and changes will be reflected in all funbuff objects sharing its laba Horizontal resizing of theefunc editor has the same effect as resizing the etable editor changing the total duration in which the numbers are sent out when thetimelineis played but does not change the time grain of the interpolated output 368 TI mel Ine Creatinga graphicscoreofM ax messages The emovie editor Asexplained earlier when you create a new timeline track and thus assign it a particular ac
345. nced M ismatched parentheses brackets and braces arecom mon causes of syntax errors H elpfully js attempts to isolate which line theerror occurred on the line cited to you may beslightly different depending on where you placed your post state ments e Gototheoffendinglinein your avaScriptcodeand closetheparenthesescorrectly W hen you save the code all should be well again M isspellings are another common cause of mistakes in JavaScript 253 Tutorial 48 BasicJavaScript e Rewriteoneofyour post statementsso that theword post isspelled wrong feel freeto be creative here Save your script Something like this will appear js Compiling Functions and Executing Global Code Hi There eerror js Javascript ReferenceError pst is not defined line 15 A referenceerror means that wetold J avaScript to executea command that it simply didn t under stand Whilepost isinitsvocabulary of legitimatecommands pst isnot N ote JavaScript stopped executing our global codeat the point wheretheerror occurred In the casejust cited thewords H i There were printed in the M ax window but the value of x 0 66 was not This gives us an important clue asto wheretheerror lies i e somewhere between the two Usingpost statements liberally in thedevelopment phase of your js codeis just as important as using print objects for debugging in M ax You can alwaystakethem out later e Correct your spelling and save you
346. ne or more messages to a par ticular ticmd object in that track s action You place an event onto thetimdineby O ption clicking on Macintosh or Alt clicking on Windows in the right side of the track This reveals a pop up menu of names corresponding to the names of ticmd objects within the action You can also place 363 TI mel Ine Creatinga graphicscoreofM ax messages an event in atimelinetrack simply by clicking in the event portion of thetrack and holding the mouse down until the pop up menu of possible events appears then choosing the event CY mnm 144 44 O B b gt gt gt i F 00 00 00 i 00 04 06 ara Display 9000 00 00 04 00 00 08 00 00 12 00 00 16 0 SE es at 1 A PrintThree printint gt printfloat printsymbol EE Add Event to Track 1 marker When you chooseacommand namefrom thismenu you are actually specifying which ticmd object you want to send a message to Based on theb f s or a arguments in that ticmd object in theaction thetimdine knows what kind of message is appropriate for that event and places an object known asan editor for that message in thetrack When you place an event that sends a bang a symbol or alist M ax will give you an editor known as the messenger T he messenger looks just like the message object except that it has a label show ingthecommand name of theticmd object to which its message will be sent 80 80 Untitled 144 44 0 E Db
347. need to be aware of two details The first detail is that line sets out interpolating from its starting point immediately without pausing and without necessarily first outputting its starting point value So specifying a 3 5 second line from 0 to 35 in oneof the ways shown in the following example will not give us quite the desired results set 0 35 3500 line 100 Goes bo zero but doesn t output it then starts counting from 1 A second detail worth knowingaboutline isthat itactually travelsto its destination in lessthan the specified time It will output numbers at the rate specified by its grain of resolution the rate specified by its second argument or by anumber received in itsrightinlet aslongasthetotal time elapsed is less than that specified in its middle inlet So in the preceding example it will actually arriveatits destination valueof 35 in 3400ms By givingit aslightly longer time weallow it to take 3500ms in 36 steps including thefirst immediate output so the first step starts at 0 Creating a New table Therearethree easy ways to create a new Table file 1 ChooseTablefrom the N ew submenu of the File menu to open anew table editing window Draw in the values you want then choose Save from the File menu to save the table values 2 Create anew table object which will automatically open anew table editing window for you Thenew table can besaved asa separate file before closing the table editing window or yo
348. ng 391 viewing 386 389 message box 92 message lookup 341 message object 9 92 as a data structure 349 changeable argument 351 punctuation in 355 message type 341 messenger 184 364 metro 17 MIDI connecting MIDI equipment 6 port specifying 138 MIDI channel filtering by 141 343 specifying 41 MIDI device list 221 226 MIDI Enable Disable 180 MIDI file 148 360 376 MIDI note name displaying 34 MIDI objects 40 midiformat 140 midiin 138 midiout 138 midiparse 139 modular programming 339 modulo 25 monitor monochrome 197 Monk Thelonius effect 108 More MIDI ins and outs 56 Mouse control 175 mouse control 46 418 Index mouse status and location 176 mousefilter 175 MouseState 176 mtr 155 multiplier of a slider or dial 29 multi track MIDI file 360 376 Multi track sequencing 155 multi tracking 155 mute a timeline track 372 N New Object List 11 notein 41 note off message filtering out 44 supplying 43 noteout 41 Now 107 number 15 typing on the Mac keyboard 31 74 Number box 15 31 as a debugging tool 388 Number boxes 31 Number groups 115 numkey 74 O object box punctuation in 355 objects aligning 12 creating 10 nonexistent 394 size of adjusting 20 70 using a patch as an object 101 octave parallel octave patch 41 random octave transpositions 112 offset of a slider or dial 29 omni mode 41 one or both numbers are not zero 53 onscreen control 46 Open 8 Open Track File 372 or 53 ornamentation patc
349. ng 80 120 142 344 inlet Assistance description 100 inlet object 99 int 15 77 interface design 220 interpolate between points 368 interval 402 interval of timing resolution 402 inverting pitch values 49 invisible objects and patch cords 67 iter 115 417 J js methods and scheduling 275 K key 72 key commands 211 keyboard commands 72 entering numbers 74 keyboard onscreen 221 keyboard slider 46 keyup 75 kslider 46 L label mode for umenu 225 labeling with text 225 lcd 201 led 180 limiting numbers to a specific range 48 72 limiting the speed of a stream of numbers 58 line 121 linear map of ranges inverse 113 linear mapping of ranges 111 list combining numbers into 116 161 convert to a series of numbers 115 convert to separate numbers 115 in left inlet 27 loadbang 179 disable defeating 334 suppressing 225 loading a patch 341 locking and unlocking a Patcher window 9 loop 344 looping 80 looping in a timeline 372 M main patch 339 makenote 43 Making decisions with comparisons 51 Managing messages 92 Managing note data 43 Managing raw MIDI data 138 mapping a range of numbers 111 marker in a timeline track 372 Max Preferences 334 Max messages to 401 Index MaxMSP Runtime application 326 memory usage 343 menu bar changing 224 hiding and showing 402 menu object 163 350 Label mode 204 menubar 224 message append arguments at the end of 93 prepend one before another 93 reversing order of two numbers 116 traci
350. ng at theindex specified in the argument For example follow 10 causes the object to look for incoming pitches that match the 10th notein the score W hen the matching pitch is received follow sends that pitch out its right outlet and sends theindex outits left outlet 150 Tutorial 35 seq and follow Thefollow object even allowsfor wrongnotes so if theperformer playsacoupleof spuriousnotes or skipsanoteor two follow will still beableto keep track of theperformer s progress through the score Onecan also step through the score with repeated next messages After a follow message has been received the message next triggers the pitch at the specified index and increments the pointer to thenext index An Attentive Accompanist W hen weusethe index numbers from the left outlet of follow as addresses of atable or addresses of some other array object likefunbuff theindex numberscan trigger other values In thisway we can createan accompanist who knowsthescore and followsalongwith theperformer Eachtime the performer plays a note of the score the accompanist has a specific reaction play a simulta neous note or notes play some independent melody rest whatever and seemsto follow along with the performer W e vemadesuch an accompanist in Patch 2 Theaccompanist playstheleft hand part of theBach E minor bourr ewhileyou play theright hand part T hefollow object has loaded thesequencefile bourr e sc to use as the score E
351. ng dynamically 143 specifyingin M ax 143 port setting for MIDI objects 232 pound sign 295 pow function 221 preempt 329 prepend 97 preset 171 288 print 8 asa debugging tool 335 priority of asprite 203 probability 111 138 297 Probability tables 138 program change pgmin 60 pgmout 60 punctuation in amessage object 295 in an object 295 Q quantile 297 QuickTimemovie 188 205 310 quit 329 R r94 random 89 random notepatch 89 random number weighted randomness 297 without repetitions 213 range of aslider 29 Index receive 94 recorder patch 160 recordingin non real time 222 322 rect 200 recursion 108 127 refresh 329 relational operators 54 relative path 255 repeat actions 284 repeated note patch 83 173 Resume 345 rhythm analyzing 139 creating with delay 89 123 Right to left order 22 ritard following aperformer 158 route 65 routing messages to different destinations 55 63 76 runtime 329 S s94 SaveT rack As 313 Saying H ello 7 scheduler 328 345 score of M ax messages 188 scoreof timed messages 302 score reading object 155 Screen aesthetics 70 script for menubar 230 scripting basic overview 233 bring to front 252 command syntax 235 connecting objects 236 creating objects 238 deleting objects 244 disconnecting objects 236 hiding objects 251 moving objects 249 offset messages 250 replacing objects 245 resizing objects 249 responseto mouseclicks 252 send to back 252 s
352. ngein response Theoutput number is displayed using the multislider object in the patch and gener ates M IDI notes As you increasethe value going into thejs object above 3 0 the value gener 249 Tutorial 48 Basic avaScript ated by our js object will begin to oscillate between ahigh and alow value At higher values e g above 3 5 the output of will become chaotic lt slowly increase this number watch what happens when it goes above 3 0 logistic equation js popu js D gt 0 242424 Thejs object in this patch simulates a simplechaotic function called thelogistic population equa tion Thebasic formula for thefunction is f x rx 1 x wherer isthecurrent input value and x isthe previous output value 250 Tutorial 48 BasicJavaScript e Double click thejsobjectin theT utorial patch A texteditor will appear containingthesource code for thejs object in the patch This codeis saved asa file called popu js located in the same folder as theT utorial patch eee popu is Jy popu js if simulates the logistic population equation ff fix rx 1 fi input is r output is current x fi ff rid 5 04 ff J indets and outlets inlets 1 outlets 1 global variables var x 0 66 di float men the equation once function msg_floatir x F x 1 x outlet O x H Al bang post the current population to the max window function bangi posti the current population
353. nic command is chosen from the M odify menu Command P on M acintosh or Control P on W indowsistyped abang issent to theuzi 16 object in each track which proceeds to send out an all notes off message continuouscontroller 123 with a valueof 0 on all 16 channels to theoutput port of that track Thisis the best way to implement a quick panic command for stop ping stuck notes on thesynth Summary W ith someattention to programming and designing theuser interface aM ax patch can bemade into afinished application for distribution to others Themenu bar can be customized with new menusand commandsusingthemenubar object Thewindowsof all constituent patches and sub patches can besized placed and customized precisely and automatically using thethispatcher object N ew onscreen buttons can bedesigned in agraphics program placed in a patcher and madeclickable using theubutton object And M ax s user interface objects can be nested in apic turethat was designed in agraphics program making them look like part of the picture You should choosethecolors and fonts in the graphics you design not only for attractiveness but also for functionality and clarity Thepicturein a patcher can be changed using pict messages to fpic T ext labels can be changed by sending item numbersto a menu in Label mode Devicenamesin the current M IDI setup can be obtained using themidiinfo object and placed in amenu object Thenames can then besent to M IDI objectsto change
354. nlet The vast majority of objects are triggered by input received in the left inlet Input received in the other inlets is usually stored for later use e Intheupper examples click on the message boxes above the operators Notice that the number coming in the right inlet has to be received beforethe number in the left inlet is received T hat is because the message received in the left inlet triggers the calculation with the most recently received numbers If you haven t supplied a number asa typed in argument and no number has been received in theright inlet 0isthedefault argument for the and objects and listhedefault for and 25 Tutorial 8 Doingmath in M ax Int or Float Output You may havenoticed that the object sends out 8 as theresult of 25 3 That s becausetheoutput isan int and is truncated before being sent out All the arithmetic operators send out an int asthe result unless they have atyped in argument that contains a decimal point in which case they are converted to float Thetwo division programs at the bottom right corner of the Patcher window demonstrate con verting from onetypeto another The first program removes the decimal part of any float num bers it receives It performs the operation 12 2 and outputs a result of 6 Thesecond program divides the numbers 12 75 and 2 5 as floats and gives a full float output because its typed in argu ment contains a decimal point If you want an operator
355. not betriggered by a word becauseit will try to understand the word assomekind of command H owever if the word is preceded by symbol the message box will be triggered and the word will replace a 1 changeable argument in the box Editing the Contents of coll To view and edit the contents of a coll double click on the object and a Text window will open If you make any changes to the Text window you will be asked whether you want to keep those changes in thecoll when you close the Text window Thecontents of acoll arewritten in aspecific format For details look up coll in theM ax Reference M anual Saving the Contents of coll Once you have stored messages in coll you can set it to save its contents as part of the patch You unlock the Patcher window select the coll object choose Get Info from the O bject menu and check Save coll with Patcher in theI nspector window Alternatively you can savethe contents of the coll as a separate file so the contents can be used by morethan one patch To do this open the coll object s Text window and choose SaveAs from the File menu Another way to save the contents as a separate file is to send awrite messageto the coll object which opens a SaveAs dialog box To load afileinto a coll object typethenameof thefilein as an argument or send coll a read mes sage which will causetheO pen Document dialog box to appear Storing Chords in coll e Double click on the patcher coll_ examples o
356. ns that will result in improper messages being sent to an inlet For example M ax will let you connect the outlet of a message box to almost any inlet because theres no way of knowing what message will come out of the outlet In such a case the error does not become evident until you test the program and the message is actually sent lt objectname gt message too long lt message gt A message was sent that contained morethan 256 elements lt objectname gt missing arguments for message lt message gt Occurs when an object receives a message that it understands but one or more of the expected arguments in the message is missing Check the object s input description in the O bjects section lt objectname gt No such object Occurs when creating anew object or loading a document W hen you are editing a patcher and 393 Erro rS Explanation oferror messages youtypethenameof anonexistent object into an object box orthenameof an object or subpatch that isnotin M ax s search path M ax produces this error message When you open adocument that contains an object that M ax cannot find either becauseit is not located in M ax ssearch path or becauseitjust doesn t exist M ax displaystheobjectasif it existed except that the object name is surrounded by a dotted outlinein the object box and an error mes sage is printed in the M ax window This preserves the connections to the object box in case you can retype the object to cre
357. nt and sets thedial without triggering any output so the data won t be echoed back to thesynth W hen you changethedial the data is transmitted to thesynth with clout Because they can communicatefrom onePatcher window to another send and receive objects allow you to send messages back and forth between a patch and an embedded subpatch inlet and outlet Objects e Nowbringthekeyboard window to theforeground and unlock it to seethe hidden objects At thetop of thesubpatch you see two inlet objects inlet object outlet object W hen you includean inlet or outlet object in asubpatch acorrespondinginlet or outlet is created in thepatcher object in the main Patcher window Thisis usually the most efficient way to send messages to and from asubpatch Messages inthe inlets of the patcher object N a patcher keyboard Come out the inlet objects in the subpatch 99 Tutorial 26 T hepatcher object Assistance W hen Assistanceis checked in theO ptions menu M ax gives you information about the inlets and outlets of objects while you are editing a patch Every time you placethe mouseon an inlet or an outlet a brief description of that inlet or outlet is printed in the bottom bar of the Patcher win dow You can giveA ssistance descriptions to theinlets and outlets of your patcher object To do so select theinlet or outlet object in your subpatch and choose Get Info from theO bject menu You can typein adescription which will sh
358. nt rectangular pill on the right side of the window that can be used for toggling between locked and unlocked state e Usingoneofthesemethods unlock thePatcher window You should beableto seethe palette You can now modify the program The first two items in the palette are the object box and the message box CC BREEARGE E gt Message box Object box Modifying the Patch Now well producea program that prints G ood bye e Click on the object box in the palette T he cursor turnsinto an object icon Click insidethe Patcher window near the bottom right corner A list of pre defined M ax objects called the New Object List will appear If the list does not appear it s because New Object List isnot checked in theO ptionsmenu You can bringup theO bject List by O ption clicking theempty 10 Tutorial 1 Saying H ello objectboxon M acintosh or Alt clickingtheemptyobjectboxin W indows Or ifyou wantthe list to always appear check New Object List in the Options menu All Ob jects Control ler Data 1 Dev ices i n Graphics l Interaction l Librarians Ea Lists a Math amp Messages BS MILI w MSF Analysis wY MEF Delays MSF FFT MSP Filters x MSF Functions MSF Generators Scroll down through theright hand column of the New Object List until you seeprint click on the word to select it and typethe Return or Enter keyson M acintosh or the Enter key on Windows
359. nts in terms of that new point That s why you click on the bottom left corner of the pitch velocity box before starting Weve situated a tiny ubutton object 176 Tutor al 39 M ousecontrol on thecorner of the box so when you click there it triggers a zero message to mousestate and sets that point asthe new 0 0 point mousestate also reports the status of the mouse button It sends out 1 when the button is pressed and 0 when itis released W eusethisfeaturein our patch to control the metro object which sends bang messages to mousestate Since metro only sends abang when the mouse button is down mous estate only sends out location values whilethe mouseis down House State Thetwo right outlets report the changein location since the previous report The horizontal loca tion thevertical location and the changein vertical location are used in this patch to supply val ues for pitch velocity and tempo Each rangeof values has to belimited and processed slightly differently to placethe valuesin an appropriate range For example the pitch velocity box is 256 pixels wide so welimit the horizontal location values between 0 and 255 with asplit object then dividethen by 2 to get arange of pitches from 0 to 127 Theboxis128 pixelshigh butremember that vertical location ismeasured from top to bottom so when themouseisin the box the vertical values will range from 0 to 127 W ethereforelimitthe vertical values between 127 and 1 and u
360. nwieldy Comparethesetwo patches sprintf script send numbox i i thispatcher Sending to many objects using script send 232 Tutorial 46 Basic scripting N ot only doesthe second patch eliminatethegate and thesend objects but thereisno need for receive objects on theother end Thereceiving number box objects simply haveto benamed In this case each number box has a name starting with numbox and ending with a number These names can easily be generated by thesprintf object Another important use of the script send message isto send messages to objects that don t have inlets such as comment For instance in thefollowing example werepatch objects and updatethe text of the comment located to the right of the number 0 vibrato 1 tremelo vibrato 1 tremelo pO tremelo depth vibdepth Script disconect mynunmbox O tremsend 0 Script connect mynumbox O yibsend Script send mycomment set vibrato depth tremdepth Script disconnect myrnumbox tremsend 0 Script connect myrumbox O yibsend Script send mycomment set vibrato depth script disconect myrumbox 0 yibsend Script connect mynumbox O tremsend script send mycomment set tremelo depth Script disconnect mynumbox 0 yibsend Script connect mynunbox 0 tremsend Script send mycomment set tremelo depth Changing comment text using scripting and repatching objects using script connect script disconnect You could als
361. ny one of three actions typethe Return or Enter keys on M acintosh or the Enter key on Windows type 31 Tutorial 10 Number boxes the Enter key on M acintosh or the Shift and Enter keys on Windows or click anywherein the Patcher window outside of thenumber box e Whileanumber box is selected in a locked Patcher you can also raise and lower thenumber in it by pressing the up and down arrow keys Holding down one of these arrow keys moves the number up or down continuously just as if you were dragging on the number box with the mouse You can seethat the number box is useful both for displaying the numbers received in theinlet as in the case of thenumber box below theslider and for allowing you to send numbers by typing them in or dragging with the mouse T hesecond patch shows thenumber box in both uses for sending numbers to the object and for displaying the result e Send anumber to theright inlet of the object either by dragging on the number box or by clicking on it and typing in a number Remember we want to send a number to the right inlet first because the left inlet isthe onethat triggers the addition e Nowsend anumber to the left inlet of the object and you will see the result of the addition in the bottom number box 32 Tutorial 10 Number boxes Number box Range You can set many characteristics of anumber box how it functions and how it looks by select inga number box and choosing Get Info fro
362. o int 14 from to int 15 from to In T racemode thepatch cord flashesand themessageisprinted in theM ax window Alternatively you can choose Auto Step from the Trace menu and M ax will step through the dif ferent messages at a constant moderately fast rate reporting as it goes If you choose Continue from the Trace menu M ax will go on tracing but at full speed Beforetracing messages you can select oneor moreparticular patch cords when thePatcher win dow isunlocked and choose Set Breakpoint from the Trace menu T hat will cause message trac ing to pause each time a message gets sent through one of those patch cords In that way you can move through the messages at full speed with the Continue command and M ax will pausewhen 391 Deb U gg ng Tipsfor debugging patches itreachesthepatch cord you havedesignated asa breakpoint allowingyou to examinethestateof the patch at that moment Error Messages If you makea programming error M ax will often print an error message telling you about the mistakein theM ax window M anyerrorsarereported whileyou areeditingin thePatcher window such astryingto putan objectinto your patch that doesn t exist but other errorsdo not become evident until you actually run your program such as sending a certain messageto an inlet that doesn t understand that message A list of error messages likely causes of each message and pos sible solutions can be foun
363. o button near thetop of its Inspector N oticethat the control doesn t display thecorrect portion of the picture until after you vesetits mode Thisisbecausepictctrl uses different regions of thepicturefilebased on which modeit s using and how you havethe various properties set using the checkboxes in the Inspec tor Inactive States Controls created with pictctrl can havea separate set of images for their inactive state You can use these images to indicate that the control won t respond to mouseclicks similar to how the M acin tosh greysout inactive controls 316 Interfaces U singpicture based user interface objects In pictures for pictctrl theinactive images appear below the regular images In the following pic ture found in thefileLED button w inactive pct we veadded inactiveimagesto our light up but ton Theimages are blurred to indicate that the control isinactive N oticethat there aretwo inactive images onefor thecontrol when its valueiszero and onefor when thevalueisone To usethispic turewith thepictctrl object s toggle mode you would check H asInactivel magesin thel nspector Image Masks All M ax objects havearectangular bounding box which defines their location and size You can create controls that haveanon rectangular appearance by using a feature called masks M asks are special images within picture files that define which portions of the images are visible and which portionsaretransp
364. o design graphical user interface objects for usein the M axenvironment The avaScriptimplementation for thejsui object issimilar to that used in thejs object with an added API that supports two and three dimensional vector graphics drawn with OpenGL commands It also includes methods for handling mouse interaction in thejsui object window In addition to the advantages provided by JavaScript jsui provides a number of built in features that make UI development flexible e jsui objects draw their geometries relativeto thesizeofthejsui object box resizing ajsui object will correctly resize all of the drawn elements inside of it e jsui objects work with a vector graphics language OpenGL that supports a wide variety of simpleshape and drawing primitives In addition anumber of higher level graphics func tionsareavailable T hejsui object can also perform anti aliasing on the imageto give you as smooth an object as possible though this comes with adecreasein performance e Thejsui object allows you to draw ascenethat exceeds the boundaries of the object box By adjusting the camera orientation in theO penGL space you can create and manage different views of thesame U I object In addition to using thejsui object for user interface design onecould usethe object simply as an OpenGL graphics engine built into the M ax patcher for algorithmic drawing operations ThisT utorial assumesthat you vealready looked atthe avaScriptT utorials
365. o load a movie the word read followed by thenameof a moviefile set the volume and start the movie all from within atimeline viaticmd eco Untitled majaa a a b pe ee po 00 00 00 08 06 Track Display 0000 00 000400 00 0800 O0A20 eres not enna ore conn etiee T hr T E playmowie cantrolmowie start controlmowie wol 255 controlmowie read globe spin mow oe ee ee S H a One Inch Four Seconds pale 4 Features of the timeline Window In theupper left corner of thetimelinewindow therearetaperecorder likecontrolsfor playingthe timeline N extto thecontrolsthereisaclockicon and adigital readout ofthe currenttime asrec ognized by thetimeline the current point of the timelines progress The current time is also indicated by the little arrow indicator on thetimeline itself N ext to the current time the current 370 TI mel Ine Creatinga graphicscoreofM ax messages cursor position is displayed T his is useful as a reference for placing events accurately in atrack with the mouse Kove current time Kove current time back on timeline Loop forward on timeline Sti Pla Ga to End Goto oF Y n beginning ia da o a bee ph 1 po 00 00 7 00 04 15 Track Display 00 00 00 00 04 00 00 08 00 TE Be 1 playmowie Current time You createanew track by choosing an action from thepop up menu labeled Track In theleft part of the track you are shown thetrack number and thetr
366. o make it as well organized attractive intuitive Clear and user friendly as possible This chapter presents a complete application written in M ax and discussesa variety of issuesto consider when planning your application and designingits user interface Because this patch is considerably more complex than any of the other examples in this Tutorial we won t go into extensive detail trying to explain how it works Well leave that for you to investi gateon your own if you recurious Rather we ll try to point out someofthevisual design decisions that were made and some ways of implementing certain user interface features T his chapter will show how to plan the layout of your program how to modify windows and the menu bar to your liking how to add graphics to customize the look of your program and how to decidethe best way to present information to and get input from the user The Note Modifier Program Theexampleapplication called N ote M odifier is a four track router channelizer transposer inverter randomizer delayer of M IDI note messages The four tracks of modification work in parallel separately and simultaneously and can beturned on and off individually T he actual modifications performed in each of thefour tracks are in series the output of one goes into the input of thenext and can be turned on or bypassed individually In addition the program pro videsan onscreen imitation keyboard so that notes can beplayed w
367. o ranges of numbers using thelin ear mapping procedure described in this chapter 114 Tutorial 30 N umber Groups Use of Lists We have seen that a message can consist of a single number or alist of numbers separated by spaces The list isan effective way of sending numbers together ensuring that they are received at thesametime by an object For example we usually want to keep pitch values and velocity values synchronized so that they arereceived in theproper order by noteout W hen noteout receives alistin its left inlet itinterprets thethird element if present asthe channel number the second element as the velocity and the first dement as the pitch Thereare objects specifically for combining numbers into alist and objects for breaking lists up into individual numbers So you can choosethemostappropriateway to send groupsof numbers between objects A list even can includesymbols words aswell asnumbers which may beuseful in somecases Aslongasthefirst elementisanumber M ax objects will recognizethemessageas a list iter W hen theiter object receives alist of numbersin itsinlet itbreaks thelist up into itsindividual ele ments and sendsthenumbers out in sequential order rather than all at the sametime It s as if iter puts commas between the dements to make them into separate messages mle E major accompaniment metro 2000 sends out list elements sequentially 40 39 50 In theright part of the Patcher windo
368. o seehow you would do this using normal M ax objects N otethat becausethe expr object hasno knowledgeof it s previousoutput value wehaveto storeit manually and enter it again using asecond inlet to the object slowly increase this number watch what happen when lt Th goes above 3 0 expr 1 f2 1 2 0 131156 Thesecond lineof codein our float method takes our new valueof x and sendsit out thejsobject s outletto M ax Theout let function takesasits argumentsthenumber of theoutletto useand theinformation to send out Theoutlet numbering starts at 0 for theleftmost and in our case only outlet e Tryrunningthepatch again knowing how thecodeworks Seeif you can work out at what point the equation becomes chaotic and why Variable Scope Thekey to thesuccess of our JavaScript coderesidesin theuse of x asaglobal variable JavaScript likemany scriptinglanguages will dynamically allocatevariablesas you usethem allowing you to use new variablenamesas you go without having to predefinethem all ahead of time T hese dynamic variables however are local to thefunctions within which they are used For example if wehad avariablei in ourmsg_float function our bang function would not beableto useit Similarly we could usei asa variablein both functionsindependently of oneanothe Becauseweexplicitly defined x asavariablein our global code both msg_float which eval uates x setsitto anew value and sendsit out
369. o usethis method to send offset messages to bpatcher objects that lack an inlet Creating Objects Themost powerful feature of scripting isthe ability to create new objects The form of thescript ing command is script new lt variable name gt lt creation message gt Asmentioned above the lt variable name gt field is anew object name which is assigned to the object being created 233 Tutorial 46 Basic scripting Themessagepartof script new isnotstraightforward You want to send amessagethatisidentical to theformat of M ax text patch files In order to understand this let s takea look at this simple patch in itstext format A simplepatch You can look at thetext version of any M ax patch by choosing Open AsText from theFile menu max v2 header information AN vpatcher 40 55 299 300 patcher window definition button 65 98 15 0 object definition for thebutton object number 94 75 35 1000022000221 221 221 222 222222000 objectdefinition for thenumber box object message 94 124 14 1441802 0 object definition for thelower message box message 94 98 43 1441802 set 1 object definition for theupper message box newex 94 148 50 1441802 print a object definition for theprint object connect 3010 patchcord connect 40 20 patchcord connect 1020 patchcord connect 2000 patchcord pop create patcher window In order to create any object in M ax using scripting usethe portion of the object d
370. object is triggered by the message received in its left inlet the pitch value gets to theif object too late Father than halw the velocity of This halves the velocity only notes with pitch 60 or greater If the pieh is D or greater if fil 60 then i2 else out i2 J this uses the pitch of the previous note by storing the velosity in the right inlet to determine whetherto halwe the velocity wotil the piteh value arrives in the left inlet In thepatch on theright thevelocity valueisstored in theright inlet of theif object until thepitch value arrives so the patch works properly Redirect bits 0 3 of the status byte In this case EE depending on ie pepe tues bits 46 input too early ESSE fe T hepositioningof objectson thescreen affects theway thepatch functions In thepatch on the left the gt gt 4 object and the amp 15 object are perfectly aligned vertically and thereforethe gt gt 4 object receivesitsinputfirst Asaresult thepack object getstriggered beforethe number arrives in its right inlet In theexample on theright the patch has been debugged simply by moving the amp 15 object afew pixels to theright If you renotawareof theright to left and bottom to top order in which M axmessagesaresent you may be troubled by the fact that moving an object one pixel can potentially change the way a patch works H owever if you remember theseordering principles you can tell ataglancetheexact order i
371. objectsina background window without first bringing the window to thefront See Also inlet Receive messages from outside a patcher outlet Send messages out of a patcher patcher Create asubpatch within a patch M enus Explanation of commands 100 Tutorial 27 Your O bject Use Your Patch as an Object Asyou get involved with writing your own patches you will probably find that you are using cer tain configurations of objects very frequently or that there are certain computational tasks that you need to do very often It would beniceif you could just make an object to do that task then plug in the object wherever necessary Actually any patch you have created and saved can be used as an object in another patch just by typing thefilename of your patch into an object box asif it werean object name M any M ax users refer to patches used in this way as abstractions Aswesaw with thepatcher object when you usea patch within a patch you usually want to beable to communicate with thesubpatch Therefore when you are making a patch that you plan to use as an object inside another patch you will usually want to includeinlet and outlet objects or send and receive objects so that you can send messages to your object and it can send messages out The transposer Object In this patch you see atransposer object for transposing incoming pitches and sending out the transposed pitch Theinterval of transposition thenumber of semitonesup or dow
372. ome thingon and off or to providevaluesfor calculation or symbols such asstart and stop to control a morecomplex task such as a sequencer Thesimpler the messages that a patch receives and sends and thesimpler the function of each patch the greater thenumber of contexts in which that patch is likely to be effective Documenting Subpatches H erearethreetips for documenting your own patches that will be used as subpatches 1 Giveyour subpatches informative names so you ll remember what each one does 2 PutAssistancetextin each inlet and outlet object to remind you of theinletor outlet spurpose when usingthe patch 3 If your subpatch is complicated includecomment boxesinsideit to explain its operation See Also Debugging Techniques for debugging patches Efficiency Issues of programming style 340 Efficiency ssuesofProgrammingStyle Program Size and Speed When you arewriting very big complicated patches or arelinking many subpatches together insideonemain patch matters of program sizeand computational efficiency comeinto play W hen you open apatcher file each object in the patch isloaded into theinternal memory of the computer A very large patch containing many objects and subpatches can take up a considerable amount of memory and can takea long timeto load Therefore you may wish to consider how to build patches that avoid superfluous messages and objects T hereareusually several waysto accomplish thesameprogr
373. ome from outside M ax from aM IDI controller or another MIDI application usingthelAC Bus or can be generated algorithmically within M ax T hebasic sequencer in M axisseq which recordsraw M IDI datareceived in itsinletfrom midiin or midiformat and can play the data back at any speed T herecording and playback processis con trolled with messages such as record start and stop Sequences recorded by seq can be written into a separate fileto be used again later Under OSX M ax text file and M ax binary file are the two options for SaveAs Under Windows the options are maxb Files mxb pat help and TEXT Files txt pat help mxt When seq receives awrite message it calls up the standard SaveAs dialog box If the file is saved as text by choosingM axFormatT extFilefrom theF ormat pop up menuin theSaveAsdialogbox itcan be edited by hand by choosing Open As Text from theFilemenu M IDI files can also beloaded into seq with aread message follow The follow object functions exactly like seq but has the added ability to compare a live perfor mance to the performanceit has recorded earlier follow can record not only raw M IDI data but also individual numbers such as note on pitch values You can step through the set of recorded notes or numbers using thenext message M ost interestingly follow containsa score following algorithm activated by the follow message follow will compare incoming n
374. ompletein each object and then stop Double click any of thejs objects in the patch let s examinetheir code 273 T asks A rgumentsand Tutorial 50 Global Objectsin JavaScript Right on Schedule Examinethe global code for our script inlets and outlets inlets 1 outlets 2 define global variables and set defaults var tsk new Task mytask this our main task var count 0 var decay 1 0 defaults for arguments var dcoeff 0 0002 decay coefficient var note 60 note to trigger upon bounce process arguments decay coefficient note to trigger if jsarguments length gt 1 argument 0 is the name of the js file dcoeff jsarguments 1 if jsarguments length gt 2 note jsarguments 2 Global Max namespace variables glob new Global bounce glob starttime 500 Theglobal codesection of our JavaScript file which defines the familiar inlets outlets we have two thistime and variables has a number of things that wehaven t encountered before T he first iSavariable assigned to a special object called Task var tsk new Task mytask this our main task Thiscreatesa new Task objectinJ avaScript referred to by thenametsk W hen wecall methods for tsk they will relateto thescheduling of afunction called mytask Thecontrolling object for theT ask will be our js object which werefer to as this If wewould liketo execute our task once wewoul
375. on T heoval has six inlets for left top right and bottom screen location drawing mode and color index into the graphics 321 I Overview of graphics Graphics windows and objects window s palette A list of four numbers sent to an oval object causes it to draw within the pixel coordinates specified in the list left top right and bottom 20 350 100 100 oval Display graphic Display A graphics window titled Display appears when thegraphic object is created Below you can see the result of clicking on thebutton in this patch 8 6 Display If the oval isredrawn with different coordinates theold oval is erased automatically becausethe oval acts asa sprite which has changed location and possibly size Ways to Move Objects Two useful objects which let you move a sprite based object such as an oval across the screen are line and mousestate line can movethespritesmoothly in atrajectory whilemousestate can be used to make aspritefollow the mouse 322 Overview of graphics Graphics windows and objects H ereis a program that usesline to movean oval from onesideof the window to theother Notice that only theleft and right coordinates are being changed by the output of theline object 30 310 2000 graphic Display oval Display Thenext exampleuses mousestate to follow themouse W hen mousestate receives the poll message with thename of agraphic object as an argument it will begin polling the mouse
376. on a particular perhaps less obviously M ax like look By default this option is enabled Normally onecan stop all loadbang objects from sending out their bang messages by holding down the Shift and Command keys on M acintosh or Shift and Control keyson Windows while the patch or collective or standalone is loading You can disable that loadbang defeating capa bility in a standalone application by checking the Prevent loadbang D efeating with Cmd Shift option This option is turned off by default 334 Groupingfilestocreate Col ect Ives a single application TheOverdrive Enabled and All Windows Active Enabled options allow you to preset these menu options to configure your application s initial behavior They are both off by default If you check the User Can t Close Topleva Patcher Windows option top level patchers will have no close box in their title bar and the Closecommand in the Filemenu will be disabled whenever a top level patcher istheforeground windowin your application Sinceclosingthetop level patcher in most cases renders the application useless this option is checked by default The final two options allow you to include all the files necessary to seethe M IDI Setup and D SP Status windows as well as all of the audio and M IDI driver objects This option doesnot include any non M ax files that might be necessary for MIDI and audio for example checkingAudio Support does not includethe M SP ReW ire driver Th
377. on will show up Custom Icons and Splash Screens for Windows In order to create a custom icon for your standalone application follow these steps 1 2 Create your ICON using theWindows ico format Using the Collective Editor add alineto your Collective Script with the following syntax appicon filename H int you can use the Include File button to choosethe ICO fileand then changethe include command to appicon In order to create a custom splash screen for your standalone application follow these steps 1 2 Create your splash screen using theW indows bmp format Using the Collective Editor add alineto your Collective Script with the following syntax appsplash filename 336 Groupingfilestocreate Col ect Ives a single application H int you can usethe Include File button to choosethe ICO file and then changethe include command to appsplash The Search Path in Standalone Applications It may beimportant for developers of standalones to know the order in which M ax searches for files it is slightly different than the search order in the editing version of M ax M SP This informa tion is relatively advanced and will probably not be of much interest to users who arenot develop ing standalone applications On MacOSX theUtilizeSearchP ath option when checked doesthefollowingfor thesearch path of a standalone 1 Addsallofthefoldersinsideofthefolder containingthestandal
378. onal precision Thesplit object is useful for limiting numbers to a specific range All numbers it receives that are within its specified range are sent out its left outlet Otherwise they aresent out its right outlet Cycles of numbers can be produced by looping A loop is created by continually changing a num ber then resetting it when thenumber meets a certain condition Theaccum object is well suited for such looping schemes See Also accum Store add to and multiply anumber float Storea decimal number int Store an integer number Loops Usingloopsto perform repeated operations 82 Tutorial 22 Delay Lines Delaying Numbers and bang messages M essages normally passthrough patch cordsasfast asthecomputer can send them H owever you can also delay numbers lists or bang messages for acertain amount of time before sending them on their way Thisis useful for creating a specific time lag between messages or delaying notes to create echo effects Thepipe object delaysthenumbersit receives for a certain amount of time before sending them on Thedelay object also called del delays abang for acertain amount of time before sending it on pipe e Dragon thenumber box at thetop of Patch 1 Thenumbersareall delayed for 2000 millisec onds by thepipe object Each number is sent out the outlet a certain amount of time after it is received so pipe can delay many numbers and send them out later in the samerhythm in which they werer
379. oneapplication i e theCon tents folder and all of its subfolders The folder containing the application s package is not included In other words if you put your application in the M ac OS X Applications folder the Applications folder is not included in thesearch path 2 AddstheCycling 74 folder Library A pplication Support Cycling 74 if it exists On Windows XP the Utilize Search Path option when checked does the following for the search path of astandalone 1 Addsall of the foldersinside of the application folder i e the folder containing YourApplica tion exe 2 AddstheCycling 74 folder c Program Files Common Files Cycling 74 if it exists When Utilize Search Path is not checked the only folder s added to the search path are the sup port folder inside the standalone application s folder and any of its subfolders Theorder in which folders will be searched is as follows 1 Thecollectivefile and any other open collective files 2 Thesupport folder 3 Thefolder containing the application and its subfolders optional if Utilize Search Path is checked 4 TheCycling 74 folder optional if Utilize Search Path is checked The Search for FilesN otintheA pplication sC ollectiveoption is different from theU tilizeSearchP ath option It prevents M ax from looking for any files that are not in open collectives including the support folder which means that you cannot uncheck Search for M issing Files and have eit
380. onsiveness of the user interface Theword setslop followed by a floating point value sets the scheduler slop value theamount of timeascheduled event can beearlier than thecurrenttime beforethetimeof the event is adjusted to match the current time T hedefault valueis 25 milliseconds Shows thefloating inspector window Shows themenu bar after it has been hidden with hidemenubar Prints thenumber of symbols in thesymbol tablein the M ax window Theword system followed by thenameof an O perating System windows or macin tosh and a message will execute the message if M ax isrunning on the named OS 404 M essages tO M ax ControllingtheM ax application MIDI Configuration Messages Thefollowing messages areused to configureM IDI on your system and to accessthebuilt in DLS Downloadable Soundfont synthesizer for MIDI playback By default asingleaugraph on M ac OSX or midi_dm on Windows portis created H owever you can create additional M IDI syn thesizer ports and assign new D LS sound bank files to each one Addressing the DLS synthesizers currently requires the use of themessage box techniquewhere you send messages to named objects by typinga semicolon followed by themessagetext into a message box then click themes sage box H ereisalist of messages that you can useto access the D LS synthesizer Creating a DLS Port SM createoutport lt portname gt lt drivername gt wheredrivernameismidi_dmonW indowsand augraph on
381. or isreported in adialogbox Thefollowing errorscan appear in dialogs Choose Resume from the Edit menu to restart the Max scheduler Itispossibleto get M ax working so hard it doesn thavetimeto respond to your commands say if you havea number of metro objects sending out bang messages as fast as they can or if you have created aloop that overloads M ax causing a Stack Overflow error H olding down the Command key on W indowsor theControl key on W indows and typing a period will stop M ax sscheduler giving you timeto turn off some of the overloading processes W hen M ax stimer is stopped the above message is shown in adialog box ChooseResumefrom the Edit menu to restart M ax s timer No help available for lt objectname gt A help filein the max help folder can t be located for thenamed object Restorethehe p filefrom your original M ax disks Stack Overflow Occurswhen an object soutputis beingfed back into itsinletin sometypeof loop After stopping 399 Erro rS Explanation oferror messages theprocessthatiscausingthestack overflow chooseResumefrom theEdit menu to restart M ax s scheduler See Also Debugging Techniques for debugging patches 400 M essagestoM ax ControllingtheM axA pplication The maxmessage Usingamessagebox you can control theM ax application All such messages begin with max as if therewereareceive object named max H ereisa list of messages the M ax application under stands
382. osed Pitch to makenote Calculating an Inverse Linear Map You may remember from an earlier patch in which weinverted pitches that wesubtracted themax imum possible pitch from whatever pitch was played then took the absolute value of the result See Patch 2 in Tutorial 14 The formula for an inverse linear map then looks like this y X xmax ymax ymin xmax xmin ymin When we plug our ranges into the formula we get y x 96 90 60 5 Wecan translatethis into Patcher objects as pich from kslider x mins max times 1 times 90 60 pius ymin equal percentage for PassPet y Scroll to the right in the Patcher window to see Exercise 2 and Exercise 3 combined in asingle patch Weve used our PassPct object 113 Tutorial 29 Test 5 Probability object Summary To create your own object make a patch that includes inlet and outlet objects and changeable arguments if appropriate save the patch then use your object by typing thenameof the fileinto an object box in someother patch ThePassPct object is similar to thegamble objectfrom thepreviouschapter It passes or suppresses the bang messages it receives according to some percentage of probability You can transpose a note by an arbitrary number of octaves by first calculating its pitch class with a 12 object and then adding some multiple of 12 to the pitch class You can create a direct or inverse linear relationship between tw
383. other Example which isa com pletely separate program from therest of this patch e Double click on the p Another Example object to open it Although some of the arithmetic in the expr objects may appear daunting the basic operation of this patch is extremely simple When you click on thebutton 1 A record message is sent to detonate 2 uzi sendsout 1000 numbers ascending from 1 to 1000 effectively from 0 to 999 sincethe numbers go immediately to a 1 object 3 Each of thosenumbersis used to calculatethe different parameters of anote event 4 Whenuziisdone astart message is sent to detonate followed immediately by anext message to send out the first note event 5 Theevent parameters are converted to M IDI messages by makenote and noteout and ctlout for panning messages and the delta time is used to determine when the next note should be triggered 217 Tutorial 44 Pat Marae In asingletick of M ax s clock a melody approximately 78 seconds long is composed and recorded Each of the event parameters is calculated according to a unique formula describing a particular curve from the beginning to the end of the melody s duration Piya Pada Ae a Aea 1 X gt naom nE Oe H i H i H i A anA eao re Ke i D r i D AEE Se agi 4 4 a a eee RS Sete eae Wowabar ie tes ewes soi pened Weippe r ae A ia my A Poin y ae i L t be i i i aya i H i 1 r ti Re f noB 3 4 i i i 7 paa E a
384. ou may wantto read theuser s manual of your synthesizer to besureyou understand itsM IDI capabilities TheTutorial patches are designed for a keyboard synth with local control on one that makes sounds when you play without receiving any additional M IDI in rather than for a keyboard controller with no built in synth If the keyboard and tone generator you are using are separate you should open the patch called thru in the M ax Tutorial folder specify your input and output portswith thepop up menus and leaveit open asyou run theT utorial patches T hiswill routethe M IDI output of your keyboard directly through M ax to your tone generator emulating a key board synth Tutorial 1 Saying H ello Open Tutorial 1 e f you havenot already started up the M ax application do so now by double clicking on the M ax application icon e OnceMaxislaunched open the M IDI Setup window by choosing M idi Setup from the FileM enu and assign theinputand output devices you wantto useto port abbreviation a with achannel offset of 0 OOA MIDI Setup On Input Device Abbrev Offset On Output Device Abbrev Offset to Max MSP 1 B ep AU DLS Synth 1 B cs to Max MSP 2 S amp S ey from Max MSP 1 B 7 from Max MSP 2 B ey QTMA Synth 1 B ja Both the M acintosh and Windows XP provideaDLS Downloadable Soundfont synthesizer for MIDI playback If you don t want to use any external M IDI gear you can drivethe DLS synth directly
385. out the outlet of mousefilter Thepatch in theleft part of thePatcher window isvery similar to thisexample except that wehave hidden the mousefilter object and the patch cords W hen you drag on the dial the upper number box shows the output of dial but no number is sent to the lower number box and to pgmout also hidden until the mouse button is released e Dragon thedial to select anew program change number Nothing is sent to your synth until you release the mouse button Thebutton at the top left corner of the patch triggers aline object to step through the program changes automatically over the course of 16 seconds e Click on thebutton W hilethedial isbeing automatically controlled you can usethemouseto suppress certain program change numbers Whenever you hold the mouse button down mousefilter acts as a gate to shut off the flow of numbersto pgmout e Unlock the Patcher window to see how the connections are made Lock thewindow again before trying the rest of the patch Using the Mouse Position to Provide Values Thelarge box in the example Patcher window wasimported from a graphics application and pasted into thewindow usingPastePicturefrom theEdit menu Itdelineatesapitch velocity grid in which you can drag with the mouse to play notes T he gray area shows the pitch space that cor responds to the range of a61 key keyboard C1 to C6 e Beforeusingthepitch velocity grid you mustclick on themost extremebottom left corner of
386. ow 189 Tutorial 41 TimdineofM axmessages e To play thetimdine just click on the message box that says play in the Patcher window W hen you get bored with the repeating sequencein SectionA move the mod wheel and thetimeline will progress on to the Coda section To stop the timdiine click on thestop message in the Patcher window To go back to thebeginning click on thelocate 0 message box or choosel ntro from the Go To pop up menu in the Patcher window Controlling the timeline s Tempo Like the clocker line metro pipe and tempo objects a timeline object can be synced to asetclock object and its tempo will then be controlled by that setclock object rather than by M ax s regular millisecond clock e Click on the message box that says clock scalespeed T hat instructs thetimeline object to sync to thesetclock scalespeed mul object Click on thelocate 0 message box to rewind the timeline then click play You will notice some changes in thetempo of the Intro section Whenever asetclock object with a mul argument receives anumber in its left inlet it multiplies its clock values i e divides its tempo by that number In this case the tempo changes comefrom thetimeline itself Specifically scalespeed event editors float objects in the Intro section of the timelinetransmit numbers to theticmd scalespeed f object in the action patch which sends them via atiout 1 object out the first outlet of the timeline object
387. ow labeled Status in theruntimeversion W hen maxinwmenu is fol lowed by 0 themenu item isnot present T he default is for the Status item to be present in theW indows menu 402 M essages tO M ax ControllingtheM ax application midi midilist objectfile paths preempt pupdate quit refresh Theword midi followed by a variable length message allows messages to be sent to configurethesystem M IDI object Thefollowingis alist of the available options autosetup Duplicates the action of clicking on theAuto Setup button in theM1D1 Setup window portabbrev lt innum outnum gt lt portname gt lt abbrev gt innum specifies an input port outnum specifies an output port portnameisthe nameof theportas a single symbol i e Itis necessary to use double quotes An abbrev valueis 0 for no abbrev in menu 1 for a and 26 for z portenable lt portname gt lt 0 1 gt Enables 1 or disables 0 the port specified by portname All ports are enabled by default portoffset lt innum outnum gt lt portname gt lt offset gt Similar to portabbrev but offset is the channel offset added to identify input or out put portswhen aM IDI object can send to or receivefrom multipleports by chan na number M ust bea multiple of 16 e g max midi portoffset innum PortA 16 sets the channel offset for PortA deviceto 16 Printsthenames of all current M IDI devicesin the M ax window See also MIDI M essagesto M ax
388. ow up asan Assistance message when you areworking in themain Patcher window e Unlock themain Patcher window and pass the mouse over the inlets of the patcher keyboard object to see the Assistance messages Although writing Assistance messages to yourself may seem like a waste of time it can bevery helpful in reminding you later what typeof messagea subpatch object expectsto receivein itsinlet and what type of message will come out of its outlet Summary T hepatcher object creates a subpatch within a patch T hesubpatch issaved aspart of thedocument that contains the patcher object If the subpatch window is open when the patch is saved it will be opened automatically when the document is reopened You can even nest a patcher object within another patcher object M essages can be sent between the main patch and thesubpatch with send and receive objects or with inlet and outlet objects W hen inlet or outlet objects are placed in asubpatch corresponding inlets or outlets are automatically created in the patcher object W hen Assistanceis checked in the O ptions menu M ax prints a description of inlets and outlets in the bottom bar of the Patcher window whileyou areediting a patch You can assign Assistance messages to the inlets and outlets of a patcher object by selecting the inlet or outlet object in the subpatch and choosing Get I nfo from the O bject menu W henAllW indowsActiveischecked in theO ptionsmenu you can click and dragon
389. own 1 12 then locate 11 In this example action a goto event in the track will cause the timeline to rdocate to whatever timelocation it givesitself H ereitistellingitself to go to apoint fivesecondsinto thetimeline In theexample aconditional clausehasbeen builtinto theaction so thatthe goto eventwillonlybe enacted by the action if the space bar is currently being held down Theinteraction between a timeline the patch that contains it and the actions it employs can be as complex as you care to makeit You will need to plan your program very carefully to besure that you understand which object is actually acting at any given moment the patch containing atimeline object thetimeline itself or theaction s being used by thetimeline See Also mtr M ulti track sequencer setclock M odify clock rate of timing objects thistimeline Send messages from a timeline to itself ticmd Receive messages from atimeline timeline Time based score of M ax messages tiout Send messages out of atimeline object Tutorial 41 Timeline of M ax messages 375 D etonate GraphicEditingofaM IDI Sequence Uses of detonate The detonate object isa flexible sequencing graphic editing and score following object It can record alist of notes tagged with time duration and other information You can save the note list asasingle track format 0 or multi track format 1 M ID I file and you can read in any M IDI file that has been saved to disk by
390. ows how much to move over per row for i O i lt ncols i iterate through the columns for j 0 J lt nrows j iterate through the rows moveto i colstep colstep 2 1 0 1 0 j rowstep rowstep 2 0 move the drawing point if state iJ j set on color glcolor vfrgb 0 vfrgb 1 vfrgb 2 vfrgb 3 else set off color midway between vbrgb and vfrgb glcolor vmrgb 0 vmrgb 1 vmrgb 2 vmrgb 3 circle 0 7 Math max nrows ncols draw the circle Thegraphicscommands everything beginningwith gl aswell asthecircle command are all methods and properties of the sketch object which encapsulates most of the OpenGL API much astheM ath object encapsulates most common math functions NoteTheJavaScript with statementallowsusto usepropertiesand methodsbelongingto an object in this casethe sketch object that provides us with our OpenGL functionality with out having to reference sketch in every command Without thewith wewould haveto writesketch glcolor instead Of glcolor sketch circle instead of cir cle 4c This useful trick could also beimplemented in functions that rely heavily on other objects e g Task or Patcher Our araw function sets some default drawing behaviors and clearsthe window with thecolor defined by thevbrgb array It then iterates through our statearray based on how many columns ncols and rows nrows w
391. p up with the performer Thepitchesfrom patcher addnotes and from funbuff aresent to makenote wherethey arepaired with the velocity of theright hand melody notes so the accompanist is sensitive to the performer s dynamics as well Rather than usean algorithm or alookup tableto providedurations for the accompaniment notes we just picked a duration that seems to work both as an eighth note dura tion and as a stylistically staccato quarter note Summary A singletrack of raw M IDI data can be recorded and played back at any speed with the seq object TheM DI dataisreceived from midiin and istransmitted by midiout You can also parsethe 153 Tutorial 35 seq and follow data from seq using midiparse and process thenumbers with other M ax objects before transmit ting them A recorded sequence can be saved as a separate file by sending awrite message to seq If you check theSaveasT ext option in theSaveA sdialogbox you can open and edit thefilelater with Open As Text A MIDI filecan beread into seq by sending aread message or by typingin thefilenameas an argument The follow object allows you to record or read in a sequence then use that sequence as a musical scoreto follow alongwith aliveperformance Asthepitches received in theinlet arematched with notes in the score the index number for each note is sent out and can be used to trigger other notes or processes See Also follow Comparealive performanceto a recorded performance
392. patch the note on message goes directly to noteout and pipe supplies a later note off message on the same key and channd Fich We m w Channel The pitch veloc iy and channel Dum hers go directly to wotecut pichani channel are also de layer by the duration time then sent to moteout wih welor ity of Oto Modifying the Playback Tempo You haveno doubt noticed that the duration valuesand thedeltatimevalueseach passthrough a 1 object Asthey go through they are multiplied by a scaling factor received from ther tempofac tor objects Thistempo scaling factor is produced in the p tempo subpatch e To seehow thescaling factor is produced closethe output window and bring the tempo window to the foreground Since the tempo window contains hidden objects you ll need to unlock it and click on thezoom box in theright corner of thetitle bar to seeits contents or you can simply consult the picture of it shown here q Values range from 100 to 100 expr 1 0 f1 zpr 1 0 f1 tempofactor Thecontentsofthep temposubpatch expr powi 05 1 100 3 We decided to usethehslider object to permit the user to give tempo scaling values from half the original tempo to twice the original tempo from 0 5 to 2 0 This presents a small problem becausethefactor wewantto useisamultiplier whilehslider ison an additive linearly increasing scale H owever if we recognize that 0 5 21 1 2 and 2 0 2 then wesee that w
393. patcher in the main patch Thisis the most obvious use of the offset message to athispatcher object in abpatcher H owever as with any imagethatis positioned by specifying its pixel coordinates thecontents of abpatcher can be animated with a continuous stream of different positioning messages Animating a bpatcher e Toseeademonstration of an animated bpatcher click on the words Roll Credits in the lower left corner of the window Theuse of offset messages to athispatcher object in abpatcher isanother method of displaying and hiding different text messages In this case themessage box containingthewordsRaoll Credits is con 205 Tutorial 43 Graphics in a Patcher nected by a hidden patch cord to the inlet of the bpatcher and its output triggers a progression of different offset messages causing the appearance of scrolling text e Toseethecontents of the scrolling text bpatcher open the filenamed scrollingtext in the M ax Tutorial folder and unlock it prepend offset thispatcher set 450 450 10000 100 This scrolling text is contained in a bpatcher subpatch When a message is received in the inlet of abpatcher it is converted to a bang by the b object and triggers aline object which sends out astream of numbers progressing from 450 to 450 over the course of ten seconds T he number is used as the horizontal coordinate with the number 70 appended as the vertical coordinate and with the word offset preoend
394. patches you can save memory and disk space by using fpicobjectsthatall referencethesamefile You musttakecare of course that thefile islocated where M ax can find it Seethe discussion of thefile search path in theO verview section of the Getting Started manual TheM ax icon in this particular patch doesn t do anything It sjust thereto demonstrate the fpic object which loadsin a small graphics file containing a picture of the M ax icon 68 Tutor al 19 Screen aesthetics Cicking on a Picture e Lock thePatcher window and click on thepictureofabutton marked ON Themetro object is started just as if you had clicked on thetoggle Click on the picture of an OFF button to stop themetro W eknow that theOFF and ON buttons arejust pictures so how do they turn themetro off and on Thepictures seem to respond to amouseclick becausetransparent buttons ubutton objects have been placed on top of them ubutton Theubutton object is arectangular button that becomes invisiblewhen thePatcher window is locked W hen you click down on aubutton it sendsabang out its second outlet and invertsthepart of thescreen it covers W hen themouse button is released ubutton sends a bang out its left outlet and becomes transparent again A ubutton can be placed over apictureor a comment or over nothing for that matter if you just want an invisible button to make that portion of the screen respond to amouseclick T he pixel inverting featureof
395. phics ity of a pict object is 0 whilethe default priority of arect is 3 so by default a rect will cover a pict We give our pict a higher priority so that the picture will bedrawn in front of the rectangles Becausethesizeof apictureispredetermined by thedimensionsofthegraphicsfile you only need to give pict two coordinates to situate the picture the coordinates of the left top corner A non zero number or a bang in the left inlet draws the picture at the specified spot In the example patch line objects are used to change the left and top coordinates continuously on atrajectory toward a specified goal The left coordinate goal of the picture is calculated from the pitch of the played note just as in the case of the rectangles The pictures distance from the bot tom of the window is determined by mapping therange of note on velocities 1 to 127 to the range of vertical pixels going up 322 to 0 Because the picture is 32 pixels high the effective ver tical pixel rangeis 290 to 0 M ultiplying thevelocities by 2 3 causes them to rangefrom 2 to 290 and adding 292 to that gives us the desired pixel range The amount of timethat each line object takes to move the picture to the target coordinates is determined using timer objects that measure the elapsed time since the previous note on The interpolation resolution of 33ms was chosen to animate the picture at a potential rate of 30 frames per second T he actual rate at which the
396. play Try this with asustained sound on your synth The last patch demonstrates that you can typein an argument for the channel on which noteout will transmit The channel inlet is still present however and you can change the channel by send ingin anew number The patch also shows that noteout combines pitches with whatever velocity was most recently received e Try sending different velocities to noteout T he velocity is just stored until a pitch number is received to trigger aM IDI note message Summary Thenotein object looks for incoming M IDI notemessages and outputs pitch velocity and chan nel data You can typein aspecific port letter as an argument which causesnotein to output only the note data received in that one port You can also typein a specific channel number causing notein to output only thenote data received on that one channel When thenoteout object receives a number in its left inlet it uses that number asa pitch value combines the pitch with a velocity and a channel number and transmits a M IDI note message The pitch velocity and channel can also be received together as alist in the left inlet See Also notein Output incoming M IDI note messages noteout Transmit M IDI note messages 42 Tutorial 13 Sendingand RecelvingM IDI N otes Note On and Note Off Messages Oneofthemain problemsthat you encounter when sendingnotemessagesto asynth from M axis the need to follow every note on message with a cor
397. pointer at address 0 in thetable the first address goto gota aaaress o a JE JE Ta Led ww e e ee ee e ae A next message sends out the valuein the address at then sets the pointer the pointer to thenext address W hen themessagenext isreceived in theleft inlet table sends out thevaluestored at theaddress at the pointer then increments the pointer to the next address W hen the pointer reaches the last addressin thetable anext message will causeit to wraparound and pointto thefirst address again so you can usenext to cycle continuously through atable You can also cycle backward through a table with the prev message not shown in this patch Thus in our patch valuesaresent out of thetable each timea pitch is played on your keyboard on channds 1 through 8 and values can also be sent out automatically by turning on the metro to send repeated next messages to the table step through the table metro 125 System Exclusive Messages M IDI system exclusive sysex messages are used to send information other than that which is established as standard by the M IDI specification Sysex commands are implemented by manu facturers as a way of modifying settings on their gear via M IDI M ax has asysexin object for receiving system exclusive messages but to send sysex messages you need to format them yourself and then send then using midiout 142 Tutorial 34 Managing raw M IDI data Thereisan object to help yo
398. port the time elapsed between messages which detonate will record asthe data time parameter of each note event On playback the data time should be used to determine how long to wait before playing the next note M ultiplying the delta times and durations by some number other than 1 changes thetenpo of the playback W hen supplying note offs for notes on different channas pipe can bea useful substitute for makenote 218 Tutorial 44 Sequencing with detonate See Also detonate Graphic score of note events D etonate Graphic editing of a M IDI sequence Sequencing Recording and playing back M IDI performances 219 Tutorial 45 D esigningtheU ser Interface Making an Application for Others When you have written an interesting M ax program you may want to giveit to other people to use If your program consists of many different files your own objects graphics files etc you will probably want to use the SaveAs Collective command in the Filemenu to save all the nec essary files together as a single collective You can even save your collective as a standalone applica tion for people who don t have M ax or M ax M SP Runtime For moreinformation about saving your program as a collective or standalone application see the chapter on Collectives in the Topics section of thismanual If you re going to give your program to others to use you will probably also want to spend some time planning and designing the user interface t
399. possible situation M ax can turn your computer into avery expensive M IDI thru box by simply connecting the outlet of midiin to the inlet of midiout These two objects in fact all M IDI objects can begiven aletter argument specifying asingleport through which to receive or transmit so you can usethe arguments to route M IDI datafrom oneport to another What comes in port ais What comes in port a i echoed back out port a transmitted out port h You can also change the input or output port of any MIDI object dynamically by sending the nameof a portin theinlet Beware of the possibility of stuck notesif you change ports whilenotes are being played Specify port by letter or by name iF wing OME midiin KSS The word port i optional midiout a midicut TOTT If thereis no port specified for midiin or midiout either by an argument or by a port messagein the inlet port a is assumed by default For moreinformation about port assignment seethe Ports sec tion of this manual 138 Tutorial 34 M anaging raw M IDI data capture If you just want to examinethe M IDI bytes that your equipment is sending out you can connect the outlet of midiin to a capture object as we have donein this Tutorial patch Thecapture object is a good all purpose debugging tool It collects the numbers it receives and when you double click on it it opens a Text window for you to view the numbers T he numbers stored in capture
400. pt hide lt variable name gt To show them again script show lt variable name gt The following patch demonstrates asimple application of script show and script hide in which a comment box named mycomment is used to clearly indicate the inactive status of the interface objects L show mycomment Script hide mycomment thispatcher Thescript show and script hide messages L show myrcomment script hide myrcomment thispatcher Theabove patch makes someassumptions however It assumes that mycommentisin front of the threenumber boxes otherwise it would appear behind them It also assumes that the user takes 246 Tutorial 4 Advanced scripting asimple inactive sign to heart and doesn t try to changethenumber box values anyway T akea look at this variation Script shor mycomment script bringtofront myoomment script ignoreclickh somewhere script ignoreclick nowhere script ignoreclick anywhere script hide mycomment script sendtoback mycomment script respondtoclick somewhere script respondtoclick nowhere script respondtoclick Sea eats thispatcher A better approach W e ve added several messages Thescript bringtofront and script sendtoback messages are used in the same manner as the M ax menu commands Bring to Front and Send to Back to adjust the visual priority of thecomment object Theformat of those messages is script bringtofront lt variable name gt script sendtob
401. r code Let s moveon to therest of thescript Defining Functions M ax objects interface with oneanother through theuse of methods which areroutines of code that are executed in response to messages received at the inlets of the object In JavaScript these methods are defined as functions within our code each of which respondsto adifferent typeof incoming M ax message In our example js object wehave two functions defined T hesefunctions msg_float andbang contain thecodethat js executes when our object receivesin its inlet a floating point number and a bang respectively e Takealookatthebang function first Thecodelookslikethis function bang post the current population is post x post Thisfunction tellsjs what to do if wesend it abang from our M ax patch Itwill printoutthecurrent value of x in the M ax window with an explanatory preface Thepost statement at the end of thefunction tellsM ax to putacarriagereturn in theM ax window so that thenext message printed therewill begin on anew line N otethat our function is enclosed in curly braces Removing oneof these braces will result in asyntax error e IntheTutorial patch click on thebutton object connected to thejs object O ur bang method should be working correctly 254 Tutorial 48 BasicJavaScript e Lookatthemsg_float function H ereisthe code function msg_float r LFA E E outlet 0 x Ourmsg_float function ex
402. r pitch The new pitches must be combined with a velocity perhaps the velocity of the original played note to send note on and note off messages to thesynth Scroll the Patcher window to theright to see two possible solutions to the problem Solution 1 Both solutionsusetherelational operator gt to find out if the played pitch is greater than or equal to 60 Each solution uses the result of that comparison in slightly different ways 64 Tutor al 18 Test 3 Comparisons and decisions In Solution 1 a successful comparison results in a decision to trigger the numbers 12 and 12 The pitch is stored in the right inlet of a object before the comparison is made Then if the pitch is greater than or equal to 60 the gt object sends out 1 causing thesel object to trigger the messages 12 and 12 Thesetwo numbers are added to the original pitch and the sums are sent to noteout wherethey are combined with the velocity of the played note triggering note messages to the synth T his process occurs both for note ons and note offs so the transposed pitches are success fully played and turned off In Solution 2 asuccessful comparison opens agate letting the pitch through so that only pitches greater than or equal to 60 will be passed on The placement of the gt object is of utmost importance Because it is to the right of thegate object it receives the pitch first and either opens or shuts the gate before the pitch ar
403. r to have passed through apatch cord 15 Tutorial 3 About numbers e Click on the different message boxes and notice what is displayed either in thenumber box objects or in theM ax window Notice a couple of important differences between printing messages with a print object and dis playing then with anumber box 1 Theprint object will printany messageit receives regardless of thecontent of themessage The number box on theother hand can display only onenumber at atime If it receives alist it dis plays and passes on only thefirst number in thelist If it receives an arbitrary text message it does nothing except complain that it doesn t understand that message 2 A number box can show only an int or afloat If an int number box receives a float it converts thenumber to int and vice versa Thenumber box has other features not described here This patch does show oneof its most com mon uses though to display the number that has most recently passed through a patch cord You will learn morein theN umber box Tutorial Summary A Max message can consist of asinglenumbe of typeint for integers or float for decimals M any numbers used in M ax such as M IDI data and millisecond time values areints A message can also consist of aspace separated list of numbers which areall sent together in one message A number box shows the most recent number it has received and passes that number on out the outlet A number
404. ransposition 12 semitones W hen theappend object receives a message for example thenumber 12 it placesthe word semitones after it and sends out 12 semitones Theprepend object then puts set Transposition beforeit and sends outset Transposition 12 semitones which changes the contents of the message box to Trans position 12 semitones Thesame result could be obtained using only message boxes in the following manner set Transposition 1 semitones Transposition 12 semitones backslash The backslash isaspecial character for negating other special characters A special character that is preceded by a backslash loses its special characteristics and is treated like any other charac ter Thisis necessary if you want to include a character such asacommaor adollar sign in a mes sage without its being interpreted to havea special meaning The append Message W hen append followed by any message is sent to amessage box the message following append will beadded to the contents of the message box e Inthepart of thepatch marked D click on themessagesset 1 and append 3000 to construct the message 1 3000 N oticethat we had to precedethe dollar sign with a backslash Otherwise the message box would havetried to interpret 1 as a changeable argument and the message would havebeen set 0 Then drag on thenumber box marked B 94 Tutorial 25 M anaging messages The l argument isreplaced by theincomingnumber and
405. re and recall the settings of other user interface objects in the same win dow such asslider dial number box and toggle objects When you recall a stored setting preset restores all these objects back the way they were at the moment the settings were stored You can even connect the outlet of apreset to atable to storeand recall variousversionsofthetable object s contents The preset can operatein one of threeways If the left outlet of preset is connected to the inlet of other user interface objects it stores and recalls the settings of only those objects Or if the right outlet of preset is connected to theinlet of other objects preset stores and recalls the settings of all user interface objects in the window except those objects If neither the left nor right outlet of pre set isconnected to anything preset stores the settings of every user interface object in the window except table objects which can only be stored by being connected to the left outlet of a preset In the preset_ examples window thepreset object is actually connected to thetable with a patch cord but we have hidden the patch cord for aesthetic reasons 166 Tutorial 37 Data structures e Beforeyou usethe patch enableAll WindowsActive in the Options menu Then double click on thetable objectto open itsgraphic editing window You can draw in pitch valuesfrom 0 to 60 which will betransposed up into thekeyboard rangeby theO ffset of the lower hslider and then p
406. responding note off message For example just sending a pitch and a velocity to noteout plays a note on thesynth but that note will not be turned off until you also send the same pitch with a velocity of 0 60 127 60 O note off Dole makenote M ax has objects that generate note off messages for turning off notes that have been sent to the synth Onesuch object is makenote When makenote receives a number in its left inlet it uses the number asa pitch value combines that pitch with a velocity and sends the numbers out its two outlets Then after a specified delay or duration makenote automatically sends the same pitch number but with a velocity value of 0 Thesynth interprets anote on message with a velocity of 0 as anote off So when the output of makenote issent to noteout both anote on and a note off get transmitted to the synth Fatch 1 Patch 2 72 96 1500 all three Values cal he peceiyed makenote 64 250 asa list pitch o velocity duration provide woke off after a certain duration velocity on barg provide mote ofks for all held notes 43 Tutorial 13 Sending and receiving M IDI notes e Dragon theslider marked pitch in Patch 1 Each number that comes out of the slider is com bined with avelocity by makenote in this case the velocity is 127 specified in the first argu ment and the pitch and velocity are sent to noteout 50 milliseconds after each pitch is received the
407. ring its memory preparing it to output numbers onceagain In this example urn always clearsitsown listand re bangsitself whenever ithasrun outof numbersto send so it alwayssends out anumber but it minimizes the repetitions that occur 208 Tutorial 43 Graphicsin a Patcher Summary Thereareseveral ways to create animation within a Patcher window You can play a QuickTime moviein a Patcher window with theimovie object you can paint colored lines shapes and text in a Patcher window with QuickD raw like messages to an Icd object and you can make text mes sages appear change or disappear in the Patcher window by sending amenu item number to a borderless menu object Graphic images can be animated algorithmically using controlled randomness fractal formulae or any formulainto which you send a progression of different input values to calculate the coordi nates of graphic objects lines or shapes The bpatcher object allows you to create a window into the contents of a subpatch User interface objects that are visible in abpatcher can respond to the mouse just as if they were in the main patch You can display different parts of the subpatch in a single bpatcher box by sending an offset message to athispatcher object insidethe subpatch By sending a progressive series of offset values to abpatcher you can scroll text or givethe impression of moving objects Theurn object functionslikerandom when it receives abang itoutputs arandom
408. rintsits arguments into the M ax window letting you do exactly what theprint object does from withinjs e Add thefollowinglineright underneath where we initialize x to equal 0 66 post x 252 Tutorial 48 BasicJavaScript W hen we save the code our M ax window now tells us js Compiling Functions and Executing Global Code Hi There 0 66 If you givepost atextstring enclosed in double quotes it will printit Other lettersareinter preted asvariablenames In this case weasked jsto tell usthevalueofthevariablex which wehad initialized on thepreviouslineto 0 66 Notethatpost doesnotputacarriagereturn attheend of theline to do this wecan placeapost statement with no arguments e Add thislinesomewherein between thetwo post statements we ve added post Our M ax window now tells us this when we save the code js Compiling Functions and Executing Global Code Hi There 0 66 Handling Mistakes e Removetheclosing parenthesis from any of thepost statements we veadded so far Save the avaScript code TheM ax window should print an error js Compiling Functions and Executing Global Code eerror js Javascript SyntaxError syntax error line 15 source line post Thistells us that we ve madea type of mistake called a syntax error Thismeans that wewrote something illegal from the point of view of JavaScript syntax in this case we broketherulethat says that parentheses must be bala
409. rives at the gate When a pitch islet through it has 12 subtracted from it in one object and has 12 added to it in another object The results are sent to noteout as pitches where they are combined with the origi nal played velocity both for note ons and note offs Note Thenotein and noteout objectsin Solution 2 are set to receive and transmit on M IDI chan nel 2 only so that anotefrom your MIDI keyboard won t cause both patches to react Summary In thisexercise thecomparison gt 60 was used to trigger messagesin onecase and to open agate in another case Either method could beincorporated in a solution to the problem To perform atest and makea decision ask yourself these questions 1 Whatdo need to know to make the decision W hat will be tested 2 Whataction will betaken if the test is successful true 3 Whataction will betaken if the test is unsuccessful false 65 Tutorial 19 Screen A esthetics Segmented Patch Cords So far wehave been making patch cord connections with straight patch cords by dragging from the outlet of one object to the inlet of another object In complicated patches though it would be niceif we could bend patch cords around objects to keep things from getting too messy W hen Segmented Patch Cordsischecked in theO ptionsmenu patch cordscan bemadeup of as many as 10 line segments allowing them to bend around objects Segmented patch cords func tion no differently from straight pat
410. rom thenumber box to trigger the message containingset 1 W atchthe results in the table editing window set 1 G2 104 62 64 44 28 12 28 44 64 e Theword size followed by a number sets the size of the table the number of addresses Trig ger the message containing size 1 by sending it a number from the number box Noticethe changein thetable editing window You ll also noticethat weve included additional connections so that a new size setting will cause corresponding changes in other objects so they interact properly with thetable Using a table for MIDI Values In Patch 1 weused thevaluesin atableto providepitchesto noteout In Patch 2 weusealine object to step through thetable at different speeds outputting different pitch bend curves 130 Tutorial 32 Thetable object Each note on velocity is multiplied by 40 yielding potential values from 40 to 5080 This valueis used asthe amount of timetheline object will taketo read through thetable The louder anoteis played the moreslowly line reads through the table sending out pitch bend values pack O 127 set 0 2 1 line 0 20 bemdout a 1 Notice how the message box is used to rearrange the incoming numbers and send out two differ ent messages We are not as picky about thetiming of the line object here as we werein Patch 3 because the number of values sent out by line is quite unpredictable due to possible variations in played velocity e Alter the
411. roperties sending them messages and making connections between them JavaScript allows you to use procedural codeto generate patcher denentsin ways that may be moredifficult to do through messages to thethispatcher object ThisT utorial covers how to create and delete objects and connectionsin aM ax patch through custom methodswritten in JavaScript as well as to show how to usemethodsto handle custom messages coming from the patcher M uch of the basic information regarding scripting is covered in Tutorial 46 Basic scripting You may wish to review theinformation presented there before proceeding with thisT utorial Aswith the previous avaScript Tutorial you may wish to review how to connect your MIDI syn thesizer equipmentin order to hear M IDI generated by theT utorial patch Tutorial 12 Sending and receiving M IDI notes explains how to configure and test these connections e When you initially open thetutorial patch 49 avascript Scripting pat you will seea largely empty patcher with ajs object in the lower part of the patcher window T hejs object has loaded aJ avaScript sourcefile called autosurface js which is located in thesame folder asthe Tutorial patch bo Make some sliders Sliders i c tumiton reverse the sequence j autosurface js 259 Tutorial 49 Advanced scripting Thejs object is configured to send numbersto aM IDI output device using themakenote and noteout objects It also hasaright out
412. rror 399 416 Index DLS synthesizer 405 documenting patches 104 340 Doing math in Max 25 dollar sign 92 351 355 E echo 83 edetonate 366 383 editing a sequence graphically 377 editor for events in a timeline 364 efficiency 341 efunc 368 emovie 369 Enable Trace 391 enablerefresh 401 encapsulation 210 339 error dialog 399 stack overflow 122 346 error message 392 393 etable 367 event in a timeline 362 exponent 216 exponential curve 173 177 expr 170 expr and if 170 external clock synchronizing Max to 123 externs 401 extra precision pitch bend data 144 F fade in creating 120 file type 311 filename extensions 310 filtering MIDI messages 139 343 filtering out a specific number 56 float 15 77 floating point division 78 flush 44 follow 150 font characteristics 20 formatting MIDI messages 140 fpic 68 222 frequency distribution histogram 133 funbuff 102 348 368 G gate 61 214 Gates and switches 60 Get Info table 126 getruntime 402 getsleep 402 getslop 402 getsystem 402 Ggate 60 global variable 90 grace note patch 108 graph interval 380 graphic 194 Graphics 194 graphics 194 graphics file 68 197 Graphics in a Patcher 200 graphics window 194 grow bar 20 70 Gswitch 60 H hexadecimal number displaying 34 entering 356 hide objects in a bpatcher 205 Hide On Lock 67 hideglobal 402 hidemenubar 402 Histo 133 hslider 48 I if 171 imitation 87 imovie 200 improvising patch 134 in 352 incrementi
413. rwise that part of thecodewill beignored Similarly you can access the arguments by number as an array a arguments 0 will assign the variablea to the value stored in thefirst argument of the message In our case this refers to thenumber of sliders wewant to create 265 Tutorial 49 Advanced scripting Object Creation and Maintenance From theperspective of using js for object creation in M ax the M axobj class allows us to use our object variables to create connect and destroy objects Thisisdoneby first accessing the Patcher object which isaJavaScript representation of our M ax patch Thestatement this patcher remove thefunnel tellsjs to find aM axobj called thefunnd in the Patcher called this which is always the patcher con taining thejs object and deleteit The this in thestatementisactually optional butit sworth not ing that you can use avaScript to control objects in patches other than theonein which thejs object resides To create an object weassign a variableto anew M axobj created by the Patcher thefunnel this patcher newdefault 300 300 funnel a In this case the M axobj thefunnel is created to bea default object at coordinates 300 by 300 on the patcher window Theobject s typeis set to funnel with theobject s arguments set to whatever is contained in the variablea Note thenewdefault method to the Patcher object creates a new object just as if you had created it manuall
414. s can be redi rected out outlets of thetimeline object In fact actions can themselves send messages out outlets 373 TI mel Ine Creatinga graphicscoreofM ax messages of thetimeline object T his type of interaction is achieved by using thetiout object in an action patch and by creating outlets in the timeline object itself A second argument typed into atimeline object specifies thenumber of outlets the object will have the first argument is a timeline filename to be read in automatically timeline TimelineFile ti 2 The second argument determines the number of outlets For messages to come out of those outlets at least one of the actions used in thetimeline must contain a tiout object Any message that goes into atiout object in the action will come out of the appropriate outlet of thetimeline object using that action H ereis an action that is specially designed to send integers out the left outlet of thetimeline object that uses it and symbols out the second outlet intow events in the timeline will symbolom events in the timeline come out the 1st outlet of the will come out the 2nd outlet timeline object titmd intout i titmd symbolout s ti ut 1 tidut 2 The argument to tiou tells which outlet the message will be sent out Theactual messages to be sent out the outlets of timeline need not originatein the timeline event editor they may be generated within the action patch itself Below isan example of an action which und
415. sage box lt filename gt error opening file and variations An error occurred opening a file that was properly located M ost likely the fileor media hasa problem lt objectname gt lt filename gt can t open Occurswhen apatch isloadingor when an object is created that readsits data from aseparatefile The file that was to be read in automatically was not found in M ax s search path or was not atype of file that the object is capable of opening The erroneous filename has usually been specified as an argument to an object such as coll seg or table M ake sure that thefileisin M ax s search path lt objectname gt bad argument Occurs when creating anew object with typed in arguments T here is something wrong with what you typed after the name of an object Usually the object is expecting a symbol and you typed in anumbe or vice versa Check the object s argument specification list in the O bjects sec tion lt objectname gt bad arguments for message lt message gt Occurs when an object receives a message that it understands but one of the arguments in the message is not what the receiving object expected Usually the object was expecting a symbol argument and got a number or vice versa Check the object s input list in the O bjects section lt objectname gt doesn t understand lt message selector gt Occurs when an object receives a message that it doesn t expect It is possible to make patch cord connectio
416. sagesearch followed by thefirst word of oneof themarkersin thetimeline thecur renttimepointer of thetimelinemovesto thelocation of that marker SeeT utorial 41 for an exam ple of searching for a marker You can even create a M arker Track in a timeline window a track that does nothing but contain marker events W hen atimelineobject receivesthe message markers followed by thenumber of oneofitsoutlets it sends the first word of each marker contained in its tracks out the specified outlet to be stored in a menu object This menu can then be used to move thetimelines current time pointer to the loca tion of a particular marker by prepending the word search to the text output of the menu Using timeline in a patch So far wehaveonly discussed theuseof thetimelineeditor window O nceyou havecreated ascore consisting of action tracksand messagesto besent to thoseactions you will no doubt wantto save your score for later use Choose Save from the Edit menu and save your timeline M ax recognizes timeline files as being different from patches and when you reopen the file it will be displayed once again in the timeline editor window and you can play or further edit your score Once you have saved your timeline as afile you can also load it automatically into a patch W hen you createatimeline objectin apatch withouttypingin an argument anew timelineeditor window is automatically opened for you H owever if you typein atimeiine filename that
417. sary to reopen the window onceit has been closed and it can also beused to bringthe windowto theforeground W ehavealso used thekey object to includekeyboard shortcutso and w for open and wclose since the graphics window completely covers the Patcher window onceit has been brought to the foreground Drawing Shapes Usethe open message or theo key on your keyboard to bring theAnimation window to the foreground Play some notes on your keyboard and watch what happens in the graphics win dow Analyze the correlation between your actions and thegraphics onscreen e Choose42 Graphics from theWindows menu or use thew key on your keyboard to close the Animation window Double click on the patcher Eight Rectangles object to examine its contents 194 Tutorial 42 Graphics The played pitches and velocities are passed through a poly object which assigns a unique voice number 1 through 8 to each notecurrently being held The pitch and velocity are passed out the middle and right outlets and the voice number is sent out the left outlet If more than 8 notes are held down atatimeon thekeyboard poly sendsout anote off messagefor the oldest noteto make room for the newest note T his is known as voice stealing The first argument tells poly how many notes to hold and the second argument if non zero tells poly to steal voices pitch voie I her pitch velocity The pitch and velocity of thenoteare used to determine characteristics of th
418. se Theimovie object lets you embed aQuickTimemoviedirectly into your Patcher It displays the moviein thesameway as the movie object seeQuickTimeM oviesabove and reportsthemouse location whenever the mouseis clicked within it See Also graphic Open agraphics window imovie Play aQuickT imemoviein a Patcher window Icd Draw QuickDraw graphicsin aPatcher window mousestate Report the status and location of the mouse movie Play aQuickT imemoviein awindow oval Draw solid oval in graphics window pict Draw picturein graphics window Tutorial 42 Graphics Tutorial 43 Graphicsin apatcher 325 Collectives GroupingF ilesinto a SingleP roject What is a Collective OpeningaM ax patcher may need to open anumber of other M ax files even though it seemsas if you are opening only onefile e Thepatcher might require certain external objects e Thepatcher may contain subpatches other M ax documentsused asobjectswithin apatcher e Thepatcher may load other files used by M ax objects T hiscategory would includeM IDI files coll files env script files funbuff files mtr files preset files seq files table files timeline files action patches PICS files PICT files QuickTime movies and so on A program you writein M ax may actually be divided up among a potentially large number of dif ferent files and the absence of any one of those files may prevent your program from functioning properly T oavoid thisproblem M axallowsyouto gather
419. se click e In Program 1 you can click on the Gotcha message box to print it or you can click on the button which sends abang message to the inlet of the message box T he effect is equivalent since in either case the message box is triggered and sends out the message it contains e Program 2 not only proves that the button quite literally sends the message bang it also proves that bang has no special effect on the print object That s because the print object doesn t try to understand the message it receives Its only purposein lifeis to print out what arrives in its inlet e Program 3issort of a puzzler Clicking on either button producesa printout of y bang 13 Tutorial 2 The bang message When you click on the upper button which button actually supplies the message to the print object The answer isthelower button Theupper button sends a bang message to the lower button The lower button interprets the bang messageas Do it and performsits expected function which isto send abang message T heprint object simply prints out what it receives Summary bang is a special triggering message that causes an object to perform its task The button object s task isto send out the message bang thus triggering other objects See Also button Flash on any message send a bang 14 Tutorial 3 A boutN umbers int float and list We have seen that a message can consist of text and that some words havea sp
420. se the abs object to makethe values positive W edon t want any 0 velocities because they ll be supplied by makenote House State expr pow f 1 128 Boe w 2 5 460 40 nakenote 1 40 To get thetempo weusethe changein vertical location of the mouse But weonly want to detect substantial change so we first filter out slight changes 7 pixels Then welimit the values between 128 and 128 and useexpr to map that range onto an exponential curvefrom 40 to 500 Thus alargeincreasein velocity causes a fast tempo whilealarge decrease in velocity causes a slower tempo A gradual changein velocity does not changethetempo 177 Tutor al 39 M ousecontrol Summary W hen the mouse button is down mousefilter suppresses all numbers it receives until the button is released then it sends out the last number it received mousefilter can be used as amouse depen dent gate especially to allow you to view many numbers but only send on theones you want Every timemousestate receives a bang it sends out thelocation of themouseand thechangein location sincethe last report These values can beused to provide continuous musical control giving you the ability to usethe entire screen asa field in which to produce values in two dimen sions by moving the mouse W hen the mouse button is pressed mousestate sends 1 out its left outlet and when itis released mousestate sends out 0 These values can beused to turn a processon and o
421. sed in an expr or if object to separate items within a function in a mathematical expression asin the exam ple below N otethat acommain an object box should always be preceded by a backslash so that M ax doesnot try to interpret it as a special character The pow Eumrtion requires a coma between its arguments expr powttaii fiz xto the y power U sea backslash when you want to usea special character but don t want M ax to interpre it as such In theexample above thecommaisneeded to separate arguments to thepow function Punctuation in a Message Box Thedollar sign can be used in a message box to indicate a changeable argument W hen the message box contains a and a number such as 2 as one of its arguments that argument will be replaced by the corresponding argument in theincoming message before the message box sends out its own message The pound sign followed by anumber such as 2 in amessage box hasthesame meaning asin an argument of an object box W hen thepatch containing a argument is used as asubpatch 355 Punctuation Special characters in objects and messages inside another Patcher the argument is replaced by the corresponding argument typed into the subpatch object box in themain Patcher Seethe Arguments chapter for examples A comma in a message box is used to send a series of separate messages The comma indicates the end of onemessage and the beginning of thenext message 60
422. sed time and that informa tion is mapped to send increasing values to the mod wheel of the synth O ver the course of 6 sec ondsthetimeprogresses from 0 to 6000 causing thecontrol valuesto increasefrom 0 to 127 W hen the value reaches 128 the clocker is turned off by sel The result isa 6 second linear fade in of the modulation effect on the synth 0 02117 feel 126 to cklouk Theint object is included to truncate the float output of the object so that sel will make an accu rate comparison counter Thecounter is not itself a timing object but it is frequently used in conjunction with metro because counter counts thenumber of bang messages it has received T he metro counter combina tion isan effective way to increment or decrement a value repeatedly InthepartofthePatcher window marked B thefirst argument to counter specifies thedirection of the count 0 for upward 1 is for downward and 2 is to go back and forth between up and down 120 Tutorial 31 sratine The second argument sets the minimum value of the count and the third argument sets the max imum value N ote Themeaningoftheargumentsto counter changesdependingon how many argumentsthere are Look under counter in the M ax ReferenceM anual for details Thecount is sent out the left outlet W hen themaximum 127 is reached counter sendsa 1 out its right middleoutlet This1 is detected by sel which togglesthemetro off T hisis another way to
423. slider 51 Uzi 286 V v94 value 94 variable 81 variable global 94 varispeed playback of sequences 215 300 317 W weighted randomness 111 window size and placement 228 Y Your argument 110 Y our object 105 Symbols 51 25 51 in a message box 92 351 in an object box 352 25 amp amp 53 25 25 25 51 gt 51 gt 51 94 352 53 Numerics Ox hexadecimal indicator 356 A About numbers 15 absolute path 310 abstraction 101 accompaniment patch 118 151 accum 79 action timeline 184 362 active 180 active window 98 address of a funbuff 102 Align 12 All Notes Off message 58 all notes off message 227 All Windows Active 98 and 53 animation 194 in a Patcher window 200 anti aliased text 222 append 93 received in a message object 94 351 application written in Max 220 argument 17 changeable argument 92 351 355 arithmetic operators 25 array 348 funbuff 102 of symbols 350 table 125 arrays multi dimensional 284 ASCII 72 Assistance 100 Auto Step 391 Automatic actions 179 automatic actions 179 autoscroll while playing a timeline 372 B b 24 background window 98 backslash 94 352 355 bang 13 344 received in a table 133 358 bang means Do It 13 415 bangbang 23 beats per minute 122 bendin 56 bendout 56 bent patch cords 66 blinking text 226 boot path 310 both numbers are not zero 53 bouncing graphic effect 207 boxcolor 401 bpatcher 204 breakpoint 3
424. slider can actually change values as they pass through e Click on the message boxes containing numbers above the middle slider objects Notice that both slider objects moveto display the value they have received but the number that each onesendsisdifferent T heslider on the left has an O ffset of 0 and aM ultiplie of 1 soitdoesn t changethe number it receives but the other slider multiplies theincoming number by 2 and adds 1 to it Notice also that the numbers that are received and sent out can exceed the specified range of the Slider and that a float gets converted to int Other Inputs A slider can receiveother messagesin itsinlet W hen itreceives bang itsendsout whatever number it currently is displaying with the M ultiplier and O ffset effects The word set followed by a num ber sets the value of theslider without sending any output The word size followed by a number changes the R ange of theslider to that number Tutorial o Usingtheslider Summary A Slider lets you output acontinuousstream of numberswithin aspecified rangeby draggingon it with the mouse It will also show and send out numbers received in itsinlet making it useful for graphically displaying the numbers passing through it By choosing Get Info from the O bject menu you can change the Slider Range and can also specify aM ultiplier by which all numbers will be multiplied before being sent out and an O ffset which will beadded to thenumber aft
425. ss only note on messages sustain Hold note off messages output them on command 45 Tutorial 14 Slidersand Dials Diverse Onscreen Controllers In this tutorial we ll introduce some objects that function similarly to the slider but differ some what in appearance and behavior reduce the velocity Thake sure the velocity is never less than 1 kslider Patch No lissimilar to the patch in the previous chapter It allows you to play notes with the mouse H owever this patch uses a keyboard slider kslider e Tryplayingnotesby clicking and or draggingon thekslider thas been set to output numbers from 36 to 96 MIDI notesCl to C6 out itsleft outlet Thenumbersarethen sent to theleftinlet of makenote where they are paired with a velocity from the right outlet of kslider and the notes are sent to noteout e When you dragalongthelower half of kslider itoutputs only thenumbers associated with the white keys When you drag along the upper half it plays both white and black keys e Thevelocity that is sent out the right outlet depends on how high the mouseis placed on the key you are playing TheRange and O ffset of thenotes displayed by kslider can be changed by choosing Get Info from the O bject menu The O ffset is the value that will be output by clicking on the lowest note of thekslider and is specified asa M IDI note name The default is C1 36 If you want an offset of 0 46 Tutorial 14 Slidersand dials S
426. ssed out the proper outlet of Ggate only if the most recently received mod wheel valueis 0 and a goto message will pass through thegate only if the mod wheel is at some non zero position Reading the timeline Score e Closethetutorial ac window so that you can see thetimeline editor window again N ow that you have seen what s going on in theaction patch you can figure out what will happen when thetimelineis played In thefirst four seconds thereisawholetable full of pitch events which will besent out one by oneover the course of thosefour seconds A table of valuesis placed asan event in atimeline with the etable event editor Thereisalso a graph of volume events which will likewisebesent out continuously over thespan of timecovered by theevent edi tor known asan efunc Four secondsinto thetimeline aseqcontrol event will send the message start W ehavealready seen that thisstart message will go from thetimelineto theticmd seqcontrol sobject in theaction to asend seqcmd object in theaction to a receive seqcmd object in the41 Timelinepatch and from thereto theseq tutorial41 sc object starting the sequence e Scroll to theright in the window to seethe remainder of thetimeline 186 Tutorial 4 TimelineofM ax messages At the8000 milliseconds 8 seconds point on thetimeline there appear to be several simulta neousevents You can examine a pop up menu containing their exact times by holding down the mousein the left portion of t
427. stem 330 system exclusive 147 end byte 148 status byte 148 system exclusive programming 148 T t23 table 130 288 Don t Save 132 entering values as text 133 146 linked to an etable editor 196 308 quantile message 297 Save with Patcher 131 saving in afile 132 stepping through values 147 Index storingnumbersin 134 viewing 130 Table window creating 133 editing 134 tempo 127 Test 1 Printing 21 Test 3 Comparisons and decisions 67 Test 4 Imitating a performance 91 Test 5 Probability object 115 testing a patch 332 335 text blinking 231 Thepatcher object 102 Thetable object 130 thispatcher 228 thisTimeline 190 thistimeline 316 thresh 166 tiA ction folder 303 tiCmd 189 302 time elapsed between events 79 219 timed progression of numbers 125 timed repetition 17 285 timeline 188 302 editing events 196 TimelineAction Folder 303 timeline editor window 303 Timeline of M ax messages 188 timer 79 tiOut 190 315 titlebar hiding 229 TogEdge 141 toggle 18 toggleand comment 18 togglemodefor ubutton 227 top level patch 271 top level Patcher 278 Trace Enable Disable 337 Tracemenu 337 track in atimeline 189 302 transposed note turning off 77 105 154 transposing 42 105 trigger 23 triggering 25 truncation 14 414 Index type of message 28 1 U ubutton 73 227 umenu 230 unpack 120 urn 213 user interface 225 Using metro 16 UsingtheM acintosh keyboard 76 Usingtheslider 29 Using timers 125 u
428. succession In thesamespirit the uzi object is designed to send out a succession of bang messages as fast as possible T his series of bang messages can be sent to acounter object to convert them to aseries of numbers uzi itself counts thebang messages as it goes and sendsthe count out its right outlet so it can be used to send asequenceof numbers as fast as possible T hefollowing exampleshowstwo waysto send sixteen different M IDI messagesas fast as possible Binteen Messages in a singl box 1 2 3 4 95 6 7 8 9 10 11 12 13 14 15 16 All Hotes Oe on sinteen different channels M ultiple messages sent in immediate succession 346 Loops W aysto perform repeated operations See Also clocker counter metro tempo uzi Report the elapsed time at regular intervals Count thebang messages received output thecount Output bang at regular intervals Output numbers at ametronomic tempo Send a specific number of bang messages 347 D ata Structures Ways of StoringD ata in M ax Storing Data M ax has objects specifically designed for storing and recalling information ranging from simple objects that storea singlenumber to more powerful objects for storing any combination of mes Sages Thesimpleint and float objects storeanumber and then output it in responseto a bang They are comparable to avariablein traditional programming languages T hevalue object allowsa single value to be changed or reca
429. t function first checksout how many valueswe ve sent in from M ax e g if arguments length 2 Thefunnel object puts out alist corresponding to thenumber of the inlet receiving the value fol lowed by the valuereceived For example thenumber 55 arriving at thesecond inlet which is 267 Tutorial 49 Advanced scripting really inlet number 1 will trigger thelist 155 from thefunnel object W echeck to makesurewe havetwo argumentsin our message before weproceed inour 1ist method asweuseboth the values in thelist in thefunction W eusethe first argument which slider wemoved to determine which eement of the array thevalues we set to the second argument the value e Lookatthebang and reverse functionsin theJavaScript code bang steps through sequencer function bang if seqcounter gt numsliders reset sequencer seqcounter 0 if thereverse read from the array backwards outlet 1 numsliders seqcounter 1 send out our location in the sequence outlet 0 thevalues numsliders seqcounter 1 send out the current note else read from the array forwards outlet 1 seqcounter sound out our location in the sequence outlet 0 thevalues seqcounter send out the current note segqcountert increment the sequenc reverse changes sequence direction function reverse val if arguments length thereverse arguments 0
430. t lt string gt YourApplication icns lt string gt 335 Groupingfilestocreate Col ect Ives a single application 7 You may want to change other information in this file such as the nameof your application and its version number key CFBundleName value string Your Application or lt key gt GBundleName lt key gt lt string gt Your Application lt string gt To make an icon file you can useApples conComposer included in the D eveloper applica tionsfolder when you install thedeveloper tools or athird partyicon developmenttool such asthe IconBuilder plug in for Adobe Photoshop from Icon Factory To include your property list and icon files in the standalone you ll add them to the collective script but the technique for adding each fileis slightly different For the property list file first ensure that thefilenameends in plist then click the Include File button and choose the plist file For the icon file click the Include File button and choose the file then replace the word include with appicon H ereis an example include Disk MyAppFiles Info plist appicon Disk MyAppFiles Icon M yApplication icns When building your application the application builder will copy the Info plist fileto the cor rectlocation in your package theC ontents folder then it will copy an icon filespecified with the appicon keyword to the Resources folder You will likely need to restart your computer before the standalones ic
431. t Using a Math Object e Look atthecodefor mytask again paying attention to thelinethat changes the decay value with every bounce decay decay Math exp t count dcoeff increment decay vari able In addition to the objects that allow for interaction between JavaScript and M ax M axobj Task JavaScript hasanumber of coreobjectsthat can beuseful when writing programs for js TheM ath object hasalargelibrary of built in propertiesand methods that allow you to perform commonly needed mathematical functions In our code weusethe exp method to the M ath object which returns the value of E the base of the natural logarithm roughly 2 71828 to the power of its argument in this case our decay coefficient multiplied by thenext ball count Thisis crucial to the modeling of the exponentially increasing rate of the bounce event Note TheM ath object in JavaScript is roughly analogousin features to the math library in C or theexpr objectin M ax which isitself based on theC math library A number of other predefined coreobjects e g Date String providesimilar extensionsto thelanguagethat more or lessmatch their C equivalents e g time string Arguments to the js Object Two of our script s variables dcoeff and note are determined by the arguments given to thejs object j globaltask js 0 013 68 T heseargumentsareparsed in our global codeblock by checkingthejsarguments property of our js object if jSarguments leng
432. t called autopattr in the lower right corner has a number of mes 301 Tuto ri a 53 M orepatcher storage sage box objects connected to it that contain different example settings for the drawing con trols counter ranges drawing angle drawing offset counter desyne brgb 0 0 0 penmode 37 clear lt clear Theautopattr object has much of the same functionality as pattrhub allowing you to send and query values from objects exposed to thepattr system within a patch 302 Tuto ri a 53 M orepatcher storage e Unlock thepatch and select one of the drawing interface controls other than thetoggle object i e therslider or number box objects at thetop U nder theO bject menu select Name AAA pattr2 a Y TOES AE E NANI as Name Object a Set Object Name for range rslider N otethat our four control objectsin the patch havenames range angle offset and desynch If you create a group of user interface objects and givethem names an autopattr object will auto matically expose those objects into the pattr system exactly as if they had pattr objects all bound to them individually In thissense autopattr also functions as a set of pattr objects allowing you to include multiple objects for patcher storage with one object Thedefault behavior of the autopattr object isto expose only named user interface objectsina patcher when the object is created The autoname
433. t inlet isthe control inlet as with gate and theremaining inlets can receiveany messageto besent outtheoutletiftheinletisopen Thenumber of inlets in addition to the control inlet is specified by the argument There can be as many as 9 e Send anumber to the leftmost inlet of switch to open one of the inlets or 0 to closeall inlets Then send numbersto theother inlets and you will seethat only theoneinlet you specified is open openone of fp 3 inlets for to shut all Using switch you can have messages coming into individual inlets from several different objects but switch listens to only one of itsinlets 61 Tutorial 17 Gatesand switches Any typeof message can be passed through gate or switch Left Inlet Is Control Inlet Unlikemost objects which are triggered by a message received in the left inlet gate switch Ggate and Gswitch all usethe left inlet as a control inlet for telling which inlet or outlet is to be open M essages received in the other inlet s are then sent out the appropriate outlet route Oneothe valuable traffic controller is route sort of across between sel and gate When route receivesamessagein itsinlet it comparesthefirst item in themessageto each of itsarguments If it findsamatch itsendstherest of themessageoutthecorresponding outlet Ifthereisno match the entire message is sent out the rightmost outlet route is especially useful when it is sent a list Sev eral items s
434. t least one track within that timeline A track corresponds to and communicates with a specific action patch you have created 3 Placeeventsin thetimeline strack s specifying messagesto besentto theticmd objectsin the track s action Creating an Action Any patch that receives messages from an inlet can easily be converted to receive messages from a timeline track For example the patch shown below receives a symbol an int and afloat in its inlets and prints then in the M ax window print afloat print a_symbal But in order for this patch to receive messages from a timeline the inlets must be replaced with ticmd objects as shown below tiCmd pr intsymbol print afloat print a symbol 362 TI mel Ine Creatinga graphicscoreofM ax messages Theticmd object requires two or more arguments The first argument isa command name by which thetimelinecan refer to theticmd object The remaining arguments indicate thetype of message ticmd is expecting and determinethe number of outlets it will have Each argument after the command name creates an outlet and specifies thetype of information to be sent out of that outlet for int f for float for list s for symbol b for bang and a for any message You will notice that thereis an additional outlet on each end of theticmd objects these outlets will be explained later Any patch that contains at least oneticmd object is ready to be used
435. t once again we have included a flush object to guard against stuck notes Every timea stop message is sent to mtr a bang is also sent to flush to turn off any notes currently being held 156 Tutorial 36 M ulti track sequencing Recording Messages from Different Sources Note data is not the only thing that can be recorded with mtr messages from virtually any combi nation of objects can be recorded and played back by the same mtr object In Patch 2 we record numbers from pgmin bendin ctlin and a dial each on a different track e Click on therecord messagein Patch 2 and send pitch bend modulation and program change messages from your M IDI keyboard for several seconds You can also movethe dial with the mouse W hen you havefinished click play and you will see your performance played back controlling other objects The first 0 message can be used to eliminate the delay between thetime you clicked record and the time you started to transmit M IDI messages from the keyboard T he message delay 0 causes every track to start at time 0 even if you started sending data to thetracks at different times e Toseethedifferencebetween first 0 and delay 0 click on record and send about 5 secondsof pitch bend data then 5 seconds of mod wheel data and so on W hen you havefinished click stop e Nett click first 0 to eliminate the initial delay before any data was recorded Click play to see your performance replayed e Nowclick delay
436. t s inlet ourself this box assign a Maxobj to our js object if numsliders this patcher connect thefunnel 0 ourself 0 connect the funnel to us else complain about arguments post sliders message needs arguments post In pseudo code our sliders function performs thefollowing steps Check to see if the arguments for the sliders method are valid If true Make sure the number of sliders requested are in a reasonable range 0 128 Delete any objects previously created by our js object Make the new objects and connect them to one another Find our js object see below and connect our new funnel to it If false Post an error message in the Max window and exit the function Our JavaScript codetakes advantage of two important features of procedural programming namely conditional statements if else and iteration for loops If you ve used another programming language such asC or Java you should find these constructions familiar A Java Script reference will help you with the specifics Oneofthefirst thingswedo in our sliders function ischeck to seewhattheargumentswere to thesliders message sent in from the patcher W edo this by checking the arguments property of the function itself e g if arguments length some code here will execute the code between the braces only if there are a non zero number of arguments to the message that called the function Othe
437. t specify a file extension and a four character filetype tells M ax to associateafilenameextension with a particu lar filetype The messagemax fileformat tx TEXT associates the extension tx with TEXT text files This allows auser to send amessage read george and locate a file with thename george tx It also ensures that files with the extension tx will appear in a standard open file dialog where text files can be chosen Theword getboxcolor followed by an number between 1 and 15 and a symbol sendstheRGB values for thedefault object colorsatthespecified index asalistto thereceive object named by thesymbol 401 M essages tO M ax ControllingtheM ax application geteventinterval getpollthrottle getqueuethrottle getruntime getsleep getslop getsystem hideglobal hidemenubar interval maxinwmenu Theword geteventinterval followed by a symbol used asthe nameof areceive object will report the event interval to the named receive object See also theset eventinterval message to M ax Theword getpollthrottle followed by a symbol used as thename of a receive object reports the current poll throttle valueto thenamed receive object See also the setpollthrottle message to M ax Theword getqueuethrottle followed by asymbol used asthenameof areceive object causes M ax to report thecurrent queuethrottlevalueto thenamed receive object See also the setqueuethrottle message to M ax Theword getruntime followed
438. tandalone application on W indows is actually a folder containing M axM SP Runtime execut able plus a mxf collective file containing your patches and files In addition the standalone folder containsasupportfolder with files necessary to run your application Thefollowinglistshowsthe arrangement of files and folders YourA pplication folder YourApplication exe modified M axRT exe launch this to launch your app YourApplication mxf new format collective containing your patches msvcr70 dll Microsoft C Runtime Library used by M axRT exe and externals support folder ad folder containing M SP audio driver objects mididrivers folder containing M ax midi driver objects M axAPI dll MaxAPI for external objects M axAudio dll M SP library M axQuicktime dll M ax QT interface YourApplication rsr M ac style Resources for your application asintppc dll Support DLL needed for M ax asiport rsr Support resources needed for M ax asifont map Support file needed for M ax Macintosh Standalone Format On M acintosh thestandaloneisan application package which isalso afolder that lookslikeafile intheFinder D ouble clickingon theicon launchestheapplication You can peek into the package by control clicking on it and choosing Show Package Contents from the contextual menu As with theWindows standalone insidethe Contents M acO S folder you will find a mxf collective a runtime application and a support folder
439. tch which can open one of two inlets W hichever inlet the arrow points to istheopen inlet and messages received in that inlet are passed out the outlet M essages received in the closed inlet are ignored T heleftmost inletisthecontrol inlet for switching the arrow back and forth It functions like the left inlet of Ggate e Click on thetwo message boxes to send messages to Gswitch O nly the message received in the open inlet is sent out the outlet Changethe direction of thearrow and try again 60 Tutorial 17 Gatesand switches Ggate and Gswitch will pass on any type of message numbers lists and text gate Thegate object is like Ggate with afew important differences 1 Thenumber of outlets is determined by the argument to gate A single outlet is opened when its number is received in the left inlet All other outlets are closed 2 When thenumber 0 is received in the left inlet all outlets are closed 3 A gate doesnot respond to amouseclick the way Ggate does e Send anumber to the left inlet of gate to open oneof the outlets or 0 to closeall outlets then send numbers to the right inlet open one of 4 outlets for to shut all You can seethat gate can beused to routemessages to any of anumber of destinations just by specifying which outlet the messages are to be sent out switch Theswitch objectopensoneof several inletsto receivemessages and ignores messagesreceived in the other inlets The leftmos
440. tches and durations Or you could usea coll to storea collection of text messages to beshown to the user when certain numbers or symbols are received Call messages by mmber Humbered collection of messages to be displayed to the weer Make sure list is Each abiress in the i ss numbered correctly coll holds a list Prepend set Hake sure you have set Hemory Frotect Off on your synth rhe oe ee Provide note off Wait nexttime ms after duration ms then play next note A method of using coll to play a list of notes Storing text messages in coll You can edit the contents of acoll in astandard M ax text editor window by double clicking on its object box when the Patcher window islocked T hestandard M ax text editor window will open Thetext format used is discussed in the description of the coll object The message box can be considered a kind of data structure sinceit can hold up to 256 different itemsas arguments T hecontentsof amessage can bemodified using set and append messages and message boxes can include changeable arguments which are replaced by the arguments of mes sages it receives in itsinlet Individual itemsin a message box can be accessed by sending its con tents to another message box with changeable arguments as shown in the example below Each item of the message is weed to do a different thing 349 Data St ru ct ures Waysofstoringdatain M ax T
441. tem Sounds bad message Same as lt objectname gt doesn t understand lt message selector gt bad receiver Same as lt objectname gt doesn t understand lt message selector gt bag float int pack table missing or incorrect arguments to send Occurswhen thepatch isrunning and abag float int pack ortable object receives asend message without an argument or with an argument that is not a symbol or isnot thenameof an existing receive object 395 Erro rS Explanation oferror messages can t connect lt objectname gt to lt objectname gt Advisory message produced when you try to connect an outletto an inletthat doesn t understand the message sent by the outlet You will also noticethat the inlet was not highlighted when you dragged the mouse over it can t fragload lt objectname gt missing lt libraryname gt err lt number gt An external object that depends upon a particular shared library was not loaded because the shared library isnot available You ll seethis error if you try to usean object for M SP with thenon M SP version of M ax the missing library will becalled M axAudioLib in this case or if you try to usesome external objects created for an earlier version of M ax M SP eg attempting to load an OS 9externalin an OSX version of M ax M SP O therwise to solvethis problem you may need to relocate the shared library or update your system check failed t_ newptr in overdrive This message
442. tforward solution of the matter issimply to map one range of values to another In this patch we use velocity to calculate the height of the rectangle pitch to calculatethe rectangles placement from left to right and pitch class C C D etc to determineits color 195 Tutorial 42 Orp Velocities rangefrom 0 to 127 and thevertical range of pixels in thedrawing area is from 0 to 322 342 20 322 We made the decision to center all the rectangles vertically in the drawing area so we want to calculatetheheight of therectangleas adistanceup and down from thecenter This means that in fact wewant to use the vertical range 0 to 161 322 2 161 and 0 to 161 then offset the rectangle downward by 161 pixels 161 Use the ranges u g oto 1bl and 0 a to 161 indow i We want ko Then all 161 the vor draw out from 161 161 to shift them 322 piek high the center downward 322 322 B22 Toconvertthevelocitiesto theproper range Oto 161 or Oto 161 wemultiply by 1 27 or 1 27 then add 161 T heresulting values aresent to pack to bestored in thelocations for thetop and bot tom coordinates of the rectangle Note that when the velocity is 0 the height of the rectangle will be 0 both the top and the bottom coordinates will be 161 This causesthe rectangle to disappear when the note is released because it s drawn with a height of 0 Theeffect of pitch on thehorizontal coordinates of therectangleiscalculated in asimilar manner
443. th gt 1 argument 0 is the name of the js file dcoeff jsarguments 1 if jsarguments length gt 2 note jsarguments 2 N otethat argument 0 isthename of the avaScript file eg globaltask js so realistically we will usually start looking at the arguments starting at 1 Theabove code checks to makesure that the arguments exist before we attempt to assign their values to variables The Global Object e Closethejs object s editor and return to theT utorial patch for amoment In the lower left hand corney look at thenumber box connected to the message box containing the text bounce starttime 1 Type 2000 into the number box and enter the value Send abounceby clickingon 277 T asks A rgumentsand Tutorial 50 Global O bjectsin JavaScript thebutton atthe top N oticethat thetiming between bounces in all the objects is wider than before Try changing thenumber box to a small value Thetiming interval should start out quicker W ewould expect our message box to have sent the message starttime 2000 to a receive object some wherein our M ax patch called bounce In fact it sets the starttime property of a Global object assigned to respond to the namebounce to 2000 within our js objects W eaccomplish this be declaring a Global object in our global code Global Max namespace variables glob new Global bounce glob starttime 500 In our code we ve created a variable glob and assigned it to anew Glo
444. than b AND cis greater than d both inputs are Won zero Note that in the example above the number 5 a must be sent last so that all the other values will have arrived when amp amp is triggered Patch 4 is similar to Patch 3 but it uses to look for two pitches instead of one T he patch says if the pitch played is B OR itis D then play thenotes G1 and F 3 The effect of course isto accompany thenotesB and D with an incomplete dominant seventh chord e Play a maody in the key of C on your synth Patches 3 and 4 provide you with an annoyingly H aydnesque accompaniment 53 Tutori al 15 M aking decisions with comparisons Using Comparisons to Toggle an Object On and Off Patches 3 and 4 demonstrate that any number and thus any key or combination of keys on the synth can beused to trigger something in M ax Similarly the 1 and 0 sent out by relational oper ator objects can be used to turn an object such asmetro on and off Patch 5 demonstrates thisidea e Play thenoteC6 high C on thesynth Assoon as you release the key Patch 5 begins playing the note repeatedly until the next time you play a note The patch is looking for thecondition when the pitch is equal to 96 and the velocity is equal to 0 When both conditions are true amp amp sends out 1 otherwise amp amp sends out 0 O bviously the vast majority of note messages will cause amp amp to send out 0 In order to avoid sending thenumber 0 to metro ov
445. the strong beats of the 4 4 measure and smaller on the weaker pulses e Select avelocity sensitivesound on your synth and turn on thetempo object External Timing Themetro line clocker and tempo objects can be synchronized to some timing source other than M ax s internal millisecond timer such as atime code generator an external sequencer or even some other software sequencer For details look under those object names as well as thesetclock object in the O bjects section of this manual Summary W hen clocker is turned on it sends out the elapsed time at regular intervals Thetimevaluecan be mapped to other ranges to make then depend on the passing of time The counter keeps track of how many bang messages it has received and sends out the count The count can be restricted to a specific range and the bang messages can be supplied repeatedly by a metro to increment and or decrement the counter at a specific speed This is another way of creat inga particular progression of numbers over time Theline object isa third way of generating a linear progression of numbers line outputs numbers in aramp from some starting value to some ending value arriving at the new valuein a specific amount of time Incrementing numbers by means of recursive loops without some type of delay between repeti tions can result in astack overflow error which causesM ax to stop itsinternal scheduler Choosing Resume from the Edit menu restarts t
446. their port assignment See Also fpic Display apicturefrom agraphicsfile menubar Putup acustom menu bar pcontrol Open and closesubwindows within a patcher thispatcher Send messages to a patcher Tutorial 19 Screen aesthetics Tutorial 43 Graphicsin a patcher Collectives Grouping files to createa single application 227 Tutorial 46 BasicScripting Introduction M ax 4 offers anew way of working with objects and patchcordswithin a patcher scripting Script ingpermits you to perform numerousoperationson M ax objects by sendingsimpletext messages to thethispatcher object Scripting commands are available which create and delete objects and patchcords send values to objects and change object properties such as visibility sizeor position With scripting M ax programmers may change objects connections and patcher layout even when the Patcher window islocked Scripting might be useful for any number of purposes e Instantiating and deleting elements of a patcher as you need them e Creating altering and deleting connections between objects e Replacing embedded objects such as patchers inside a bpatcher object e Controllingthevisual arrangementof patches You can changeobjectsizes and arrangements even in responseto user input Give It A Name In order for scripting to work objects must have names AIl scripting commands refer to object namesin order to properly assign actions to them N ames can beassigned in one of several wa
447. thenumber box will makeit visually distinct from themessage box Also thetriangleshowswhen anumber box has been clicked on by becominghighlighted T hepresenceor absenceof thetrianglehasno effect on the way the object functions but it lets you change the appearance Ea aa Drawin Bold displaysthenumber in bold typeface These aesthetic options can beused to empha size certain number box objects or to show the user of your program which ones to dragon The Display pop up menu lets you select the format of the displayed data These options are available only in the int number box Decimal the default Hex Foland octal pel Binary MODI Hote Hames 03 Hote Hames C4 Although we won t be using these options in thetutorial the Inspector will also let you assign col ors to both thenumbers and the box they arein or to make the box transparent You can also choose fonts and font sizes for numbers from the Font menu i O Note Numbers entered by typing into a number box must be typed in the same format as that in which thenumber is being displayed Mouse Options Normally thenumber box sends out a continuous stream of numbers as it is being dragged upon with the mouse The Output only on M ouse Up option causes the number box to send out only the last number the number that is showing when the mouse button is released This lets you see the numbers as you drag but only send out the single number that you choose When Can t Changeis
448. thevaluesishalf of thetotal sum In this case this would be 63 since 64 10 640 which is half of 1280 bang A bang is equivalent to a quantile message with a random number between 0 and 32768 asits argument or an fquantile message with an argument randomly chosen between 0 and 1 Repeated bangsto atable will return table indiceswhich contain higher values more often than indices which contain lower values In the quantile exampleabove all indicesare equally likely to bereturned by bang becauseall the valuesin thetable arethesame H owever if oneof thevalueswere 1000 theindex at which thevaluewas 1000 would occur far morefrequently than any other table index Exactly how frequently This is determined by first taking the sum of all values in thetable which for a table with 127 indices set to 10 and one at 1000 would be 2270 For the oneindex set to 1000 we divide 1000 by the sum 2270 and get a probability of 44 percent For any of the other 127 indices set to 10 the probability is 44 percent that any onewill be chosen So the index set to 1000 will occur about 100 times more frequently than an index set to 10 See Also histo M akeahistogram of thenumbers received table Store and edit an array of numbers Tutorial 33 Probability tables 358 Sequencing Recordingand PlayingBackM IDI Performances seq M ax has four objects for recording and playing back M IDI performances seq follow mtr and det onate The performance can c
449. things a computer program does is perform somekind of atest then make a decision based on the result of that test The test is usually some kind of comparison such as see ingif two numbers are equal The answer to this test can be used to determine what the computer does next Numbers are compared using relational operators which characterize the relationship of onenum ber to another with such terms asisless than is greater than is equal to etc M ax has several rela tional operator objects for comparing onenumber to another lt means is less than lt meansis less than or equal to meansis equal to gt means is greater than gt meansis greater than or equalto meansisnot equal to M ax s relational operator objects send out the number 1 if the statement is true and 0 if the state mentisfalse So for example to test thestatement 7 isgreater than 4 you would send thenumber 4 to theright inlet of a gt object then trigger the object by sending the number 7 in the left inlet Since the statement 7 is greater than 4 is true the objects sends out thenumber 1 e Dragonthenumber boxatthetop of Patch 1 N oticeespecially theoutput of each object asyou pass by thenumber 5 Therelational operators normally expect to receive ints in the inlets Floats are converted to int before the comparison is made Likethe arithmetic operators however the relational operators can compare floats if thereis afloat argument typed in 5l
450. tion thecommand name of each ticmd object in that action becomes available as an event which can be placed in the event portion of that timeline track Additionally whenever one of the actions used in your timeline contains a movie object into which a QuickTime movie has been read either with atyped in argument specifying a moviefile or via a read message the movie window will be opened and anew typeof event editor will become available in that action track Thenew event editor is called emovie It allows you to placea start event in thetrack which will be sent directly to the movie object without having to go through ticmd 6028 Untitled aja O 2 bee ee oo 00 00 00 02 04 Track Display 90 00 00 00 704 00 00 05 00 00 1 2 00 F oe 1 playmowie start emovie globe_spin mov mi tt addeventtoT controlmovie A marker When you place an emovie event in thetrack a thumbnail miniature frame of the movieis shown in thetrack to remind you what movie will be started at that time eco Untitled mja 0 2 bee eri F oo 00 00 i 00 0415 Frsck Digpiay OO 00 00 O00400 oooso0 001200 EE e a a bul hal Te 1 playmowie ee oe ee ee ae One Inch Four Seconds al 369 TI mel Ine Creatinga graphicscoreofM ax messages Of course it is also possible to send messages to a movie object in an action just the same way you would send any other messages via aticmd object For example you could send a message t
451. tisto try and usethe channel number output to route informa tion later Three ways of getting and separating mote data from Cour different WIDI channels Totem a M ethod A isthemost compact and efficient both in memory and speed Memory Usage If you havewritten arather large program and especially if you have a computer with limited RAM you will want to try and keep down theamount of memory your patch uses when it is loaded Doingso will also make your patch load faster Try to avoid doing similar tasks with many copies of asinglesubpatch since copies of all the objects contained within the subpatch are created for each instanceof thesubpatch you use Itis better to design your subpatch to work with a variety of incoming values than to usethe 1 9 argument featureto differentiate 50 copies of asubpatch Thereisa memory overhead of at least 100 bytes for every visiblebox on thescreen though boxes in closed windows take up less space See Also Encapsulation H ow much should apatch do 343 Loops Waysto Perform Repeated O perations Repeated Actions M any aspects of music making involverepeated actions For example wemight count 25 mea sures of rests hit a gong 4 times in succession repeat the whole section a total of 3 times etc In programming repeated actions are called loops because conceptually wethink of the computer completing an action then looping back to theplacein its stored program whereit started an
452. to cap ture sets the quantity of numbersit will store Thisis oneway to producevaluesfor atable quickly and easily t sagood way to preservesomethingyou havedone such asanicepitch bend and save itin atable for future use To copy captured pitch bend valuesinto atable 1 Click on theclear message to clear the capture objects 2 Movethepitch bend wheel for at least 3 2 seconds Thespeedlim object limits theincoming pitch bend values to 40 per second After 3 2 seconds the earliest values received by capture will be lost as new ones are received 3 Double click on the capture 128 object to open its Text window 4 Select all the numbers in the Capture window 5 ChooseCopy from theEdit menu 6 ClosetheCapture window 7 Double click on thetable object to open its graphic editing window 8 Choosethe Selection tool from the Table window palette 9 ChooseSelect All from the Edit menu 10 Choose Paste from the Edit menu 141 Tutorial 34 Managing raw M IDI data 11 If you want to you can save the Table window as a separate file for future use in patches Stepping Through a table In theleft part of the Patcher window weintroduce another way to step through the valuesin a table A table object has a pointer a place in memory where it stores an address You can set the pointer to point at any address in thetable with theword goto followed by theaddress number in the left inlet For example the message goto 0 sets the
453. to each outlet before sending it out See Also bangbang Send a bang to many places in order buddy Synchronizearriving numbers output them together fswap Reverse the sequential order of two decimal numbers swap Reverse the sequential order of two numbers trigger Send anumber to many places in order 24 Tutorial 8 DoingM athin M ax Arithmetic Operators subtract multiply ivi module left inlet triggers umber in right Timbers are converted unless there I an argu the calewation inlet is stored to int before calevaltion ment with a decimal point M ax has an object for each of the basic arithmetic operations plus a modulo operator which gives theremainder when two integers are divided We call these objects operators and the numbers they operate upon are called operands Each Operator object expects oneoperand in itsright inlet which it stores and then theother in itsleft inlet which triggers the calculation and the output An initial value for the right operand can be typed in asan argument In the upper left example you see both methods Be aware however thatassoon asadifferent number isreceived in theright inlet it will bestored in placeof theinitial value even though that initial value continues to show as the argument Left Inlet Triggers the Object Note that just connecting to an object s inlet does not perform any calculation You have to trigger the calculation by sending a number or bang into theleft i
454. torial 4 W hen detonate receives a start message it does nothing except send out the delta time of its first note event A fter that each next message received causes detonate to send out the rest of the data 382 Detonate GraphiceditingofaM IDI sequence for thecurrent note and thedeltatime for thenext note So thedeltatimecan simply beused asa delay time before sending thenext next message as shown in the following example Thedelta timeof thenext noteisused asthedelay timebeforetriggeringthenext note When the very last note in the score gets triggered by a next message there is no following note so detonate cannot possibly send out the next deta time In place of a delta time it sends out 1 which isasignal that thelast notehas been played Your patch can look for that signal and useitto trigger some process In the following example the end of score signal is used to restart detonate when the last note has ended in order to play thescorein aloop When Lis sent out inteal of triggering another Dext message get tart t 5 the duration of the last mate wait iwtil it s done then restat detonate A delta timeof 1signalsthat thelast note has been played Using detonate in a Timeline A timelineevent editor called edetonate can send list messages from a timeline For any timeline event that sendsalist messageto ticmd an edetonate may beplaced in thetimelineto represent that event You can then double click on
455. trol the clicktrack window Summary Theloadbang object sends abang whenever the patch that containsitisloaded into memory The closebang object sends abang when thepatch that containsit isclosed T hesebang messages can be used to start processes open or close agate send a message etc W hen thepcontrol object receives an open or close message it opens or closes all subpatch objects connected to itsoutlet You can also enableor disableM ID I usingtheenable 1 and enable 0 messages to thepcontrol object Disabling M IDI objects while anoteis being played however may causea note off message to be lost leaving a stuck note on thesynth Theactive object sends out 1 when the window that contains itis brought to thefront and 0 when some other window is brought to thefront See Also active Send 1 when window isactive 0 when window isinactive closebang Send abang automatically when patch is closed loadbang Send abang automatically when patch is loaded pcontrol Open and closesubwindows within apatcher 182 Tutorial 41 TimelineofM ax M essages Writing a score Composers of orchestral music writethe activities of all the players out together in asinglescore so that all the predetermined events can beseen together organized in time Composers of com puter music often usea M IDI sequencing program for asimilar purpose In M ax thetimeline object exists as acombination of scoreand sequencer A timelinein M axisamulti track sequencer o
456. tsyou createpatch cordsthat bend around objects making your patches easier to understand You can also create segmented patch cords without this option turned on by shift clicking on an outlet Objects and patch cords can behidden from thesight of the user with theH ide On Lock com mand so that theuser sees only thosethings you want seen O bjects which havebeen hidden with HideOn Lock do not respond to clicking and dragging with the mouse Pictures can beimported from graphics applications and placed in a Patcher window with the PastePicturecommand A picturecan beloaded from agraphics fileon disk and displayed in a Patcher with thefpic object Graphical objects can beresized by dragging on thegrow bar in the bottom right corner of the object box Thecolor of some objects can be changed by selecting them and choosing theColor command from theO bject menu The appearance of a graphical object can also be altered by pasting a picture around it to serveas a frame Thetransparent button object ubutton lets you makeany portion of thescreen respond to clicks from themouse Thecombination of these features lets you design the screen to have almost any imaginable appearanceand respond to the mousein a variety of ways 10 Tutorial 19 Screen aesthetics See Also fpic Display apicturefrom agraphicsfile ubutton Transparent button sendsabang M enus Explanation of commands 71 Tutorial 20 U singtheC omputer K eyboard ASAI Objects
457. tual J avaScript codein theT utorial patch thenumber 8 isreolaced by thelocal variable a which represents thenumber of sliders we want to create Finding Ourself in All of This Oneimportant thing we accomplish in our sliders method isthe connection of the ava Script created funnel object to our jsobject sinlet H owever ourjs object wascreated by hand not by our avaScriptcode thiswould beimpossible if you think aboutit H ow do webind aM axobj to an object that was created independently of aJ avaScript program ourself this box assign a Maxobj to our js object The box property of our patcher returns a M axobj referring to our js object itself W ethen take thevariableoursef and assign it to ourjs object This allows usto makeconnectionsto the object containing our JavaScript code W ethen connect our funnel object to our js object using our newly assigned M axobj ourself this patcher connect thefunnel 0 ourself 0 Other Methods Thejsobjectin thisT utorial doesn tjust createand connectaM IDI control surface it also reactsto messages from the control surface as well as other messages from the M ax patcher e Openup thesourcecodefor thejs objectin theT utorial patch again and look for thefunction called list list read from the created funnel object function list val if arguments length 2 thevalues arguments 0 arguments 1 Aswith oursliders function our Lis
458. typefoo into an object box to load a patcher file and if thereisafilein the search path called foo pat it will beloaded N ote however that if there wereafilecalled foo anywherein the search path with the proper M acintosh type information or on all platforms was actually the right typeof file after M ax examined its contents it would befound before foo pat Thisis because M ax goes through its entire search path looking for an exact match before it tries to match based on filename extensions To associate afilenameextension with afiletype within a patcher you can simply typethe mes sage to M ax into amessage box preceded with asemicolon e g maxfileformat txt TEXT T his may beuseful if you don t want afilenameextension and filetypeto be automatically associated every timeyou launch M ax External Object Name Mappings Thereare other filesin theinit folder used to specify mappings between object names and file names On someoperating systems it is not possibleto use certain characters in filenames H ow ever M ax has traditionally had object names with some of these characters in them In order to avoid problems with these objects amapping between an object nameand afilenamecan be established using the objectfile message to the max object For example max objectfile rminus specifies that when you type into an object box M ax will look for an external object file called rminus In addition when you ask for help on the
459. u can check Save with Patcher so that it will be saved as part of your patch 3 ChooseTextfrom theN ew submenu of theFilemenu to open anew T ext window T ypein the word table followed by alist of numbers then save the file Once you have saved a Table file you can useit in a Patcher window by creating a new table object and typing in thetext filename as an argument 128 Tutorial 32 Thetable object Drawing in a Table Window You can draw numbers into in a tableediting window with the Pencil tool or usethe Straight Line tool which automatically draws a straight line between the points where you click show crosshair to aid precision drawing select a region to cut copy clear or paste drag the display to see another part ofthe table draw in values freehand with the mouse draw values in a straight line from click to click zoom the horizontal display in or out zoom the vertical display in or out You can select a region of values with the Selection tool cut or copy thevalues then select another region and paste the first region in its place You can even copy numbers from a Text window or from any word processingapplication then pastethem into thegraphictablewindowin aregion specified with the Sdection tool e Doubleclick on thetable object at the bottom of Patch 1 and draw anew melodic curve then listen to it by turning on the metro Other Ways to Alter a table Thetable object can understand a number of mess
460. u format sysex messages called sxformat T hesxformat object lets you specify some bytes of a M I DI message as arguments and other bytes as changeable arguments to be replaced by numbers received in theinlet s The format of changeable arguments in an sxformat object is different from that of changeable arguments in a message object Changeable arguments in sxformat e contain theletter i to indicate that they are integer arguments asin i1 e are preceded by the word is e arebounded on either side by a slash For example the changeable argument is i2 will be replaced by thenumber received in the sec ond inlet or the second number in alist received in the left inlet Calculations can even be performed on incoming numbers using the changeable argument For example thechangeableargument is il 1 adds1 to thenumber received in theleft inlet before sending it out When sxformat receives a number or alist in its left inlet it uses the number s to replace any changeable arguments then sends each of the arguments out the outlet in sequential order exformat 240 67 1643 is il 13 247 sends out 240 67 16 4 3 7 247 Programmers often express bytes of a sysex message in hexadecimal format rather than decimal If you prefer to type hexadecimal numbers you can do so in M ax by preceding the hexadecimal number with 0x zero x H ereisan exampleof thesamesysex message expressed in hexadecimal suformat O
461. u will see that it has an optional setting called T oggleM ode W hen aubutton isin T oggleM ode thefirst bang or mouseclick it receives highlights it and sends bang out its right outlet The next bang or mouse click unhigh lights it and sends bang out the left outlet T his makes it very versatile as an on off switch and an on off indicator W hen the display monitor is black and white ubutton reverses the color of what ever pictureis underneath it W hen the monitor is color ubutton reverses only the black or white portions of thepicture For this application we chose to use solid dark colors rather than light colors or gradients so that they would work well on any monitor W ealso chosefour different basiccolors onefor each of the four tracks so that the color scheme plays a functional role as well as a decorative one haping the eye separate the windows Another issuethat involves color versus black and white is the use of anti aliasing for text and graphics Anti aliased text which you can producein most painting programs looks much better onscreen than plain text but on ablack and white monitor it can look very jagged and unattrac tive Therefore in most cases it s wise to choose a font size and style that is clearly legible without anti aliasing especially when the text is small Of course the majority of people using this ver sion of M ax havea color monitor so you might decide to design the look of your program with 222 T
462. ubutton can also beused to highlight aspot on thescreen Look under ubutton in theM ax ReferenceM anual for details Theconnections between theubutton objects and thetoggle arehidden from sight with the H ide On Lock command ORL Coloring and Resizing Objects In addition to adding color to your patches by pasting in pictures you can set certain user inter face objects to acolor other than gray by selecting them and choosing acolor from theColor sub menu of the O bject menu Objects that can be colored in this way include button dial hslider rslider and uslider T hecolor of theled object is set by selecting it and choosing Get Info from theO bject menu If you haveselected an object that cannot be colored the Color submenu will bedisabled in theO bject menu 69 Tutori al 19 Screen aesthetics You can color thetop and bottom edges of an object box by using the Color submenu of the Object menu twist_it M any objects allow you to changetheir colors with RGB values thisisnormally doneusingthe object s Inspector window These patchers are opened when you choose Get I nfo from the Object menu with a single object selected Thesizeof objects can be altered by dragging on thegrow bar in the bottom right corner of the object Thislets you customizethe look of the graphical objectsin your M ax patches KOS EEE Different objects resized to bethesamesizeand shape Summary TheSegmentedPatchCordsoption le
463. ues bendout Transmit M IDI pitch bend messages ctlin Output incoming M IDI control values ctlout Transmit M IDI control messages pgmin Output incomingM IDI program change values pgmout Transmit M IDI program change messages speedlim Limit the speed with which numbers can pass through 59 Tutorial 17 Gatesand Switches Ggate In Tutorial 15 we saw examples of how to use comparisons to makea decision whether to send a message It is also possible for objects to make decisions about where to send a message Thepatch in theupper left corner showsagraphical object Ggate for routingincoming messages out one outlet or the other M essages received in the right inlet are sent out whichever outlet is pointed at by the arrow The direction of the arrow can be changed by clicking on Ggate with the mouse sending a bang to the left inlet or sending azero or non zero number to the left inlet When thenumber in the left inlet is 0 the arrow points to the left outlet A non zero number in the left inlet causes the arrow to point to theright outlet In the example above thetoggle has sent thenumber 1 to the left inlet of Ggate causingthearrow to pointto theright outlet Consequently any message received in the right inlet is passed out the right outlet e Try thevarious methods of changing the direction of the arrow then drag on thenumber box to send numbers to the right inlet of Ggate Gswitch Thesecond patch shows asimilar object Gswi
464. umbers received in theleft inlet go through Then thestart message sent to detonate causes it to report the first delta time which comesin the left inlet of p output and passes through the gate The number goes to therright inlet of delay and is used as the delay time before banging a next message to detonate to trigger the event information for thefirst note As detonate sends out event information in response to the next message it also sends out the delta time of thenext note event so the process continues until detonate is stopped or runs out of notes Theother items of event information that comefrom detonate are pitch note on velocity dura tion and channel Using makenote to supply note off messages seems reasonable but in this case doing so would unfortunately separate the channel information from the pitch and velocity mak ingit possible that note offs could betransmitted on the wrong channel if for example a note message on channel 2 occurs just before the note off for anoteon channel 1 This is an imperfect solution because channel information will mot he supplied with the mote otf Thessage Crom makenote Therefore it s preferable to create note off messages by using a pipe object to delay the pitch and channel information together which will send thosevaluesout with avelocity of 0 after waiting for 215 Tutorial 44 Sequencing with detonate thenumber of milliseconds specified by the duration value So in this
465. umbers to those stored in its recorded sequence If an incoming number matches the next number in the recorded sequence or a nearby number just in case the live performer makes a mistake follow reports the index of the matched note Theindex can then be used to read other numbers from atable or coll providing an accompaniment to the live performer or can beused to trigger any other process mtr The mtr object isa multi track sequencer that can record up to 32 individual tracks of numbers lists of numbers or symbols With such versatility it is easy to record not only MIDI events buta wide variety of other messages Tracks can berecorded played or stepped through using thenext message either individually or collectively and sometracks can be muted while other tracks con 359 Recording and playing back Seq uenc ng M IDI performances tinueto play Thecontents of mtr can bewritten to and read in from separate files either as indi vidual tracks or as an entire set of tracks record 1 a Bend on Mowse up only gt Record each track separately then play all tracks back together motet a i Sample patch using mtr For editingcompleteM ID messagesas text seq is perhapsmoreappropriatesinceitarranges raw M IDI datainto a standard M IDI fileformat However raw M IDI data can be filtered with midi parse before being sent to mtr Also a sequence recorded in seq can easily be cut out and pasted into an
466. umentation makesit morelikely that others will understand your patch and beableto useit and also helps to remind you how your patch works N ote If your comments are extensive and you want to include carriagereturnsin your comment text usethe Inspector to set two byte compatibility modefor the comment box Summary Any patch you create and save can beused as an object in another patch When you aremakinga patch that will be used as asubpatch in another patch you will usually want to includeinlet and outlet objects or send and receive objects so that you can send messagesto your object and it can send messages out Thefunbuff object stores an array of numbers x y pairs of addresses and values W hen an address number x isreceived in theleft inlet thevaluestored at that address y issent out the left outlet Thistypeof array is useful asalookup table for storing valuesin an indexed listand lookingthem up later Oneuseof arraysisto pair note on pitches with their transposition so that thetransposi tion can belooked up again when the corresponding note off is played Thewindow of asubpatch object that is saved as aseparate fileis not opened automatically when thePatcher windowthatcontainsitisopened unlikethepatcher object A patch that was saved as afileand used asa subpatch object can be edited only by opening thefilein which itis saved 104 Tutorial 27 Your object Explanatory notesin theform of comment boxesand A ssistancemessag
467. uresfrom other applicationssuch as paintingand drawing programs Cutor Copythe picturefrom another application then in M ax choose Paste Picture from theEdit menu to paste the pictureinto a Patcher window For example thedecorativeborder around thedial in this patch is actually just a frame drawn ina painting program Thedial was then placed on top of theframeto givetheillusion of a different kind of dial dial frame decorated dial Similarly thetwo buttons marked OFF and ON arenot actual M ax objects T hey are pictures that were drawn in another program and pasted in with the Paste Picture command The M ax icon was placed in the Patcher window by a different method it is contained inside an fpic object If you havedesigned a picture and saved it as a graphics file fpic can load that external fileinto memory when the patch is opened fpic After you place the fpic object in the Patcher window whileit is still selected chooseGet I nfo from the O bject menu T hefpic Inspector will appear Click theChoose button and a standard open file dialog appears After you choose the desired graphics file you can resize the fpic to dis play as much or as little of the pictureas you want W hen you savethepatch fpicsaves areferenceto the graphicsfileso that can will load that picture automatically thenexttimethe patch isopened W ith thismethod thegraphic isnot saved aspart of the patch If you are using the same graphic in several
468. used to store resources for external objects If you only see oneor two of these errors it may bea resource missing in the object or a conflict between two or more objects attempting to usethesamelD number If XXXX isSTR this problem only affects the strings shown when getting assistance on an object and should not be considered a major problen rescopy failed to get lt resource type gt lt ID number gt Occurs when installing an external object The external object fileis corrupted Restoreanew copy of the external object from your original disk script lt keyword gt variable lt variablename gt empty Occurswhen ascript message to thethispatcher object references a variablethat isno longer assigned to an object script lt keyword gt no variable lt variablename gt Occurswhen ascript message to thethispatcher object references a variable that has not yet been defined or given avalue script instance lt number gt of lt objectname gt not found Occurs when using thenth script message to thethispatcher object and the specified index is greater than thenumber of objects of the specified classin the patcher script name lt variablename gt already in use Occurswhen ascript message to thethispatcher object attempts to assign an object to a variable namethat is already been used Thiserror will not occur if you chooseN ame window from the Object menu to assign anameto an object 398 Erro rS Explanation oferror messages
469. ut of notein before the pitch does they arrive at noteout before the pitch does keeping all thedata properly synchronized Receiving On One Channel A notein object with no arguments or with only aletter argument receives incoming note mes sages on all channels This is known asomni modein M IDI terminology You can set notein to receive on only onechannel by typing in a channel number argument W hen thereis a channa 4 Tutorial 1 Sending and receiving M IDI notes argument notein has only two outlets for pitch and velocity becausethe channel number is already known Both the port argument and the channel argument are optional e If your MIDI keyboard can transmit on different channels set it to transmit on somechannel other than 1 Now when you play notes thenotein on the left still receives them but thenotein on therightignoresthem Transmitting Note Messages You don t necessarily need to play notesinto M ax to send notes out You can transmit notes to the synth that are produced within M ax Oneway to do thisis to send alist consisting of pitch velocity and channel to theleft inlet of noteout You may remember this use of lists with the arithmetic operator objects in Tutorial 8 e Click on the message boxes containing lists One list sends anote on and the other sends a note off anotewith a velocity of 0 Itis necessary or at least polite to follow anote on with anote off otherwisethenotewill continueto
470. utorial 21 StoringN umbers Variables In traditional programminglanguages variablesare placesin memory used by a program to store numbers so they can berecalled at a later time M any objectsin M ax arecapableof storing a number and recalling it later For example thenum ber box will send out thenumber stored in it when it receives a bang message In thistutorial we ll use objects that do nothing but storeanumber and send it out when abang is received in theleft inlet These objects areint for storing integer numbers and float for storing decimal numbers int and float W hen anumber is received in the left inlet of an int or afloat object itis stored and sent out the outlet Whenever abang is received in the left inlet the stored number is sent out again 1 Z 3 4 the number is shored bang causes the stored the num ber is shored bhang causes the stored and if also sent out number to be sent out but nothing is sent out Dumber to be sent out W hen anumber is received in theright inlet itis stored without triggering any output replacing the previously stored value Theint and float objects both function in exactly the sameway Theonly difference is the type of number they store W hen anumber with a decimal point float is received by an int object the number is converted to an int before being stored and vice versa An initial valueto be stored in int or float can be typed in as an argument If thereisno argument the o
471. utorial 45 D esigning the user interface color usersin mind and accommodate people with black and white monitors to whatever extent you see fit TRACK A TRACK A Anti aliased text looks better on a greyscale or color monitor than on a black and white monitor Combining Max Objects and Graphics Once you have decided what objects you want to show to the user and have laid them out the way you want them you can copy them from your M ax patch paste them into a drawing or painting program and then draw around them to makea picturethat seems to includethe M ax objects If your graphics program supports multiple layers as does Adobe Photoshop for instance you can put the M ax objects in a separate layer from the rest of your picture Once your picture isthe way you wantit delete the M ax objects from the picture copy the rest and pasteit into your M ax patch It will fit perfectly with the original M ax objects that you copied in the first place T he track windows and the keyboard window of this application were done this way Mod PB inst O TU Thispicturewaspainted around someM ax objects leaving perfectly sized holesfor them in M ax Window Size and Placement You can open and closethe window of asubpatch automatically with thepcontrol object and you can open close move resize and alter the appearance of a subpatch window with thispatcher A thispatcher object sends messagesto thePatcher that containsit Eac
472. utorial example has already been arranged and saved in a file named tutorial41 ti You can make changes to the timeline by bringing the graphic editor window to the foreground For example you can changethevolume graph in the ntro section just by clicking and draggingon thecontrol pointsin thegraph or by clicking whereno control point existsto createa new one e Double click on theetable editor of pitches in the Intro section You will be presented with a table editing window and you can changethe values in the pitch table Notice that the table editing window has a title intropitches T hat s because this particular etable has been linked to thetable intropitches object in the action patch W hen you create an etable or efunc event editor in atimelinetrack you can link it to an existing table object or funbuff object in thecase of efunc by selecting it choosingtheGet nfo command from theO bject menu and typing in thenameof the object as the Table Label for your editor From then on any changes you make in the etable will affect thetable object to which it is linked and vice versa 191 Tutorial 41 TimdineofM axmessages To place new events in a timeline track you hold down theO ption key on M acintosh or theAlt key on Windows and click on the mousein the event portion of the track at the point where you want to place the event You will be presented with a pop up menu of all the possible events you can place in that track b
473. utton so that any external objects used in the patch would be included in the collective Likewise thetimeline fileM ultiTrack ti should beincluded The action patches used by thetimeline object will beincluded automatically read MultiTrack ti Poontroal If you havean entire folder of data files you want to include you can includeall the files by clicking thel nclud older button and selectingthefolder from theensuingdialogbox N ote that this will only includefilesin thefolder itself folders insidethefolder you select will not be included 3 Onceyou have created a collective you cannot easily make changes to it So before you actu ally click on theBuildbutton to construct your collective you may wantto saveyour scriptasa separate Text file by clicking on the Save Script button T hat way if you later make changes to some of the patches or files in your collective and therefore need to rebuild or modify the collective you can simply open theoriginal script by clickingon theO pen Script button and you ll havea head start toward rebuilding your collective 329 Groupingfilestocreate Col ect Ives a single application 4 Onceyouhaveadded all thetop level patches you want they appear with an open instruction in thescript and have included all necessary files and or folders they appear as include and folderinstructionsin thescript your collectiveiscomplete Click on theBuildbutton and give your collectivea unique name
474. values stored in the object N ote Theuseof theprepend object with set argumentin pattr connectionsisto prevent thetrig gering of MIDI events when werecall the pattr object s state U nlikemost M ax objects pattr objects can be connected to other objects that are directly connected to them in turn without causing astack overflow 298 Tutorial 5 Patcher storage Automatic Binding e In thesamesubpatch try to connect an hslider object to the middleinlet of one of thepattr objects labeled mod_a mod_b mod_c or mod_d TheM ax window should print an error message and the program should prevent you from making the connection The middle outlet of pattr allows for the automatic binding of thepattr to asingleobject in the same patcher T henumber box objects controlling the objects are communicating with their respectivepattr objects just as if we had named them and bound thepattr objects to them manu ally e Look atthe names for the number box objects by selectingN ame from the O bject menu The bindto middle outlet of pattr objects automatically gives thereferring object anameif it doesn thaveonealready Thenameisbased on theclass of object attached and multipleobjects of thesameclassin apatch will begiven incrementing notation to uniquely identify them e g num ber number 1 numbe 2 etc e Back in themain patch open the durs subpatch of the main patch by double clic
475. var x 0 66 Thekeywords inlets and outlets tell M ax how many of each we ll need our js object to have Unlikemost other changeswemaketo our JavaScript code if you changethenumber of inletsand outlets you will need to manually recreate thejs object in order for it to reflect those changes You can do this by closing and reopening the M ax patch containing thejs object or by retyping the object box The var keyword tells avaScript thatthe label followingitisto bedeclared as avariable which we then assign to any valueeither in thedeclaration itself aswedo here by saying that x equals 0 66 or later on in the code Our new variable x isglobal in scope we ll investigate exactly what that means later on In order to make changesin our JavaScript code permanent weneed to savethe codein thetext editor W hen you savechanges by selecting Savefrom the Filemenu with thetext editor in the front M ax will tell you that it has updated thejs object and will report any problemsit may have had with your code e Typethefollowinglineunderneath the outlets 1 statement in the code post Hi There e Savethecodein thetext editor The M ax window should have printed the following js Compiling Functions and Executing Global Code Hi There Thefirst messagetells usthat thejs object hasreloaded our changed JavaScriptcode Thesecond lineshows theoutput from thepost statement weputin Thepost statement p
476. velocity pairs when arguments aretyped in to indicatehow many numbers areto be delayed Thedelay timeis specified in milliseconds by a number received in the right inlet or typed in as an argument Delays can be used to create echo effects or rhythms Each timetherandom object receives abang in its left inlet it generates a random number between 0 and onelessthan its argument and sends thenumber outits outlet See Also delay D elay abang before passing it on pipe Delay numbersor lists random Output a random number 86 Tutorial 23 Test4 Imitatinga Performance Creating Imitation In previous chapters you haveseen how to transposenotes played on your MIDI keyboard and how to delay notes Try making a patch of your own that imitates what you play starting on adif ferent note 1 M akea patch that imitates whatever you play 3 seconds after you play it transposed up a per fect fifth and also imitates whatever you play 6 seconds later transposed up an octave Hints Thenotes you play on your keyboard will haveto be sent to two different places In one the pitch will betransposed up by 7 semitonesand all thenote data will be delayed by 3000 milliseconds In the other the pitch will be transposed up by 12 semitones and thenotedata will all bedelayed by 6000 milliseconds Each imitation should useonepipe object to delay velocity and pitch data together e Pageonceto therightin the Patcher window to seethesolution to the
477. verse 119 linear mapping of ranges 116 list combining numbers into 121 166 convert to aseries of numbers 120 convert to separate numbers 120 Index in left inlet 27 loadbang 184 disable defeating 278 suppressing 230 loading apatch 281 locking and unlocking aPatcher window 8 loop 284 looping 84 loopingin atimeline 313 M main patch 279 makenote 45 M aking decisions with comparisons 54 M anaging messages 96 M anaging note data 45 M anagingraw MIDI data 143 mapping arangeof numbers 116 marker in atimelinetrack 313 M ax Preferences 277 M ax messages to 327 M axM SP Runtimeapplication 271 memory usage 283 menu bar changing 229 hiding and showing 328 menu object 168 290 Label mode 209 menubar 229 message append arguments at the end of 97 prepend onebeforeanother 97 reversing order of two numbers 121 tracing 337 viewing 332 335 message box 96 messagelookup 281 message object 8 96 asa data structure 289 changeable argument 291 punctuation in 295 message type 281 messenger 189 305 metro 16 MIDI connecting MIDI equipment 5 port specifying 143 MIDI channel filtering by 146 283 specifying 43 MIDI devicelist 226 231 MIDI Enable Disable 185 MIDI file 153 300 317 MIDI notename displaying 35 MIDI objects 41 midiformat 145 midiin 143 midiout 143 midiparse 144 modular programming 279 modulo 25 monitor monochrome 202 Monk Thelonius effect 112 M oreM IDI insand outs 59 M ousecontrol 180 mouse control 49
478. very 467 milliseconds 467 milliseconds 4 second 14 frames at 30fps Setting theimovie object s time location with a number whilethe movieis playing as is donehere causes the movie to continue playing from that point Thecontrol messages aresent to imovie via asend and receive pair Ther toimovie object ishidden in themain patch Drawing with the lcd Object In Tutorial 42 you learned how to draw colored shapes with spritesin a graphics window Thelcd Object lets you paint shapes lines and text in aPatcher window not with sprites but with com mands The principles of specifying the colors and coordinates of the shapes are very similar in these two cases e Closethesubpatch window playmovie and double click on the patcher concentrics object to see its contents Play the low C on your keyboard key 36 once to set the concentrics sub patch into action Thenote toggles a metro which increments a counter cycling from 0 to 100 about every two sec onds Thenumbers from the counter are used to calculatethe color and coordinates of concentric circles to be painted with the PaintOval message to Icd Let s examine how to calculate the coordinates for these concentric circles which are precisely cen tered within thelcd This particular Icd object has been sized to be 160 pixels wide by 120 pixels high A little trigonometry reveals to us that the distance from the center of this Icd to one of its corners is equivalent to 100 pixels so
479. w you can seeiter at work W hen themetro triggers the list of numbers it is sent to iter which breaks up thelist and sends each of the numbers on in order as rapidly as possible The numbers are delayed by thepipe then aresent on as virtually simulta neous pitches to makenote unpack W hen alist isreceived by unpack each element of thelistissent out adifferent outlet Thenumber of outletsunpack hasis determined by thenumber of arguments you typein T hearguments also Set an initial value for each outlet If there areno typed in arguments unpack has two outlets both with an initial value of 0 115 Tutorial 30 Number groups If therearemoreitemsin theincoming list than unpack hasoutletsfor theextraitemsareignored If alist is received that has fewer items than there are outlets unpack sends those items out the appropriate outlets but sends nothing out the remaining outlets In the example patch when a list is received by unpack the second item in thelist is sent out the right outlet then the first item in the list is sent out the left outlet output order is always right to left pack The pack object combines separate items into alist It stores the message most recently received in each of its inlets then when it receives a messagein the left inlet it sends out all the stored items together as alist Thenumber of inlets and theinitial value stored in each one is specified by thetyped in arguments pack 0
480. wheel controller 7 to vol ume etc Therefore in addition to port and channel arguments ctlin and ctlout can be given a specific con troller number as an argument immediately after the port argument if present When a specific controller number is given as an argument to ctlin the controller number outlet disappears For more about the arguments and their default values look under ctlin and ctlout in the M ax Refer enceM anual controller controller channel controller channel wih ber Liber number port number number ctlin 1 16 ctlin a 1 16 control controller channel control channel control control data wm ber wmber data number daka data 57 Tutorial 16 MoreM IDI insand outs Reassigning Control Data You can usea continuous M IDI controller to send a stream of numbers to M ax then use those numbers in any way you like In this patch the data from the mod wheel of the synth is used to send pitch values back to the synth controller num her and channel cthlin ail 1 control data mo more than 4 Lotes per second e Movethemodulation wheel on your M IDI keyboard and you should hear notes play Thespeedlim object limits the speed with which numbers can passthrough it W hen speedlim receivesanumber itsendsthenumber outthe outlet then waits acertain number of milliseconds before it will receive another number The number of milliseconds between numbers can bea typed in argument and or supplied in the right inlet
481. when a number is being sent In addition apatcher object called view receives the bang messages from the button object and creates a scrolling visual feedback of the generated rhythm with a multislider object N otethat thespecific timing of thefour objects as well as what pitches they generate are different these are determined by the arguments to thejs objects moreon this later lt Dw on visualizer A E Z The avaScript code used in thejs objects isa simple mock up of an exponentially decaying tim ing function analogousto a rubber ball being dropped onto a hard floor N otes are sent at an exponentially increasing rate until the speed at which they are sending exceeds a threshold value five milliseconds in the case of our script U pon exceeding that threshold thefunction stops and abang issent out of theright outlet of our js objects to notify that the timing function has ceased Theuse of a done bang isa common convention among M ax objects to signify the com pletion of atask c f line uzi coll etc Click on thetoggle labeled repeat and click thetop button again N otice that the cycle of bouncingnotesrepeats asthebang from thejs objects causethem to retrigger themselves T he differencein thetiming acceleration of the four js objects will causethem to phaseover multi pleiterations of the cycle notehow thisis displayed in the multislider If you click thetoggle again the current cycle of bounces will c
482. when its output is sent to acounter Produce an S second volume fade in then stop the metro 345 Lo 0 DS W aysto perform repeated operations Stack Overflow Automatic timed repetitions must be separated by at least a millisecond or two otherwiseM ax will generate a Stack Overflow which stops M ax sinternal scheduler until you shut off the repeti tions Beow areacoupleof examples of what not to do because you will causea stack overflow Kids don t try this yourselves There may look like good ways to send out mm bers as East as possible but they will resul in stack overflow These programs contain bugs Thepatchesin thisexampleattemptto increment acount asfast as possible Each solution hastwo flaws however T hefirst problem is that thereisno stopping condition thenumberswill increase indefinitely Thesecond problem isthat each patch feeds an object soutputback into itstriggering inlet with no timedelay M ax keepstryingto do moreand morethings without being given any moretimein which to do them and quickly complains that its to do stack is overflowing Instantaneous Loops W hen you want to usealoop that completes all its repetitions as fast as possible thatis you want to send out a series of events at thesametime you must use an object that is designed to send out multiple messages The message box can contain multiple messages separated by commas and sendsthem all out in immediate
483. with names are immediately followed by alinestarting with objectname T hisisagood way to determineexactly which object definition string you want to grab when you arelooking at complicated M ax text files In this example wehavefour named objects num_bottom num_topright num_topleft and mybpatcher Theobject definition string of bpatcher looks like this bpatcher lt horizontal pos gt lt vertical pos gt lt width gt lt height gt lt h offset gt lt v offset gt lt patchname gt lt border on off 1 0 gt lt argument 1 gt lt argument N gt 241 Tutorial 4 Advanced scripting W hen wecreate a new bpatcher object that contains a different patcher we ll leave everything the same except for thename Our script sequence goes like this 1 script delete mybpatcher 2 script new mybpatcher bpatcher 8 71 105 90 0 0 bpatch2 1 3 script connect num_topleft 0 mybpatcher 0 4 script connect num_topright 0 mybpatcher 1 5 script connect mybpatcher 0 num_ bottom 0 script delete mybpatcher script new myrbpatcher bpatcher B71 105 90 0 0 bpatch 1 script connect num_toplerft 0 mybpatehber script connect num topright 0 mybpatcher 1 script connect mybpatcher 0 nom_bottam thispatcher A replaced and repatched bpatcher Where to Put a Script Astheabove example makes clear even simple scripts can becomerather long M anaging your script text can beas challenging as writing it If you find yourself rout
484. wn to 31 As you play higher on the keyboard thenumbers being sent to mak enote become lower and vice versa Theinverted pitches are paired with thereduced velocity in makenote and thenotes aresent out then areturned off after 100 milliseconds 1 4 of a second Summary Thehslider and uslider objects are similar to slider but can be made any size kslider isa keyboard likeslider theR angeof which is specified asa number of octaves You can perform both chromatic glissandi and diatonic glissandi white keys only on kslider Thedial hslider and uslider objects all limit the numbers they receive in their inlet Numbers that exceed the range of these sliders are set to the minimum or maximum value of the slider Unlike Slider these other sliders respond to asingle mouse click without dragging 49 Tutorial 14 Slidersand dials Theabs object sends outthe absolutevalueof whatever number it receivesin itsinlet Thelimiting sliders and abs represent two different ways to avoid negative numbers O ther objects that can serve this purposearemaximum and split See Also abs Output the absolute value of theinput dial Output numbers by moving adial onscreen hslider Output numbers by moving aslider onscreen kslider Output numbers from a keyboard onscreen split Look for arangeof numbers uslider Output numbers by moving aslider onscreen 50 Tutorial 15 M akingD ecisionswith Comparisons Relational Operators Oneof the most basic
485. x can look atits contents and to try to determine what kind of file format it might be W erefer to thisas sniffing the file On Macintosh M ax classifiesfilesfirst by checking their M acOS specific filetypeinformation In the absence of such information M ax looksat thefile s extension If neither of these are definitive it will sniff the fileto try to determineits format Cross platform Filename Extensions Thefollowing filename extensions are recognized on both M acintosh and W indows Extension Description pat M ax patch file in either M ax binary or text format file help M ax help file in either M ax binary or text format file txt Generic text file M ax patcher in text form or other M ax text file mxb M ax binary patcher format mxt M ax text format patcher file mxf Cross platform M ax collectiveformat 310 FI les H ow M ax handles Search Paths and Files Windows only Filename Extensions The following filename extension is recognized on Windows only Extension Description mxe W indows only external object Macintosh only Filename Extensions The following filename extensions are recognized on M acintosh Extension Description mxd M acintosh only external object MXC Old format pre version 4 3 M acintosh only collective Mapping Filename Extensions to File Types A filetype or fileformat isadescription of how information in afileisarranged For example dif ferent audio fileformats such asW
486. xFO 0x43 0x10 0x4 0x3 is fii 8 OxD oOxF sends out 240 67 16 4 3 7 247 An Example Sysex Message The status beginning byte of any sysex message is always 240 T he second byte is the M anufac turer 1D each major synthesizer manufacturer has a unique number assigned to the brand name Thenext bytes are established by themanufacturer asmany as areneeded to express whatever is being expressed A sysex message always ends with the end of sysex message byte 247 143 Tutorial 34 M anaging raw M IDI data W hen a synthesizer receives the sysex status byte 240 it looks at the second byte If the second byteisthe D of some other manufacturer the synth ignores all the subsequent bytes until it sees 247 Then it begins to pay attention to incoming M IDI messages again In the bottom right corner of the Patcher window isan example of the use of sxformat It is designed to changethe effective pitch bend range on aYamahaD X7 synthesizer or TX sound module The first argument is the sysex status byte 240 and the second argument isthe M anu facturer ID for Yamaha 67 Yamaha decided that thenext byte would tell the synth what kind of message it s going to receive in this case 16 means parameter changeon channad 1 Thefourth byte specifies that the sysex message is a performance parameter change The next byte is the parameter number 3 is for pitch bend range SoTL tones suformat 240 67 16 4 3 fais il 13 2
487. xample destroys everything weworked so hard to create above counter 0 14 sprintf script delete Kimynumbax sprintf script delete Kircy thispatcher D eleting objects Summary Scripting is performed by sending messages beginning with the word script to thethispatcher object O bjects must be given namesin order to bescriptable You can perform anumber of tasks with scripting including creating objects connecting them together sending messages and finally disconnecting and deleting them In thenext Tutorial we ll exploresomemoreadvanced uses of scripting including replacing objects moving them around and hiding them 239 Tutorial 47 A dvanced Scripting Replacing replace Scripting allows you to replace objects in patches To do this you first delete an object then create anew object in its place and makeall of theappropriateconnectionsto and from thenew object This feature is particularly useful when you need to replace subpatchers and bpatcher objects within apatch where you need apart of thepatch to usean algorithm that can vary asort of plug in The previous method for replacing bpatcher objects dynamically using areplace mes sage to athispatcher object inside of abpatcher has been replaced with scriptingin M ax 4 and offers thefollowingimprovements e Control is assigned to thetop level of the patch instead of depending on a mechanism inter nal to apatch contained in the bpatcher
488. y from the palette or patcher contextual menu This simplifies scripting sub stantially over using messages to thethispatcher object If you wish to specify all the object param eters object width flags etc you can usethenewob ject method instead Connections aremade by taking two M axobjs and linking them using the connect method to aPatcher object e g this patcher connect thesliders 5 0 thefunnel 5 will connect the leftmost 0 outlet of thesixth M axobj in the array thesliders to the sixth inlet of theM axobject thefunna Remember that numbering starts at 0 for both arrays and inlet outlet numbers W euseiteration and arrays to create multiple objects at once for example for k 0 k lt 8 k controlin k this patcher newdefault 300 k 50 50 ctlin k 1 thesliders k this patcher newdefault 300 k 50 100 uslider this patcher connect controlin k 0 thesliders k 0 this patcher connect thesliders k 0 thefunnel k w 266 Tutorial 49 Advanced scripting will automatically generate8 ctlin and uslider objectsspaced 50 pixelsapart on thepatcher window starting at horizontal coordinate 300 connect them to oneanother and then connect them to thefunnel object referenced by thefunnd N ote that the variablek in our JavaScript codeis never declared since weonly useit as alocal variable in the sliders function and reinitializeit every timethat function is called In our ac
489. y step The object allows you to automatically name objects for inclusion through the autoname attribute as well as explicitly include or exclude objects through the first two outlets respectively Thepattrstorage object allows you to view the current settings of pattr exposed objects as well as save states of set 306 Tuto ri q 53 M ore patcher storage tingsinto numerical slots through thesave message and recall them by sending an integer to the object Furthermore you can interpolate between preset slots as well as save and recall your saved states in an easy to read XM L format See Also autopattr freeing pattr users from the burdens of thought pattr patcher specific named data wrapper pattrhub make your pattrobjects work for you pattrstorage view modify pattr data storeand recall presets patcher Create asubpatch within a patch preset Store and recall the settings of other objects Icd Draw graphicsin a Patcher window 307 Files H ow M axhandlesSearch Pathsand Files When Max Looks fora File M ax may look for afile at several different times H ere are some examples e When you open apatcher that containsan external objectthat hasnot been used yet M ax will search for thefilethat corresponds to that object e When you open apatcher that containsasubpatcher that isafile i e it doesn t begin with the word patcher or p M ax will search for the patcher e When you send themessage read with
490. you want the sequence to be played back The start argument divided by 1024 determines the factor by which thetempo will beincreased or decreased So for example the message start 1024 indicates theoriginal recorded tempo themessagestart 1536 plays the sequenceback 1 5 times as fast start 512 plays it back half as fast and so on 147 Tutorial 35 seq and follow In theupper left corner of Patch 1 weve devised away to calculatethetenpo ratio letting you specify the tempo in terms of a multiplier with 1 being the normal tempo start tempo multiplier e Dragon thenumber box to choose a tempo multiplier You can change the fractional part of thenumber by dragging with the mouse positioned to the right of thedecimal point Then click on the button to play your sequence at the new tempo Changing the playback speed in this manner does not actually changethetimes recorded in the sequence it merely changes the speed at which seq reads through it Another message called hook notshown here altersthetimesin a sequence Look under seq in theM ax ReferenceM anual for details Saving and Recalling Files Ifyou like you can savethesequenceyou haverecorded in aseparatefile to beused later Thewrite message opens a standard SaveAs dialog box for you to name the file where you want to storethe sequence You may want to give the names of your sequence files some unique characteristic so you can distinguish them from Patcher files and Table f
491. ys 1 Select an object then choose N ame from the O bject menu The N ame O bject window will open 88 e Name Object Set Object Name for Text TheN ameO bject window By default M ax objects do not havenames so lt none gt will appear in the N ame Object win dow when you first open it for an object Type any non reserved term into the N ameO bject Inspector and you venamed the object reserved terms include bang int float and list and errors may result if you use these names O bjects must haveuniquenames within a patcher 228 Tutorial 46 Basic scripting M ax vill warn you that anameis already in useif you try to assign duplicatenamesto objects Sincethis restriction only appliesto objects within a Patcher window identically named objects inside duplicate subpatchers or bpatcher objects arenota problem 2 Createanew object with scripting If you create an object using scripting your new object is given anameas part of the act of creating it If the nameyou assign to an object is already in use thenewly created object takes the name away from the object that owns it 3 Two scripting commands permit you to assign names to objects based on certain criteria script class and script nth Please refer to the reference page for thethispatcher object for more details about these commands To check whether an object isnamed you can e Selecttheobject and chooseN ame from theO bject menu Iftheobjectisnamed
Download Pdf Manuals
Related Search
Related Contents
PowerSure™ PSP - Advanced Power Protection Industries Samsung Z368 黑色 User Manual SCALANCE S V4 Philips 20PT6431 CRT Television User Manual nVIDIA MCP61S Series_Ver1.0(User`s Manual) Agilent Technologies 4396B Network Card User Manual suit - Lochinvar DOSIFICADOR SERIE ECON FP Copyright © All rights reserved.
Failed to retrieve file