/[svn]/doc/docbase/instrument_scripts/nksp/01_nksp.html
ViewVC logotype

Contents of /doc/docbase/instrument_scripts/nksp/01_nksp.html

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3717 - (show annotations) (download) (as text)
Mon Jan 13 13:29:05 2020 UTC (17 months, 1 week ago) by schoenebeck
File MIME type: text/html
File size: 67029 byte(s)
NKSP language tour: Added real number scalar and real array types.

1 <html>
2 <head>
3 <meta name="author" content="Christian Schoenebeck">
4 <title>NKSP Language</title>
5 <meta name="description" content="Introduction to the NKSP real-time instrument script language.">
6 </head>
7 <body>
8 <p>
9 This document intends to give you a compact introduction and overview to
10 the NKSP real-time instrument script language, so you can start writing
11 your own instrument scripts in short time. It concentrates on describing
12 the script language. If you rather want to learn how to modify and
13 attach scripts to your sounds, then please refer to the gigedit manual for
14 <a href="gigedit_scripts.html">how to manage instrument scripts with gigedit</a>
15 for Gigasampler/GigaStudio format sounds, or refer to the SFZ opcode
16 <code lang="sfz">script</code> for attaching NKSP scripts with
17 SFZ format sounds.
18 </p>
19
20 <h3>At a Glance</h3>
21 <p>
22 <img src="nksp_file.png" style="height:111px; margin-right:12px;">
23 NKSP stands for "is <b>N</b>ot <b>KSP</b>", which denotes its distinction
24 to an existing proprietary language called <i>KSP</i>.
25 NSKP is a script language specifically designed to write real-time capable
26 software extensions to LinuxSampler's sampler engines that can be bundled
27 individually with sounds by sound designers themselves.
28
29 Instead of defining a completely new script language, NKSP is leaned on
30 that mentioned properiatary script language. The biggest advantage is that
31 sound designers and musicians can leverage the huge amount of existing KSP
32 scripts which are already available for various purposes on the Internet,
33 instead of being forced to write all scripts from scratch in a completely
34 different language.
35 </p>
36 <p>
37 That also means however that there are some differences between those two
38 languages. Some extensions have been added to the NKSP core language to
39 make it a bit more convenient and less error prone to write scripts, and
40 various new functions had to be added due to the large difference of the
41 sampler engines and their underlying sampler format. Efforts have been
42 made though to make NKSP as much compatible to KSP as possible.
43 The NKSP documentation will emphasize individual differences in
44 the two languages and function implementations wherever they may occur, to
45 give you immediate hints where you need to take care of regarding
46 compatibility issues when writing scripts that should be spawned on both
47 platforms.
48 </p>
49 <p>
50 Please note that the current focus of NKSP is the sound controlling aspect
51 of sounds. At this point there is no support for the graphical user
52 interface function set of KSP in NKSP.
53 </p>
54
55 <h2>Event Handlers</h2>
56 <p>
57 NKSP is an event-driven language. That means you are writing so called
58 <i>event handlers</i> which define what the sampler shall do on individual
59 events that occur, while using the sound the script was bundled with.
60 An event handler in general looks like this:
61 </p>
62 <code lang="nksp">
63 on ??event-name??
64
65 ??statements??
66
67 end on
68 </code>
69 <p>
70 There are currently six events available:
71 </p>
72 <table>
73 <tr>
74 <th>Event Type</th> <th>Description</th>
75 </tr>
76 <tr>
77 <td><code>on note</code></td> <td>This event handler is executed when a new note was triggered, i.e. when hitting a key on a MIDI keyboard.</td>
78 </tr>
79 <tr>
80 <td><code>on release</code></td> <td>This event handler is executed when a note was released, i.e. when releasing a key on a MIDI keyboard.</td>
81 </tr>
82 <tr>
83 <td><code>on controller</code></td> <td>This event handler is executed when a MIDI control change event occurred. For instance when turning the modulation wheel at a MIDI keyboard.</td>
84 </tr>
85 <tr>
86 <td><code>on rpn</code></td> <td>This event handler is executed when a MIDI <i>RPN</i> event occurred.</td>
87 </tr>
88 <tr>
89 <td><code>on nrpn</code></td> <td>This event handler is executed when a MIDI <i>NRPN</i> event occurred.</td>
90 </tr>
91 <tr>
92 <td><code>on init</code></td> <td>Executed only once, as very first event handler, right after the script had been loaded. This code block is usually used to initialize variables in your script with some initial, useful data.</td>
93 </tr>
94 </table>
95 <p>
96 You are free to decide for which ones of those event types you are going to
97 write an event handler for. You can write an event handler for only one
98 event type or write event handlers for all of those event types. Also
99 dependent on the respective event type, there are certain things you can
100 do and things which you can't do. But more on that later.
101 </p>
102
103 <h3>Note Events</h3>
104 <p>
105 As a first example, the following tiny script will print a message to your
106 terminal whenever you trigger a new note with your MIDI keyboard.
107 </p>
108 <code>
109 on note
110 message("A new note was triggered!")
111 end on
112 </code>
113 <p>
114 Probably you are also interested to see which note you triggered exactly.
115 The sampler provides you a so called
116 <i title="A script variable which is provided by the sampler and which has a very specific purpose which you cannot override for other purposes.">
117 built-in variable
118 </i>
119 called <code>$EVENT_NOTE</code> which reflects the note number
120 (as value between 0 and 127) of the note that has just been triggered. Additionally
121 the built-in variable <code>$EVENT_VELOCITY</code> provides you the
122 velocity value (also between 0 and 127) of the note event.
123 </p>
124 <code>
125 on note
126 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
127 end on
128 </code>
129 <p>
130 The <code>&</code> character concatenates text strings with each other.
131 In this case it is also automatically converting the note number into a
132 text string.
133 </p>
134 <note class="important">
135 The message() function is not appropriate for being used with your final
136 production sounds, since it can lead to audio dropouts.
137 You should only use the message() function to try out things, and to spot
138 and debug problems with your scripts.
139 </note>
140
141 <h3>Release Events</h3>
142 <p>
143 As counter part to the <code>note</code> event handler, there is also the
144 <code>release</code> event handler, which is executed when a note was
145 released. This event handler can be used similarly:
146 </p>
147 <code>
148 on release
149 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
150 end on
151 </code>
152 <p>
153 Please note that you can hardly find MIDI keyboards which support release
154 velocity. So with most keyboards this value will be 127.
155 </p>
156
157 <h3>Controller Events</h3>
158 <p>
159 Now let's extend the first script to not only show note-on and note-off
160 events, but also to show a message whenever
161 you use a MIDI controller (i.e. modulation wheel, sustain pedal, etc.).
162 </p>
163 <code>
164 on note
165 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
166 end on
167
168 on release
169 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
170 end on
171
172 on controller
173 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
174 end on
175 </code>
176 <p>
177 It looks very similar to the note event handlers. <code>$CC_NUM</code>
178 reflects the MIDI controller number of the MIDI controller that had been
179 changed and <code>%CC</code> is a so called <i>array variable</i>, which not only
180 contains a single number value, but instead it contains several values at
181 the same time. The built-in <code>%CC</code> array variable contains the current
182 controller values of all 127 MIDI controllers. So <code>%CC[1]</code> for
183 example would give you the current controller value of the modulation
184 wheel, and therefore <code>%CC[$CC_NUM]</code> reflects the new controller
185 value of the controller that just had been changed.
186 </p>
187 <p>
188 There is some special aspect you need to be aware about: in contrast to the MIDI standard,
189 monophonic aftertouch (a.k.a. channel pressure) and pitch bend wheel are
190 handled by NKSP as if they were regular MIDI controllers. So a value change
191 of one of those two triggers a regular <code>controller</code> event handler
192 to be executed. To obtain the current aftertouch value you can use
193 <code>%CC[$VCC_MONO_AT]</code>, and to get the current pitch bend wheel
194 value use <code>%CC[$VCC_PITCH_BEND]</code>.
195 </p>
196
197 <h3>RPN / NRPN Events</h3>
198 <p>
199 There are also dedicated event handlers for
200 MIDI <i title="Registered Parameter Number">RPN</i> and
201 <i title="Non-Registered Parameter Number">NRPN</i>
202 events:
203 </p>
204 <code>
205 on rpn
206 message("RPN address msb=" & msb($RPN_ADDRESS) & ",lsb=" & lsb($RPN_ADDRESS) &
207 "-> value msb=" & msb($RPN_VALUE) & ",lsb=" & lsb($RPN_VALUE))
208 if ($RPN_ADDRESS = 2)
209 message("Standard Coarse Tuning RPN received")
210 end if
211 end on
212
213 on nrpn
214 message("NRPN address msb=" & msb($RPN_ADDRESS) & ",lsb=" & lsb($RPN_ADDRESS) &
215 "-> value msb=" & msb($RPN_VALUE) & ",lsb=" & lsb($RPN_VALUE))
216 end on
217 </code>
218 <p>
219 Since MIDI RPN and NRPN events are actually MIDI controller events,
220 you might as well handle these with the previous
221 <code>controller</code> event handler. But since RPN and NRPN messages
222 are not just one MIDI message, but rather always handled by a set of
223 individual MIDI messages, and since the
224 precise set and sequence of actual MIDI commands sent varies between
225 vendors and even among individual of their products, it highly makes sense to
226 use these two specialized event handlers for these instead, because the
227 sampler will already relief you from that burden to deal with all those
228 low-level MIDI event processing issues and all their wrinkles involved
229 when handling RPNs and NRPNs.
230 </p>
231 <note>
232 Even though there are two separate, dedicated event handlers for RPN and NRPN events,
233 they both share the same built-in variable names as you can see in the
234 example above.
235 </note>
236 <p>
237 So by reading <code>$RPN_ADDRESS</code> you get the RPN / NRPN parameter
238 number that had been changed, and <code>$RPN_VALUE</code> represents the
239 new value of that RPN / NRPN parameter. Note that these two built-in
240 variables are a 14-bit representation of the parameter number and new
241 value. So their possible value range is <code>0 .. 16383</code>. If you
242 rather want to use their (in MIDI world) more common separated two 7 bit
243 values instead, then you can easily do that by wrapping them into either
244 <code>msb()</code> or <code>lsb()</code> calls like also demonstrated above.
245 </p>
246
247 <h3>Script Load Event</h3>
248 <p>
249 As the last one of the six event types available with NKSP, the following
250 is an example of an <code>init</code> event handler.
251 </p>
252 <code>
253 on init
254 message("This script has been loaded and is ready now!")
255 end on
256 </code>
257 <p>
258 You might think, that this is probably a very exotic event. Because in
259 fact, this "event" is only executed once for your script: exactly when
260 the script was loaded by the sampler. This is not an unimportant event
261 handler though. Because it is used to prepare your script for various
262 purposes. We will get more about that later.
263 </p>
264
265 <h2>Comments</h2>
266 <p>
267 Let's face it: software code is sometimes hard to read, especially when you
268 are not a professional software developer who deals with such kinds of
269 things every day. To make it more easy for you to understand, what you
270 had in mind when you wrote a certain script three years ago, and also if
271 some other developer might need to continue working on your scripts one
272 day, you should place as many comments into your scripts as possible. A
273 comment in NKSP is everything that is nested into an opening and closing
274 pair of curly braces.
275 </p>
276 <code>{ This is a comment. }</code>
277 <p>
278 You cannot only use this to leave some human readable explanations here
279 and there, you might also use such curly braces to quickly disable parts
280 of your scripts for a moment, i.e. when debugging certain things.
281 </p>
282 <code>
283 on init
284 { The following will be prompted to the terminal when the sampler loaded this script. }
285 message("My script loaded.")
286
287 { This code block is commented out, so these two messages will not be displayed }
288 {
289 message("Another text")
290 message("And another one")
291 }
292 end on
293 </code>
294
295 <h2>Variables</h2>
296 <p>
297 In order to be able to write more complex and more useful scripts, you
298 also need to remember some data somewhere for being able to use that
299 data at a later point. This can be done by using
300 <i title="A variable is a storage location paired with an associated symbolic name.">
301 variables
302 </i>.
303 We already came across some <i>built-in variables</i>, which are already
304 defined by the sampler for you. To store your own data you need to declare
305 your own <i>user variables</i>, which has the following form:
306 </p>
307 <p>
308 <code>declare $??variable-name?? := ??initial-value??
309 </p>
310 <p>
311 The left hand side's <code>??variable-name??</code> is an arbitrary name
312 you can chose for your variable. That name might consist of English
313 letters A to Z (lower and upper case), digits (<code>0</code> to <code>9</code>),
314 and the underscore character "<code>_</code>".
315 Variable names must be unique. So you can neither declare several variables
316 with the same name, nor can you use a name for your variable that is
317 already been reserved by <i>built-in variables</i>.
318 The right hand side's <code>??initial-value??</code> is simply the first
319 value the variable should store right after it was created. You can also
320 omit that.
321 </p>
322 <p>
323 <code>declare $??variable-name??
324 </p>
325 <p>
326 In that case the sampler will automatically assign <code>0</code> for you
327 as the variable's initial value. This way we could for example count the
328 total amount of notes triggered.
329 </p>
330 <code>
331 on init
332 declare $numberOfNotes := 0
333 end on
334
335 on note
336 $numberOfNotes := $numberOfNotes + 1
337
338 message("This is the " & $numberOfNotes & "th note triggered so far.")
339 end on
340 </code>
341 <p>
342 In the <code>init</code> event handler we create our own variable
343 <code>$numberOfNotes</code> and assign <code>0</code> to it as its
344 initial value. Like mentioned before, that initial assignment is optional.
345 In the <code>note</code> event handler we then increase the
346 <code>$numberOfNotes</code> variable by one, each time a new note was
347 triggered and then print a message to the terminal with the current total
348 amount of notes that have been triggered so far.
349 </p>
350 <note>
351 NKSP allows you to declare variables in all event handlers, however if
352 you want to keep compatibility with KSP, then you should only
353 declare variables in <code>init</code> event handlers.
354 </note>
355
356 <h3>Variable Types</h3>
357 <p>
358 There are currently five different variable types, which you can easily
359 recognize upon their first character.
360 </p>
361 <table>
362 <tr>
363 <th>Variable Form</th> <th>Data Type</th> <th>Description</th>
364 </tr>
365 <tr>
366 <td><code>$??variable-name??</code></td> <td>Integer Scalar</td> <td>Stores one single integer number value.</td>
367 </tr>
368 <tr>
369 <td><code>%??variable-name??</code></td> <td>Integer Array</td> <td>Stores a certain amount of integer number values.</td>
370 </tr>
371 <tr>
372 <td><code>~??variable-name??</code></td> <td>Real Number Scalar</td> <td>Stores one single real (floating point) number value.</td>
373 </tr>
374 <tr>
375 <td><code>???variable-name??</code></td> <td>Real Number Array</td> <td>Stores a certain amount of real (floating point) number values.</td>
376 </tr>
377 <tr>
378 <td><code>@??variable-name??</code></td> <td>String</td> <td>Stores one text string.</td>
379 </tr>
380 </table>
381 <p>
382 So the first character just before the actual variable name, always
383 denotes the data type of the variable. Also note that all variable types
384 share the same variable name space. That means you cannot declare a
385 variable with a name that has already been used to declare a variable of
386 another variable type.
387 </p>
388
389 <h3>Array Variables</h3>
390 <p>
391 We already used the first two variable types. However we have not seen yet
392 how to declare such array variables. This is the common declaration form
393 for creating your own array variables.
394 </p>
395 <code>
396 on init
397 declare %??variable-name??[??array-size??] := ( ??list-of-values?? )
398 end on
399 </code>
400 <p>
401 So let's say you wanted to create an array variable with the first 12
402 prime numbers, then it might look like this.
403 </p>
404 <code>
405 on init
406 declare %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
407 end on
408 </code>
409 <p>
410 Like with integer variables, assigning some initial values with
411 <code>??list-of-values??</code> is optional. The array
412 declaration form without initial value assignment looks like this.
413 </p>
414 <code>
415 on init
416 declare %??variable-name??[??array-size??]
417 end on
418 </code>
419 <p>
420 When you omit that initial assignment, then all numbers of that array will
421 automatically be initialized with <code>0</code> each. With array
422 variables however, it is always mandatory to provide
423 <code>??array-size??</code> with an array
424 variable declaration, so the sampler can create that array with the
425 requested amount of values when the script is loaded. In contrast to many
426 other programming languages, changing that amount of values of an array
427 variable is not possible after the variable had been declared. That's due
428 to the fact that this language is dedicated to real-time applications, and
429 changing the size of an array variable at runtime would harm real-time
430 stability of the sampler and thus could lead to audio dropouts. So NKSP
431 does not allow you to do that.
432 </p>
433
434
435 <h3>String Variables</h3>
436 <p>
437 You might also store text with variables. These are called <i>text string
438 variables</i>, or short: <i>string variables</i>. Let's skip the common declaration
439 form of string variables and let us modify a prior example to just use
440 such kind of variable.
441 </p>
442 <code>
443 on init
444 declare $numberOfNotes
445 declare @firstText := "This is the "
446 declare @secondText
447 end on
448
449 on note
450 $numberOfNotes := $numberOfNotes + 1
451 @secondText := "th note triggered so far."
452 message(@firstText & $numberOfNotes & @secondText)
453 end on
454 </code>
455 <p>
456 It behaves exactly like the prior example and shall just give you a
457 first idea how to declare and use string variables.
458 </p>
459 <note class="important">
460 Like with the message() function, you should not use string variables
461 with your final production sounds, since it can lead to audio dropouts.
462 You should only use string variables to try out things, and to spot
463 and debug problems with your scripts.
464 </note>
465
466 <h3>Variable Scope</h3>
467 <p>
468 By default, all variables you declare with NKSP are
469 <i title="A variable that is accessible throughout an entire script.">
470 global variables
471 </i>. That means every event handler can access the data of such a global
472 variable. Furthermore, each instance of an event handler accesses the same
473 data when it is referencing that variable. And the latter fact can be a
474 problem sometimes, which we will outline next.
475 </p>
476 <p>
477 Let's assume you wanted to write an instrument script that shall resemble
478 a simple delay effect. You could do that by writing a note event handler
479 that automatically triggers several new notes for each note being
480 triggered on a MIDI keyboard. The following example demonstrates how that
481 could be achieved.
482 </p>
483 <code>
484 on init
485 { The amount of notes to play }
486 declare const $delayNotes := 4
487 { Tempo with which the new notes will follow the orignal note }
488 declare const $bpm := 90
489 { Convert BPM to microseconds (duration between the notes) }
490 declare const $delayMicroSeconds := 60 * 1000000 / $bpm
491 { Just a working variable for being used with the while loop below }
492 declare $i
493 { For each successive note we trigger, we will reduce the velocity a bit}
494 declare $velocity
495 end on
496
497 on note
498 { First initialize the variable $i with 4 each time we enter this event
499 handler, because each time we executed this handler, the variable will be 0 }
500 $i := $delayNotes
501
502 { Loop which will be executed 4 times in a row }
503 while ($i)
504 { Calculate the velocity for the next note being triggered }
505 $velocity := 127 * $i / ($delayNotes + 1)
506 { Suspend this script for a short moment ... }
507 wait($delayMicroSeconds)
508 { ... and after that short break, trigger a new note. }
509 play_note($EVENT_NOTE, $velocity)
510 { Decrement loop counter $i by one }
511 $i := $i - 1
512 end while
513 end on
514 </code>
515 <p>
516 In this example we used a new keyword <code>const</code>. This additional
517 variable qualifier defines that we don't intend to change this variable
518 after declaration. So if you know beforehand, that a certain variable should
519 remain with a certain value, then you might use the <code>const</code>
520 qualifier to avoid that you i.e. change the value accidently when you
521 modify the script somewhere in future.
522 </p>
523 <p>
524 Now when you trigger one single note on your keyboard with that script,
525 you will hear the additional notes being triggered. And also when you
526 hit another note after a while, everything seems to be fine. However if
527 you start playing quick successive notes, you will notice something goes
528 wrong. The amount of notes being triggered by the script is now incorrect
529 and also the volume of the individual notes triggered by the script is wrong.
530 What's going on?
531 </p>
532 <p>
533 To understand the problem in the last example, let's consider what is
534 happening when executing that script exactly: Each time you play a note
535 on your keyboard, a new instance of the <code>note</code> event handler
536 will be spawned and executed by the sampler. In all our examples so far
537 our scripts were so simple, that in practice only one event handler instance
538 was executed at a time. This is different in this case though. Because
539 by calling the <code>wait()</code> function, the respective handler
540 execution instance is paused for a while and in total each handler
541 instance will be executed for more than 2 seconds in this particular
542 example. As a consequence, when
543 you play multiple, successive notes on your keyboard in short time, you
544 will have several instances of the <code>note</code> event handler running
545 simultaniously. And that's where the problem starts. Because by default,
546 as said, all variables are global variables. So the event handler instances
547 which are now running in parallel, are all reading and modifying the same
548 data. Thus the individual event handler instances will modify the
549 <code>$i</code> and <code>$velocity</code> variables of each other, causing
550 an undesired misbehavior.
551 </p>
552 <note>
553 NKSP's built-in function <code>play_note()</code> allows you to pass
554 between one and four function arguments. For the function arguments you
555 don't provide to a <code>play_note()</code> call, NKSP will automatically
556 use default values. If you want your script to be compatible with KSP,
557 then you should always pass four arguments to that function though.
558 </note>
559
560 <h3>Polyphonic Variables</h3>
561 <p>
562 As a logical consequence of the previously described data concurrency
563 problem, it would be desirable to have each event handler instance use
564 its own variable instance, so that the individual handler instances stop
565 interfering with each other. For this purpose the so called
566 <i title="A variable which is effectively a separate variable for each event handler instance.">
567 polyphonic variable
568 </i>
569 qualifier exists with NKSP. Declaring such a variable is identical to
570 declaring a regular variable, just that you add the keyword <code>polyphonic</code>.
571 </p>
572 <code>
573 declare polyphonic $??variable-name??
574 </code>
575 <p>
576 So to fix the bug in our previous example, we simply make the variables
577 <code>$i</code> and <code>$velocity</code> polyphonic variables.
578 </p>
579 <code>
580 on init
581 { The amount of notes to play }
582 declare const $delayNotes := 4
583 { Tempo with which the new notes will follow the orignal note }
584 declare const $bpm := 90
585 { Convert BPM to microseconds (duration between the notes) }
586 declare const $delayMicroSeconds := 60 * 1000000 / $bpm
587 { Just a working variable for being used with the while loop below }
588 declare polyphonic $i { < --- NOW POLYPHONIC !!! }
589 { For each successive note we trigger, we will reduce the velocity a bit}
590 declare polyphonic $velocity { < --- NOW POLYPHONIC !!! }
591 end on
592
593 on note
594 { First initialize the variable $i with 4 each time we enter this event
595 handler, because each time we executed this handler, the variable will be 0 }
596 $i := $delayNotes
597
598 { Loop which will be executed 4 times in a row }
599 while ($i)
600 { Calculate the velocity for the next note being triggered }
601 $velocity := 127 * $i / ($delayNotes + 1)
602 { Suspend this script for a short moment ... }
603 wait($delayMicroSeconds)
604 { ... and after that short break, trigger a new note. }
605 play_note($EVENT_NOTE, $velocity)
606 { Decrement loop counter $i by one }
607 $i := $i - 1
608 end while
609 end on
610 </code>
611 <p>
612 And that's it! The script works now as intended. Now you might wonder, why
613 are variables not <i>polyphonic</i> by default? Isn't that more common and
614 wouldn't that be more safer than using global variables by default? The reason is that
615 a polyphonic variable consumes a lot more memory than a regular (global) variable.
616 That's because for each polyphonic variable, the sampler has to allocate
617 in advance (when the script is loaded) as many instances of that
618 polyphonic variable as there are maximum events
619 allowed with the sampler. So that's a lot! Considering that today's
620 computers have plenty of RAM this might be a theoretical aspect, but in the
621 end: this default scope of variables was already like this with <i>KSP</i>
622 so we are also doing it like this with NKSP for compatibility reasons.
623 </p>
624 <p>
625 Please note that the <i>polyphonic</i> qualifier only exists for integer
626 variables. So you cannot declare polyphonic string variables, nor can you
627 declare polyphonic array variables. Like in the previous explanation,
628 this is due to the fact that it would consume a huge amount of memory
629 for such variables. And with string variables and array variables, the
630 required amount of memory would be much higher than with simple integer
631 variables.
632 </p>
633 <p>
634 As summary, the following are guideline rules describing when you should
635 use the polyphonic qualifier for a certain variable. You should declare
636 a particular variable polyphonic if one (or even both) of the following two
637 conditions apply to that variable.
638 </p>
639 <ol>
640 <li>
641 If you call the <code>wait()</code> function within your event
642 handlers and the respective variable is modified and read before
643 and after at least one of the individual <code>wait()</code> calls.
644 </li>
645 <li>
646 If you have loops that might run for a very long time, while accessing
647 the respective variable in between. That's because if your script is
648 running consecutively for too long, the sampler will automatically suspend your
649 script for a while to avoid your script becoming a real-time stability
650 hazard for the sampler. Your script will then automatically be resumed
651 after a short moment by the sampler, so effectively this is similar to
652 something like an "automated" <code>wait()</code> function call by
653 the sampler.
654 </li>
655 </ol>
656 <p>
657 In all other cases you should rather use regular (global) variables instead.
658 But keep in mind that you might need to re-assign a certain value for
659 some global variables when you enter the respective event handler, just
660 like we did with <code>$i := $delayNotes</code> right from the start
661 during discussion of the previous example script.
662 </p>
663 <p>
664 There is another special aspect regarding the variable scope of polyphonic
665 variables: <code>note</code> handlers and <code>release</code> handlers of
666 the same script share the same polyphonic variable scope, that means you
667 may pass data from a particular note's <code>note</code> handler to its
668 <code>release</code> handler by using the same polyphonic variable name.
669 </p>
670
671 <h2>Control Structures</h2>
672 <p>
673 A computer is more than a calculator that adds numbers and stores them
674 somewhere. One of the biggest strength of a computer, which makes it
675 such powerful, is the ability to do different things depending on various
676 conditions. For example your computer might clean up your hard drive
677 while you are not sitting in front of it, and it might immediately stop
678 doing so when you need all its resources to cut your latest video which
679 you just shot.
680 </p>
681 <p>
682 In order to do that for you, a computer program allows you to define
683 conditions and a list of instructions the computer shall
684 perform for you under those individual conditions. These kinds of
685 software mechanisms are called <i>Control Structures</i>.
686 </p>
687
688 <h3>if Branches</h3>
689 <p>
690 The most fundamental control structure are <i>if branches</i>, which has
691 the following general form.
692 </p>
693 <code>
694 if (??condition??)
695
696 ??statements??
697
698 end if
699 </code>
700 <p>
701 The specified <code>??condition??</code> is evaluated each time script
702 execution reaches this control block. The condition can for example be
703 the value of a variable, some arithmetic expression, a function call or
704 a combination of them. In all cases the sampler expects the
705 <code>??condition??</code> expression to evaluate to some numeric
706 (or boolean) value. If the evaluated number is exactly <code>0</code> then
707 the condition is interpreted to be <i>false</i> and thus the list of
708 <code>??statements??</code> is not executed. If the evaluated value is any
709 other value than <code>0</code> then the condition is interpreted to be
710 <i>true</i> and accordingly the list of <code>??statements??</code> will be
711 executed.
712 </p>
713 <p>
714 Alternatively you might also specify a list of instructions which shall be
715 executed when the condition is <i>false</i>.
716 </p>
717 <code>
718 if (??condition??)
719
720 ??statements-when-true??
721
722 else
723
724 ??statements-when-false??
725
726 end if
727 </code>
728 <p>
729 In this case the first list of statements is executed when the
730 <code>??condition??</code> evaluated to <i>true</i>, otherwise the second
731 list of statements is executed instead.
732 </p>
733 <p>
734 Once again, let's get back to the example of counting triggered notes.
735 You might have noticed that it did not output correct English for the
736 first three notes. Let's correct this now.
737 </p>
738 <code>
739 on init
740 declare $numberOfNotes
741 declare @postfix
742 end on
743
744 on note
745 $numberOfNotes := $numberOfNotes + 1
746
747 if ($numberOfNotes == 1)
748 @postfix := "st"
749 else
750 if ($numberOfNotes == 2)
751 @postfix := "nd"
752 else
753 if ($numberOfNotes == 3)
754 @postfix := "rd"
755 else
756 @postfix := "th"
757 end if
758 end if
759 end if
760
761 message("This is the " & $numberOfNotes & @postfix & " note triggered so far.")
762 end on
763 </code>
764 <p>
765 We are now checking the value of <code>$numberOfNotes</code> before we
766 print out a message. If <code>$numberOfNotes</code> equals one, then we
767 assign the string <code>"st"</code> to the variable <code>@postfix</code>,
768 if <code>$numberOfNotes</code> equals 2 instead we assign the string
769 <code>"nd"</code> instead, if it equals 3 instead we assign
770 <code>"rd"</code>, in all other cases we assign the string
771 <code>"th"</code>. And finally we assemble the text message to be
772 printed out to the terminal on line 23.
773 </p>
774
775 <h3>Select Case Branches</h3>
776 <p>
777 The previous example now outputs the numbers in correct English. But the
778 script code looks a bit bloated, right? That's why there is a short hand
779 form.
780 </p>
781 <code>
782 select ??expression??
783
784 case ??integer-1??
785
786 ??statements-1??
787
788
789 case ??integer-2??
790
791 ??statements-2??
792
793 .
794 .
795 .
796 end select
797 </code>
798 <p>
799 The provided <code>??expression??</code> is first evaluated to an integer
800 value. Then this value is compared to the integer values of the nested
801 <code>case</code> lines. So it first compares the evaluated value of
802 <code>??expression??</code> with <code>??integer-1??</code>, then it
803 compares it with <code>??integer-2??</code>, and so on. The first integer
804 number that matches with the evaluated value of <code>??expression??</code>,
805 will be interpreted as being the current valid condition. So if
806 <code>??expression??</code> equals <code>??integer-1??</code>,
807 then <code>??statements-1??</code> will be executed, otherwise if
808 <code>??expression??</code> equals <code>??integer-2??</code>,
809 then <code>??statements-2??</code> will be executed, and so on.
810 </p>
811 <p>
812 Using a select-case construct, our previous example would look like follows.
813 </p>
814 <code>
815 on init
816 declare $numberOfNotes
817 declare @postfix
818 end on
819
820 on note
821 $numberOfNotes := $numberOfNotes + 1
822 @postfix := "th"
823
824 select $numberOfNotes
825 case 1
826 @postfix := "st"
827 case 2
828 @postfix := "nd"
829 case 3
830 @postfix := "rd"
831 end select
832
833 message("This is the " & $numberOfNotes & @postfix & " note triggered so far.")
834 end on
835 </code>
836 <note>
837 If you like, you can also put parentheses around the select expression,
838 like <code>select (??expression??)</code>. Some developers familiar with
839 other programming languages might prefer this style. However if you want
840 to keep compatibility with KSP, you should not use parentheses for
841 select expressions.
842 </note>
843 <p>
844 The amount
845 of case conditions you add to such select-case blocks is completely up
846 to you. Just remember that the case conditions will be compared one by one,
847 from top to down. The latter can be important when you define a case line
848 that defines a value range. So for instance the following example will
849 not do what was probably intended.
850 </p>
851 <code>
852 on init
853 declare $numberOfNotes
854 end on
855
856 on note
857 $numberOfNotes := $numberOfNotes + 1
858
859 select $numberOfNotes
860 case 1 to 99
861 message("Less than 100 notes triggered so far")
862 exit
863 case 1
864 message("First note was triggered!") { Will never be printed ! }
865 exit
866 case 2
867 message("Second note was triggered!") { Will never be printed ! }
868 exit
869 case 3
870 message("Third note was triggered!") { Will never be printed ! }
871 exit
872 end select
873
874 message("Wow, already the " & $numberOfNotes & "th note triggered.")
875 end on
876 </code>
877 <p>
878 You probably get the idea what this script "should" do. For the 1st note
879 it should print <code>"First note was triggered!"</code>, for the 2nd
880 note it should print <code>"Second note was triggered!"</code>, for the 3rd
881 note it should print <code>"Third note was triggered!"</code>, for the 4th
882 up to 99th note it should print <code>"Less than 100 notes triggered so far"</code>,
883 and starting from the 100th note and all following ones, it should print
884 the precise note number according to line 23. However, it doesn't!
885 </p>
886 <p>
887 To correct this problem, you need to move the first case block to the end,
888 like follows.
889 </p>
890 <code>
891 on init
892 declare $numberOfNotes
893 end on
894
895 on note
896 $numberOfNotes := $numberOfNotes + 1
897
898 select $numberOfNotes
899 case 1
900 message("First note was triggered!")
901 exit
902 case 2
903 message("Second note was triggered!")
904 exit
905 case 3
906 message("Third note was triggered!")
907 exit
908 case 1 to 99
909 message("Less than 100 notes triggered so far")
910 exit
911 end select
912
913 message("Wow, already the " & $numberOfNotes & "th note triggered.")
914 end on
915 </code>
916 <p>
917 Or you could of course fix the questioned case range from <code>case 1 to 99</code>
918 to <code>case 4 to 99</code>. Both solutions will do.
919 </p>
920 <p>
921 We also used the <i>built-in function</i> <code>exit()</code> in the
922 previous example. You can use it to stop execution at that point of your
923 script. In the previous example it prevents multiple messages to be
924 printed to the terminal.
925 </p>
926 <note class="important">
927 The <code>exit()</code> function only stops execution of the <b>current</b>
928 event handler instance! It does <b>not</b> stop execution of other
929 instances of the same event handler, nor does it stop execution of other
930 handlers of other event types, and especially it does <b>not</b> stop or
931 prevent further or future execution of your entire script! In other words,
932 you should rather see this function as a return statement, in case you are
933 familiar with other programming languages already.
934 </note>
935
936 <h3>while Loops</h3>
937 <p>
938 Another fundamental control construct of program flow are loops.
939 You can use so called
940 <i title="Repeats a given list of instructions until the defined condition turns false.">
941 while loops
942 </i>
943 with NKSP.
944 </p>
945 <code>
946 while (??condition??)
947
948 ??statements??
949
950 end while
951 </code>
952 <p>
953 A while loop is entered if the provided <code>??condition??</code>
954 expression evaluates to <i>true</i> and will then continue to execute
955 the given list of <code>??statements??</code> down to the end of the statements
956 list. The <code>??condition??</code> is re-evaluated each time execution
957 reached the end of the <code>??statements??</code> list and according to
958 that latest evaluated <code>??condition??</code> value at that point, it
959 will or will not repeat executing the statements again. If the condition
960 turned <i>false</i> instead, it will leave the loop and continue executing
961 statements that follow after the while loop block.
962 </p>
963 <p>
964 The next example will print the same message three times in a row to the
965 terminal, right after the script had been loaded by the sampler.
966 </p>
967 <code>
968 on init
969 declare $i := 3
970
971 while ($i)
972 message("Print this three times.")
973 $i := $i - 1
974 end while
975 end on
976 </code>
977 <p>
978 When the while loop is reached for the first time in this example, the
979 condition value is <code>3</code>. And as we learned before, all integer
980 values that are not <code>0</code> are interpreted as being a <i>true</i> condition.
981 Accordingly the while loop is entered, the message is printed to the
982 terminal and the variable <code>$i</code> is reduced by one. We reached
983 the end of the loop's statements list, so it is now re-evaluating the
984 condition, which is now the value <code>2</code> and thus the loop
985 instructions are executed again. That is repeated until the loop was
986 executed for the third time. The variable <code>$i</code> is now
987 <code>0</code>, so the loop condition turned finally to <i>false</i> and the
988 loop is thus left at that point and the text message was printed
989 three times in total.
990 </p>
991
992 <h3>User Functions</h3>
993 <p>
994 We already came across various built-in functions, which you may call
995 by your scripts to perform certain tasks or behavior which is already
996 provided for you by the sampler. NKSP also allows you to write your
997 own functions, which you then may call from various places of your
998 script.
999 <p>
1000 </p>
1001 When working on larger scripts, you
1002 may notice that you easily get to the point where you may have to
1003 duplicate portions of your script code, since there are certain things
1004 that you may have to do again and again in different parts of your script.
1005 Software developers usually try to avoid such code duplications to
1006 keep the overall amount of code as small as possible, since the
1007 overall amount of code would bloat quickly and would
1008 make the software very hard to maintain. One way for you to avoid such
1009 script code duplications with NKSP is to write so called <i>User Functions</s>.
1010 </p>
1011 <p>
1012 Let's assume you wanted to create a simple stuttering effect. You may do so
1013 like in the following example.
1014 </p>
1015 <code>
1016 on note
1017 while (1)
1018 wait(200000)
1019 if (not (event_status($EVENT_ID) .and. $EVENT_STATUS_NOTE_QUEUE))
1020 exit()
1021 end if
1022 change_vol($EVENT_ID, -20000) { Reduce volume by 20 dB. }
1023 wait(200000)
1024 if (not (event_status($EVENT_ID) .and. $EVENT_STATUS_NOTE_QUEUE))
1025 exit()
1026 end if
1027 change_vol($EVENT_ID, 0) { Increase volume to 0 dB. }
1028 end while
1029 end on
1030 </code>
1031 <p>
1032 This script will run an endless loop for each note being triggered.
1033 Every <code lang="none">200ms</code> it will turn the volume alternatingly down and
1034 up to create the audible stuttering effect. After each <code lang="nksp">wait()</code>
1035 call it calls <code>event_status($EVENT_ID)</code> to check whether
1036 this note is still alive, and as soon as the note died, it will stop
1037 execution of the script instance by calling <code>exit()</code>. The latter
1038 is important in this example, because otherwise the script execution instances would
1039 continue to run in this endless loop forever, even after the respectives
1040 notes are gone. Which would let your CPU usage increase with every new note
1041 and would never decrease again.
1042 This behavior of the sampler is not a bug, it is intended, since there may
1043 also be cases where you want to do certain things by script even after the
1044 respective notes are dead and gone. However as you can see, that script is
1045 using the same portions of script code twice. To avoid that, you could also
1046 write the same script with a user function like this:
1047 </p>
1048 <code>
1049 function pauseMyScript
1050 wait(200000)
1051 if (not (event_status($EVENT_ID) .and. $EVENT_STATUS_NOTE_QUEUE))
1052 exit()
1053 end if
1054 end function
1055
1056 on note
1057 while (1)
1058 call pauseMyScript
1059 change_vol($EVENT_ID, -20000) { Reduce volume by 20 dB. }
1060 call pauseMyScript
1061 change_vol($EVENT_ID, 0) { Increase volume back to 0 dB. }
1062 end while
1063 end on
1064 </code>
1065 <p>
1066 The script became in this simple example only slightly smaller, but it also
1067 became easier to read and behaves identically to the previous solution.
1068 And in practice, with a more complex script, you can
1069 reduce the overall amount of script code a lot this way. You can choose any
1070 name for your own user functions, as long as the name is not already
1071 reserved by a built-in function. Note that for calling a user function,
1072 you must always precede the actual user function name with the
1073 <code>call</code> keyword. Likewise you may however not use the
1074 <code>call</code> keyword for calling any built-in function. So that
1075 substantially differs calling built-in functions from calling user functions.
1076 </p>
1077
1078 <h3>Synchronized Blocks</h3>
1079 <p>
1080 When we introduced the <a href="#polyphonic_variables">polyphonic keyword</a>
1081 previously, we learned that a script may automatically be suspended by
1082 the sampler at any time and then your script is thus sleeping for an
1083 arbitrary while. The sampler must do such auto suspensions under certain
1084 situations in cases where an instrument script may become a hazard for the
1085 sampler's overall real-time stability. If the sampler would not do so, then
1086 instrument scripts might easily cause audio dropouts, or at worst, buggy
1087 instrument scripts might even lock up the entire sampler in an endless
1088 loop. So auto suspension is an essential feature of the sampler's real-time
1089 instrument script engine.
1090 </p>
1091 <p>
1092 Now the problem as a script author is that you don't really know beforehand
1093 why and when your script might get auto suspended by the sampler. And when
1094 you are working on more complex, sophisticated scripts, you will notice
1095 that this might indeed be a big problem in certain sections of your scripts.
1096 Because in practice, a sophisticated script often has at least one certain
1097 consecutive portion of statements which must be executed in strict consecutive order
1098 by the sampler, which might otherwise cause concurrency issues and thus
1099 misbehavior of your script if that sensible code section was auto suspended
1100 in between. A typical example of such concurrency sensible code sections are
1101 statements which are reading and conditionally modifying global variables.
1102 If your script gets auto suspended in such a code section, another
1103 script handler instance might then interfere and change those global
1104 variables in between.
1105 </p>
1106 <p>
1107 To avoid that, you can place such a sensible code section at the very beginning
1108 of your event handler. For example consider you might be writing a custom
1109 <i title="A consecutive pitch glide from one note to another note.">glissando</i>
1110 script starting like this:
1111 </p>
1112 <code>
1113 on init
1114 declare $keysDown
1115 declare $firstNoteID
1116 declare $firstNoteNr
1117 declare $firstVelocity
1118 end on
1119
1120 on note
1121 { The concurrency sensible code section for the "first active" note. }
1122 inc($keysDown)
1123 if ($keysDown = 1 or event_status($firstNoteID) = $EVENT_STATUS_INACTIVE)
1124 $firstNoteID = $EVENT_ID
1125 $firstNoteNr = $EVENT_NOTE
1126 $firstVelocity = $EVENT_VELOCITY
1127 exit { return from event handler here }
1128 end if
1129
1130 { The non-sensible code for all other subsequent notes would go here. }
1131 end on
1132
1133 on release
1134 dec($keysDown)
1135 end on
1136 </code>
1137 <p>
1138 Because the earlier statements are executed in an event handler, the higher
1139 the chance that they will never get auto suspended. And with those couple of
1140 lines in the latter example you might even be lucky that it won't ever get
1141 suspended in that sensible code section at least. However when it comes to live
1142 concerts you don't really want to depend on luck, and in practice such a
1143 sensible code section might be bigger than this one.
1144 </p>
1145 <p>
1146 That's why we introduced <code>synchronized</code> code blocks for the
1147 NKSP language, which have the following form:
1148 </p>
1149 <code>
1150 synchronized
1151
1152 ??statements??
1153
1154 end synchronized
1155 </code>
1156 <p>
1157 All <code>??statements??</code> which you put into such a synchronized
1158 code block are guaranteed that they will never get auto suspended by
1159 the sampler.
1160 </p>
1161 <note>
1162 Such <code>synchronized</code> blocks are a language extension which
1163 is only available with NKSP. KSP does not support <code>synchronized</code> blocks.
1164 </note>
1165 <p>
1166 So to make our previous example concurrency safe, we would
1167 change it like this:
1168 </p>
1169 <code>
1170 on init
1171 declare $keysDown
1172 declare $firstNoteID
1173 declare $firstNoteNr
1174 declare $firstVelocity
1175 end on
1176
1177 on note
1178 { The concurrency sensible code section for the "first active" note. }
1179 synchronized
1180 inc($keysDown)
1181 if ($keysDown = 1 or event_status($firstNoteID) = $EVENT_STATUS_INACTIVE)
1182 $firstNoteID = $EVENT_ID
1183 $firstNoteNr = $EVENT_NOTE
1184 $firstVelocity = $EVENT_VELOCITY
1185 exit { return from event handler here }
1186 end if
1187 end synchronized
1188
1189 { The non-sensible code for all other subsequent notes would go here. }
1190 end on
1191
1192 on release
1193 dec($keysDown)
1194 end on
1195 </code>
1196 <p>
1197 If you are already familiar with some programming languages, then you
1198 might already have seen such synchronized code block concepts
1199 in languages like e.g. Java. This technique really provides an easy way
1200 to protect certain sections of your script against concurrency issues.
1201 </p>
1202 <note class="important">
1203 You <b>must</b> use such <code>synchronized</code> code blocks only with great
1204 care! If the amount of statements being executed in your synchronized block
1205 is too large, then you will get audio dropouts. If you even use loops in
1206 synchronized code blocks, then the entire sampler might even become
1207 unresponsive in case your script is buggy!
1208 </note>
1209
1210 <h2>Operators</h2>
1211 <p>
1212 A programming language provides so called <i>operators</i> to perform
1213 certain kinds of transformations of data placed next to the operators.
1214 These are the operators available with NKSP.
1215 </p>
1216
1217 <h3>Arithmetic Operators</h3>
1218 <p>
1219 These are the most basic mathematical operators, which allow to add,
1220 subtract, multiply and divide integer values with each other.
1221 </p>
1222 <code>
1223 on init
1224 message("4 + 3 is " & 4 + 3) { Add }
1225 message("4 - 3 is " & 4 - 3) { Subtract }
1226 message("4 * 3 is " & 4 * 3) { Multiply }
1227 message("35 / 5 is " & 35 / 5) { Divide }
1228 message("35 mod 5 is " & 35 mod 5) { Remainder of Division ("modulo") }
1229 end on
1230 </code>
1231 <p>
1232 You may either use direct integer literal numbers like used in the upper
1233 example, or you can use integer number variables or integer array variables.
1234 </p>
1235
1236 <h3>Boolean Operators</h3>
1237 <p>
1238 To perform logical transformations of <i>boolean</i> data, you may use the
1239 following logical operators:
1240 </p>
1241 <code>
1242 on init
1243 message("1 and 1 is " & 1 and 1) { logical "and" }
1244 message("1 and 0 is " & 1 and 0) { logical "and" }
1245 message("1 or 1 is " & 1 or 1) { logical "or" }
1246 message("1 or 0 is " & 1 or 0) { logical "or" }
1247 message("not 1 is " & not 1) { logical "not" }
1248 message("not 0 is " & not 0) { logical "not" }
1249 end on
1250 </code>
1251 <p>
1252 Keep in mind that with logical operators shown above,
1253 all integer values other than <code>0</code>
1254 are interpreted as boolean <i>true</i> while an integer value of
1255 precisely <code>0</code> is interpreted as being boolean <i>false</i>.
1256 </p>
1257 <p>
1258 So the logical operators shown above always look at numbers at a whole.
1259 Sometimes however you might rather need to process numbers bit by bit. For
1260 that purpose the following bitwise operators exist.
1261 </p>
1262 <code>
1263 on init
1264 message("1 .and. 1 is " & 1 .and. 1) { bitwise "and" }
1265 message("1 .and. 0 is " & 1 .and. 0) { bitwise "and" }
1266 message("1 .or. 1 is " & 1 .or. 1) { bitwise "or" }
1267 message("1 .or. 0 is " & 1 .or. 0) { bitwise "or" }
1268 message(".not. 1 is " & .not. 1) { bitwise "not" }
1269 message(".not. 0 is " & .not. 0) { bitwise "not" }
1270 end on
1271 </code>
1272 <p>
1273 Bitwise operators work essentially like logical operators, with the
1274 difference that bitwise operators compare each bit independently.
1275 So a bitwise <code>.and.</code> operator for instance takes the 1st bit
1276 of the left hand's side value, the 1st bit of the right hand's side value,
1277 compares the two bits logically and then stores that result as 1st bit of
1278 the final result value, then it takes the 2nd bit of the left hand's side value
1279 and the 2nd bit of the right hand's side value, compares those two bits logically
1280 and then stores that result as 2nd bit of the final result value, and so on.
1281 </p>
1282
1283
1284 <h3>Comparison Operators</h3>
1285 <p>
1286 For branches in your program flow, it is often required to compare data
1287 with each other. This is done by using comparison operators, enumerated
1288 below.
1289 </p>
1290 <code>
1291 on init
1292 message("Relation 3 < 4 -> " & 3 < 4) { "smaller than" comparison }
1293 message("Relation 3 > 4 -> " & 3 > 4) { "greater than" comparison }
1294 message("Relation 3 <= 4 -> " & 3 <= 4) { "smaller or equal than" comparison}
1295 message("Relation 3 >= 4 -> " & 3 >= 4) { "greater or equal than" comparison}
1296 message("Relation 3 # 4 -> " & 3 # 4) { "not equal to" comparison}
1297 message("Relation 3 = 4 -> " & 3 = 4) { "is equal to" comparison}
1298 end on
1299 </code>
1300 <p>
1301 All these operations yield in a <i>boolean</i> result which could then
1302 be used e.g. with <code>if</code> or <code>while</code> loop statements.
1303 </p>
1304
1305 <h3>String Operators</h3>
1306 <p>
1307 Last but not least, there is exactly one operator for text string data;
1308 the string concatenation operator <code>&</code>, which
1309 combines two text strings with each other.
1310 </p>
1311 <code>
1312 on init
1313 declare @s := "foo" & " bar"
1314 message(@s)
1315 end on
1316 </code>
1317 <p>
1318 We have used it now frequently in various examples before.
1319 </p>
1320
1321 <h2>Preprocessor Statements</h2>
1322 <p>
1323 Similar to low-level programming languages like C, C++, Objective C
1324 and the like, NKSP supports a set of so called preprocessor statements.
1325 These are essentially "instructions" which are "executed" or rather
1326 processed, before (and only before) the script is executed by the sampler,
1327 and even before the script is parsed by the actual NKSP language parser.
1328 You can think of a preprocessor as a very primitive parser, which is the
1329 first one getting in touch with your script, it modifies the script code
1330 if requested by your preprocessor statements in the script, and then
1331 passes the (probably) modified script to the actual NKSP language parser.
1332 </p>
1333 <p>
1334 When we discussed <a href="#comments">comments</a> in NKSP scripts before,
1335 it was suggested that you might comment out certain code parts to disable
1336 them for a while during development of scripts. It was also suggested
1337 during this language tour that you should not use string variables or use
1338 the <code>message()</code> function with your final production sounds.
1339 However those are very handy things during development of your instrument
1340 scripts. You might even have a bunch of additional code in your scripts
1341 which only satisfies the purpose to make debugging of your scripts more easy,
1342 which however wastes on the other hand precious CPU time. So what do you
1343 do? Like suggested, you could comment out the respective code sections as
1344 soon as development of your script is completed. But then one day you
1345 might continue to improve your scripts, and the debugging code would be
1346 handy, so you would uncomment all the relevant code sections to get them
1347 back. When you think about this, that might be quite some work each time.
1348 Fortunately there is an alternative by using preprocessor statements.
1349 </p>
1350
1351 <h3>Set a Condition</h3>
1352 <p>
1353 First you need to set a preprocessor condition in your script. You can do
1354 that like this:
1355 </p>
1356 <code>
1357 SET_CONDITION(??condition-name??)
1358 </code>
1359 <p>
1360 This preprocessor "condition" is just like some kind of
1361 <i title="A variable which can only have two states: i.e. true or false.">
1362 boolean variable
1363 </i>
1364 which is only available to the preprocessor and by using
1365 <code>SET_CONDITION(??condition-name??)</code>, this is like setting this
1366 preprocessor condition to <i>true</i>. Like with regular script
1367 variables, a preprocessor condition name can be chosen quite arbitrarily
1368 by you. But again, there are some pre-defined preprocessor conditions
1369 defined by the sampler for you. So you can only set a condition name here
1370 which is not already reserved by a built-in preprocessor condition. Also
1371 you shall not set a condition in your script again if you have already set it
1372 before somewhere in your script. The NKSP preprocessor will ignore setting
1373 a condition a 2nd time and will just print a warning when the script is
1374 loaded, but you should take care of it, because it might be a cause for
1375 some bug.
1376 </p>
1377
1378 <h3>Reset a Condition</h3>
1379 <p>
1380 To clear a condition in your script, you might reset the condition like so:
1381 </p>
1382 <code>
1383 RESET_CONDITION(??condition-name??)
1384 </code>
1385 <p>
1386 This is like setting that preprocessor condition back to <i>false</i> again.
1387 You should only reset a preprocessor condition that way if you did set it
1388 with <code>SET_CONDITION(??condition-name??)</code> before. Trying to
1389 reset a condition that has not been set before, or trying to reset a
1390 condition that has already been reset, will both be ignored by the sampler,
1391 but again you will get a warning, and you should take care about it.
1392 </p>
1393
1394 <h3>Conditionally Using Code</h3>
1395 <p>
1396 Now what do you actually do with such preprocessor conditions? You can use
1397 them for the NKSP language parser to either
1398 </p>
1399 <ul>
1400 <li>use certain parts of your code</i>
1401 <li><b>and</b> / <b>or</b> to ignore certain parts of your code</i>
1402 </ul>
1403 <p>
1404 You can achieve that by wrapping NKSP code parts into a pair of either
1405 </p>
1406 <code>
1407 USE_CODE_IF(??condition-name??)
1408
1409 ??some-NKSP-code-goes-here??
1410
1411 END_USE_CODE
1412 </code>
1413 <p>
1414 preprocessor statements, or between
1415 </p>
1416 <code>
1417 USE_CODE_IF_NOT(??condition-name??)
1418
1419 ??some-NKSP-code-goes-here??
1420
1421 END_USE_CODE
1422 </code>
1423 <p>
1424 statements. In the first case, the NKSP code portion is used by the NKSP
1425 language parser if the given preprocessor <code>??condition-name??</code> is set
1426 (that is if condition is <i>true</i>).
1427 If the condition is not set, the NKSP code portion in between is
1428 completely ignored by the NKSP language parser.
1429 </p>
1430 <p>
1431 In the second case, the NKSP code portion is used by the NKSP
1432 language parser if the given preprocessor <code>??condition-name??</code> is <b>not</b> set
1433 (or was reset)
1434 (that is if condition is <i>false</i>).
1435 If the condition is set, the NKSP code portion in between is
1436 completely ignored by the NKSP language parser.
1437 </p>
1438 <p>
1439 Let's look at an example how to use that to define conditional debugging
1440 code.
1441 </p>
1442 <code>
1443 SET_CONDITION(DEBUG_MODE)
1444
1445 on init
1446 declare const %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
1447 declare $i
1448
1449 USE_CODE_IF(DEBUG_MODE)
1450 message("This script has just been loaded.")
1451
1452 $i := 0
1453 while ($i < num_elements(%primes))
1454 message("Prime " & $i & " is " & %primes[$i])
1455 $i := $i + 1
1456 end while
1457 END_USE_CODE
1458 end on
1459
1460 on note
1461 USE_CODE_IF(DEBUG_MODE)
1462 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
1463 END_USE_CODE
1464 end on
1465
1466 on release
1467 USE_CODE_IF(DEBUG_MODE)
1468 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
1469 END_USE_CODE
1470 end on
1471
1472 on controller
1473 USE_CODE_IF(DEBUG_MODE)
1474 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
1475 END_USE_CODE
1476 end on
1477 </code>
1478 <p>
1479 The <i>built-in function</i> <code>num_elements()</code> used above, can
1480 be called to obtain the size of an array variable at runtime.
1481 As this script looks now, the debug messages will be printed out. However
1482 it requires you to just remove the first line, or to comment out the first
1483 line, in order to disable all debug code portions in just a second:
1484 </p>
1485 <code>
1486 { Setting the condition is commented out, so our DEBUG_MODE is disabled now. }
1487 { SET_CONDITION(DEBUG_MODE) }
1488
1489 on init
1490 declare const %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
1491 declare $i
1492
1493 USE_CODE_IF(DEBUG_MODE) { Condition is not set, so this entire block will be ignored now. }
1494 message("This script has just been loaded.")
1495
1496 $i := 0
1497 while ($i < num_elements(%primes))
1498 message("Prime " & $i & " is " & %primes[$i])
1499 $i := $i + 1
1500 end while
1501 END_USE_CODE
1502 end on
1503
1504 on note
1505 USE_CODE_IF(DEBUG_MODE) { Condition is not set, no message will be printed. }
1506 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
1507 END_USE_CODE
1508 end on
1509
1510 on release
1511 USE_CODE_IF(DEBUG_MODE) { Condition is not set, no message will be printed. }
1512 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
1513 END_USE_CODE
1514 end on
1515
1516 on controller
1517 USE_CODE_IF(DEBUG_MODE) { Condition is not set, no message will be printed. }
1518 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
1519 END_USE_CODE
1520 end on
1521 </code>
1522 <p>
1523 Now you might say, you could also achieve that by declaring and using
1524 a regular NKSP variable. That's correct, but there are two major
1525 advantages by using preprocessor statements.
1526 </p>
1527 <ol>
1528 <li>
1529 <b>Saving Resources</b> -
1530 The preprocessor conditions are only processed before the script is
1531 loaded into the NKSP parser. So in contrast to using NKSP variables,
1532 the preprocessor solution does not waste any CPU time or memory
1533 resources while executing the script. That also means that variable
1534 declarations can be disabled with the preprocessor this way
1535 and thus will also safe resources.
1536 </li>
1537 <li>
1538 <b>Cross Platform Support</b> -
1539 Since the code portions filtered out by the preprocessor never make it
1540 into the NKSP language parser, those filtered code portions might also
1541 contain code which would have lead to parser errors. For example you
1542 could use a built-in preprocessor condition to check whether your script
1543 was loaded into LinuxSampler or rather into another sampler. That way
1544 you could maintain one script for both platforms: NKSP and KSP.
1545 Accordingly you could
1546 also check a built-in variable to obtain the version of the sampler in
1547 order to enable or disable code portions of your script that might
1548 use some newer script features of the sampler which don't exist in older
1549 version of the sampler.
1550 </li>
1551 </ol>
1552 <p>
1553 As a rule of thumb: if there are things that you could move from your
1554 NKSP executed programming code out to the preprocessor, then you should
1555 use the preprocessor instead for such things. And like stated above,
1556 there are certain things which you can only achieve with the preprocessor.
1557 </p>
1558
1559 <h3>Disable Messages</h3>
1560 <p>
1561 Since it is quite common to switch a script between a development version
1562 and a production version, you actually don't need to wrap all your
1563 <code>message()</code> calls into preprocessor statements like in the
1564 previous example just to disable messages. There is actually a built-in
1565 preprocessor condition dedicated to perform that task much more conveniently for you.
1566 To disable all messages in your script, simply add <code>SET_CONDITION(NKSP_NO_MESSAGE)</code>
1567 e.g. at the very beginning of your script.
1568 So the previous example can be simplified to this:
1569 </p>
1570 <code>
1571 { Enable debug mode, so show all debug messages. }
1572 SET_CONDITION(DEBUG_MODE)
1573
1574 { If our user declared condition "DEBUG_MODE" is not set ... }
1575 USE_CODE_IF_NOT(DEBUG_MODE)
1576 { ... then enable this built-in condition to disable all message() calls. }
1577 SET_CONDITION(NKSP_NO_MESSAGE)
1578 END_USE_CODE
1579
1580 on init
1581 declare const %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
1582 declare $i
1583
1584 message("This script has just been loaded.")
1585
1586 USE_CODE_IF(DEBUG_MODE)
1587 $i := 0
1588 while ($i < num_elements(%primes))
1589 message("Prime " & $i & " is " & %primes[$i])
1590 $i := $i + 1
1591 end while
1592 END_USE_CODE
1593 end on
1594
1595 on note
1596 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
1597 end on
1598
1599 on release
1600 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
1601 end on
1602
1603 on controller
1604 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
1605 end on
1606 </code>
1607 <p>
1608 You can then actually also add <code>RESET_CONDITION(NKSP_NO_MESSAGE)</code>
1609 at another section of your script, which will cause all subsequent
1610 <code>message()</code> calls to be processed again. So that way you can
1611 easily enable and disable <code>message()</code> calls of entire individual
1612 sections of your script, without having to wrap all <code>message()</code>
1613 calls into preprocessor statements.
1614 </p>
1615
1616 <h2>What Next?</h2>
1617 <p>
1618 You have completed the introduction of the NKSP real-time instrument
1619 script language at this point. You can now dive into the details of the
1620 NKSP language by moving on to the
1621 <a href="nksp_reference.html">NKSP reference documentation</a>.
1622 Which provides you an overview and quick access to the details of all
1623 built-in functions, built-in variables and more.
1624 </p>
1625 <p>
1626 You might also be interested to look at new <i>NKSP</i> core language
1627 features being added to the latest development version of the sampler:
1628 <a href="real_unit_final/01_nksp_real_unit_final.html">
1629 Real Numbers, Units and Finalness ...
1630 </a>
1631 </p>
1632
1633 </body>
1634 </html>

  ViewVC Help
Powered by ViewVC