text:
Convert braces to Right Hand Brace (Sad Brace)
Right hand brace is a style of code bracketing in which curly braces and semicolons are all aligned to a single point on the right side of a a file.

Generally, this is considered bad practice, for several reasons.
The Challenge
Take a multiline string through any method, and convert it's brace style to Right Hand Brace.
For this challenge, you only need it to work on Java code, however, it should theoretically work on any code that uses Braces and Semicolons.
You must grab all {}; characters in a row, with any amount of whitespace between them. EG. }}, ; } }\n\t\t}, and line them up on the right side of the file through the use of whitespace.
for example:
a {
b;
{c

should become
a {
b ;{
c

Or, more abstractly, push any and all whitespace from the left of all {}; characters, to the right.
Indentation of lines should be otherwise preserved. Lines only containing whitespace after the movement of the {}; characters may optionally be removed.
For example:
a{
    b{
        c;
    }
}
d;

May become either
a        {
    b    {
        c;}}
d        ;

or
a        {
    b    {
        c;}}

d        ;

Pushed to the right refers to all the {}; characters being aligned to a point no shorter than the longest line. Any amount of space after that is acceptable.
So all the below is acceptable:
a {
bc;

a  {
bc ;

a   {
bc  ;

etc...
Lines in any code may contain {}; characters between other non-whitspace characters, the handling of this case isn't necessary, although if you're inclined, you should leave them in place. Lines may also not contain any {}; characters at all, and this should be handled correctly. As is shown below.
a {
b ;
c
d }

Because we don't want Code Review to see the horrible things we're doing, you need to make your code as small as possible.
Examples / Testcases
Generic Java
public class HelloWorld{
       public static void main(String[] args){
           System.out.println("Hello, World!");
       }
}

becomes...
public class HelloWorld                        {
    public static void main(String[] args)     {
        System.out.println("Hello, World!")    ;}}

The image itself
public class Permuter{
    private static void permute(int n, char[] a){
        if (n == 0){
            System.out.println(String.valueOf(a));
        }else{
            for (int i=0; i<= n; i++){
                permute(n-1, a);
                swap(a, n % 2 == 0 ? i : 0, n);
            }
        }
    }
    private static void swap(char[] a, int i, int j){
        char saved = a[i];
        a[i] = a[j];
        a[j] = saved;
    }
}

becomes...
public class Permuter                                {
    private static void permute(int n, char[] a)     {
        if (n == 0)                                  {
            System.out.println(String.valueOf(a))    ;}
        else                                         {
            for (int i=0; i<= n; i++)                {
                permute(n-1, a)                      ;
                swap(a, n % 2 == 0 ? i : 0, n)       ;}}}
    private static void swap(char[] a, int i, int j) {
        char saved = a[i]                            ;
        a[i] = a[j]                                  ;
        a[j] = saved                                 ;}}

Not so Perfectly Generic Python
For contrast
def Main():
    print("Hello, World!");

Main();

becomes...
def Main():
    print("Hello, World!")    ;
Main()                        ;

Notes

Standard Loopholes apply
Standard IO applies
This is code-golf, so shortest program in bytes wins!
I am not Liable for damages related to programming in Right Hand Brace style
Have Fun!

Edit Notes
I reworded the challenge details, Hopefully I didn't break anyone's view of the rules, I assure you it was unintentional. This should be a much more clear and less self-conflicting spec.

What's the verdict on lines with multiple semicolons? Something like int a=0;System.out.println(a);

You only need to handle the last semicolon, although you may optionally insert a newline after each. You can assume such a case won't happen

Oh I forgot to ask - can we assume no white space exists to the right of any trailing {};s?

@JonathanAllan For the case of this, you can assume to whitespace after the {};s, however, you do need to combine {};s with whitespace between them, including across lines.

Ah "and across lines". I read "You may optionally: ... Preserve blank lines" to mean we can keep them.

If a { is on its own line, and the line before it has no braces or semicolons, such as if (condition), does the brace need to go up to the previous line?

Yes, otherwise it leaves a basically blank line left over

That might no be the best image for the challenge if we don't need to handle for loops like in the sample image?

The sample image was the inspiration for this challenge. Plus, the actual contents of the code shouldn't matter that much.

Looks like the image in the question came from this example, which was followed up by this followup, which has more complex examples

It could be made clearer that you want the ;{} characters gathered up if they're on separate lines (it's only clear from the example, not the rules, and in fact if a line consists of \t} preserving the indentation would mean not moving } up to the end of the previous line)

Can we assume there is always a semicolon or brace in a line with code?

You say Yes, otherwise it leaves a basically blank line left over here in the comments, but You may optionally: [...] Preserve blank lines in the challenge. Those seem to contradict each other.

In the second example, on the second line, there are two spaces between the closing bracket and the semicolon. Is this on purpose? if so, does this mean that A space between the longest line and this point is optional is in reality some spaces... ?

The 'a space' refers simply to any amount of white space. In regards to @Dennis, he's right. The preserving or removal of those lines Which only contain {}; should be optional. As for @Titus, there may not always be a brace or a semicolon on the line. I may reword the rules to make this more obvious when I get to a computer.

Some more test cases would be nice...

You edit changes the challenge a lot. In particular, the removal of you can assume these characters will not occur in the middle of a line. might invalidate a few answers.

@Dada It invalidates mine, so I have to change it now

Also in your Permuter example, you forgot to move the brace behind the }else

Good god, please tell me nobody actually does this in practice for a verbose language like Java ._.

I think this style is for people who like whitespace-delineated languages (accuracy of term?) (cough, Python, cough) or like the game of "find the missing brace!"

V + Bash utilities, 64 62 61 60 62 bytes
1 byte saved thanks to @DJMcMayhem for putting the ex commands together
:se ve=all|%!wc -L
y$uò/^ *<93>[{};]
xk$pòò/<84> {};][{};]«$
lDî^R0|p

^R is the character literal for <C-r> (0x12) and <84> is 0x84 and <94> is 0x94.
wc -L works on most *nix based systems, but not macOS. For macOS, you have to do gwc -L  after getting coreutils using brew, if you haven't already.
Try it online! (Java)
Try it online! (Python)
Try it online! (Java again)
This preserves all blank lines and does not handle tabs, only spaces.
Hexdump:
00000000: 3a73 6520 7665 3d61 6c6c 7c25 2177 6320  :se ve=all|%!wc
00000010: 2d4c 0a79 2475 f22f 5e20 2a93 5b7b 7d3b  -L.y$u./^ *.[{};
00000020: 5d0a 786b 2470 f2f2 2f84 207b 7d3b 5d5b  ].xk$p../. {};][
00000030: 7b7d 3b5d ab24 0a6c 44ee 1230 7c70       {};].$.lD..0|p

Explanation
First we need to be able to move the cursor anywhere in the buffer, so we use
:se ve=all|...

and we chain this with another ex command using |
We need to get the length of the longest line in the input. This can be done with the shell command wc -L.
       ...|%!wc -L

This overwrites the current buffer (containing the input) with the result of wc -L. It gives an output of something like:
            42

and the cursor lands on the 4 in 42. Then we copy this number by using y$: yank text from the cursor's position to the end of the line. This conveniently stores this number in register 0. But more on that later. The input is replaced with this number, so to revert back, we undo.
Now say the input looked somewhat like this:
public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello, World!");
    }
}

we need to move the braces } from the end of the buffer to just after the println statement.
ò                  " recursively do this until a breaking error:
 /^ *<93>[{};]     "   this compressed regex becomes /^ *\zs[{};]
                   "   this finds any character from `{};` after leading spaces
                   "   the cursor then goes to the `{};`

x                  "   delete character
 k$                "   go to the end of the line above
   p               "   and paste
    ò

If the regex cannot be found, a breaking error happens and breaks out of the recursion caused by ò.
Now comes the main part of this program, move all braces and semi-colons and align them as stated in the question.
ò                  " starts recursion
 /<84> {};][{};]«$ "   compressed form of [^ {};][{};]\+$
                   "   finds a sequence of `{};`s at the end of the line with a non-`{};` char to preceding it
 l                 "   move the cursor 1 to the right (since we were on the non-`{};` char now)
  D                "   delete everything from this position to the end of line
                   "   the deleted text contains `{};`
   î               "   execute as normal commands:
    ^R0            "   contains what's in register `0`, ie the length of the longest line
       |           "   now go to the column specified by that number
        p          "   and paste the contents
                   " implicit ending `ò`

Again, this recursion will be stopped by a breaking error caused when the regex could not be found in the buffer.
Edits

Used D instead of d$ (I don't even know why I missed that in the first place)
Compressed [^ (in the regex) to <84>
Fixed bug by using \zs (compressing it into <93>) and by removing the $ in $xk$pò
Removed useless newline
Changed regex to make submission compliant with new rules and gained 2 bytes

You could save one byte if you join your ex commands together :se ve=all|%!wc -L

@DJMcMayhem Thanks, TIL

Ruby, 100 114 108 bytes
Reads file name as command line argument. If no file name is supplied, it'll read from STDIN. Does not handle tabs.
Try it online!
f=$<.read.gsub(/[\s;{}]*$/){$&.tr"
 ",''}
$><<f.gsub(/(.*?)([;{}]+)$/){$1.ljust(f.lines.map(&:size).max)+$2}

I can't get it to work, can you help me out?

@Pavel try this on for size.

Doesn't work with this

@Pavel thanks for letting me know. The two issues I saw after piping into file were A. an indented catch statement, and B. a semicolon that was indented way too much, on the longest line in the code. I think I know just the thing I need to fix it, give me a sec. (Also, I updated the spec to mention it can't handle tabs, and your file has tabs.)

Does it have tabs? I just did a find and replace on it, and it made 0 changes.

The raw hastebin that I copied off of has many tabs.

@Pavel it should be fixed now.

Perl, 90 bytes
88 bytes of code + -p0 flags.
\@a[y///c]for/.*/g;s/(.*?)\K[{};]$/$"x(@a-$1=~y%%%c).$&/gme;1while s/ *
 *([{};]+)$/$1/m

Try it online!
Short explanations:
\@a[y///c]for/.*/g; counts the length of the longest line: for each line, it defines the element at index y///c (ie the size of the line) of the array @a. At the end, the max index of @a (ie. the size of @a) is the size of the longest line.
s/(.*?)\K[{};]$/$"x(@a-$1=~y%%%c).$&/gme places the {}; characters at the end of the lines.
1while s/ *\n *([{};]+)$/$1/m makes makes the braces on empty lines go on the line above.
Thanks to @primo from whom I partially "stole" the beginning of my code from here to count the length of the longest line.

The braces must go back up to the line above if there is only whitespace before them, this answer doesn't do that

@KritixiLithos indeed, it seemed fine before the challenge was reworded (from what I understood from both the challenges and the comments). Anyway, it's fixed now (I already had the code written in my answer in case you didn't notice).

Python 2: 228 Bytes
import re
g=re.search
def b(a):
    s,l="",a.split('\n')
    r=max([len(k)for k in l])
    for k in l:
        n,m=g('[;}{]',k),g('[\w]',k)
        if n:n=n.start()
        if m:m=m.start()
        if n>m and m!=None:s+="\n"+k[:n]+" "*(r-n)
        s+=k[n:]
    print s

Horribly long.  I probably should have started from scratch when I realised lone ;{}s needed to go on the end of the previous lines.

stacked, 133 bytes
'\s+([;{}])' '$1'repl lines{!n'[\s;{}]+$'match''join:n\'$'+del\,}"!tr:$size"!$MAXmap@k{e i:e[' 'k i#rpad]"!}map tr[' 'join]map'
'join

Try it online!I could be heavily overthinking this... but whatevs. I'll look at it again tomorrow. Some nice tips:

"! can often be used in place of map, saving a byte or two, depending on if the next token starts with a word. However, it can only be used when each atom of the array is wanting to be mapped over. It's similar to a deep map.
A space is not needed after a quoted function, so $MAXmap is equivalent to $MAX map, which in turn is equivalent to [MAX] map. (Maps each array to its maximal element.)

JavaScript (ES Proposal), 139 121 bytes

f=
s=>s.replace(/^(.*?)\s*(([;{}]\s*)+)$/gm,(_,t,u)=>t.padEnd(Math.max(...s.split`
`.map(s=>s.length)))+u.replace(/\s/g,``))
<textarea rows=10 cols=40 oninput=o.textContent=f(this.value)></textarea><pre id=o>

Requires Firefox 48/Chrome 57/Opera 44/Safari 10/Edge 15 for padEnd. Edit: Saved 18 bytes thanks to @ValueInk.

Do you really need to run s.replace(r,\$1`)` when calculating the line length? Any amount of reasonable right-padding should be enough, so counting line length with the semicolons and brackets should be fine.

PHP, 201 194 185 172 167 bytes
foreach($f=file(f)as$s)$x=max($x,strlen($a[]=rtrim($s,"{} ;
")));foreach($a as$i=>$c)echo str_pad($c,""<$c|!$i?$x:0),trim(substr($f[$i],strlen($c))),"
"[""==$a[$i+1]];

takes input from file f; assumes single byte linebreaks and no tabs; preserves blank lines.

+2 bytes for delimiting whitespace: append +1 to the second str_pad parameter.
-6 bytes if it was guaranteed that no code line consists of a single 0:
Remove ""< and replace ""== with !.

breakdown
foreach($f=file(f)as$s)             // loop through file
    $x=max($x,strlen(                   // 3. set $x to maximum code length
        $a[]=                           // 2. append to array $a
            rtrim($s,"{} ;\n")          // 1. strip trailing whitespace and braces
    ));
foreach($a as$i=>$c)echo            // loop through $a
    str_pad($c,                         // 1. print code:
        !$i|""<$c                       // if first line or not empty
        ?$x                             // then padded to length $x
        :0                              // else unpadded (= print nothing)
    ),
    trim(substr($f[$i],strlen($c))),    // 2. print braces
    "\n"[""==$a[$i+1]]                  // 3. if next line has code, print newline
;

Are you sure you need to escape the {} braces in the regex?

@KritixiLithos Probably not; but I found a shorter approach anyway.

Java 8, 312 305 bytes
s->{String t="([;{}]+)",z[],r="",a;s=s.replaceAll(t+"[\\s\\n]*","$1").replaceAll(t,"$1\n");int m=0,l;for(String q:s.split("\n"))m=m>(l=q.length())?m:l;for(String q:s.split("\n")){z=q.split("((?<="+t+")|(?="+t+"))",2);for(a="",l=0;l++<m-z[0].length();a+=" ");r+=z[0]+a+(z.length>1?z[1]:"")+"\n";}return r;}

Explanation:
Try it here.
s->{                                  // Method with String parameter and String return-type
  String t="([;{}]+)",                //  Temp regex-String we use multiple times
    z[],a,                            //  Temp String-array and temp String
    r="";                             //  Result-String
  s=s.replaceAll(t+"[\\s\\n]*","$1")  //  We replace all ;{} in the input with zero or more whitespaces/newlines to just ;{}
     .replaceAll(t,"$1\n");           //  and then add a single newline after each group of ;{}
  int m=0,l;                          //  Two temp integers
  for(String q:s.split("\n"))         //  Loop (1) over the lines
    m=m>(l=q.length())?m:l;           //   To determine the longest line
                                      //  End of loop (1)
  for(String q:s.split("\n")){        //  Loop (2) over the lines again
    z=q.split("((?<="+t+")|(?="+t+"))",2);
                                      //   Split on groups of ;{}, but keep them in the array
    for(a="",l=0;l++<m-z[0].length();a+=" ");
                                      //   Amount of spaces we should add
    r+=z[0]+a+(z.length>1?z[1]:"")+"\n";
                                      //   Append this line to the result-String
  }                                   //  End of loop (2)
  return r;                           //  Return the result-String
}                                     // End of method

Hey, I'm commenting on this answer, but it applies to many others of yours.  We currently require lambda parameters to have types in Java.

@NathanMerrill Was afraid the day of judgement would come. Jk, will add it from now on and I've edited my answer, thanks. ;)


text:
Convert between Lambda Calculus Notations
The lambda calculus is a system of functional programming. Lambda calculus consists of variables, abstractions, and applications.
A variable is simply a name denoting a function parameter. It is a single letter. An abstraction is a "function literal" of sorts, it consists of a backslash \ followed by a variable name, and then an expression, which is the function body. For example, the function \x.x is a function which takes an argument x and returns x, a.k.a. the identity function. Abstractions can also return other abstractions. For example, \x.\y.x is a function which takes an argument x and returns a new function that returns x.
There is also application. In application, you remove the header on the first value and substitute all instances of the function's argument with the value it is applied to. For example, to apply \x.xx to \y.y, substitute all x's with \y.y's, yielding (\y.y)(\y.y) (Parenthesis may need to be added for clarification.) Applications are denoted in an expression by writing the two values next to each other, where the first is the function to apply and the second is the argument to apply to. For example, you can write xy to apply x to y. However, you may need parenthesis (for example in a(bcd) or y(\x.xx).
The first lambda calculus notation is the one I just described.
\f.(\x.xx)(\x.f(xx))

The second lambda calculus notation does not need parenthesis. It matches the following grammar:
<expression> ::= <variable> || <abstraction> || <application>
<abstraction> ::= "\" <variable> <expression>
<application> ::= "`" <expression> <expression>

Here, a <variable> can be any uppercase or lowercase letter. This is an example of an expression in the second notation:
\f`\x`xx\x`f`xx

Your task is to write a program that takes a lambda calculus expression in the first notation and outputs it rewritten in the second notation.
Specifications

Every variable name is 1 letter.
Abstractions in the first notation go as far as possible, and application goes left to right: d(abc) -> `d``abc.
You do not have to deal with free/bound variables and scoping.

Test Cases
\a.a                                  -> \aa
(\x.xx)(\x.xx)                        -> `\x`xx\x`xx
\x.\y.\z.xz(yz)                       -> \x\y\z``xz`yz
(\S.\K.SKK)(\x.\y.\z.xz(yz))(\p.\q.p) -> ``\S\K``SKK\x\y\z``xz`yz\p\qp

You might need to explain what lambda calculus is. You say "the standard, human readable one", but I don't know what it means. Or if that's not important to the challenge, at least explain the format(s). (What's an "abstraction"?, what are free bounds and scoping?, what is "application"?) You make a lot of assumptions about what people know/understand.

Haskell, 211 197 186 bytes
(Saved 10 bytes by using interact as suggested by @Challenger5, and one more by not having a final newline.)
m(')':r)=([],r)
m s|(a,u)<-e s,(b,v)<-m u=(a:b,v)
f s|(a,r)<-m s=(tail(a>>"`"):a>>=id,r)
e('\\':v:_:s)|(a,r)<-f s=('\\':v:a,')':r)
e('(':s)=f s
e(v:s)=([v],s)
main=interact$fst.f.(++")")

Initially I had a function to perform the whole transformation, but now that is inlined into the main function which makes it a complete program. Dealing with a complete program instead of using a function String -> String at the interpreter also avoids the need to type and read double backslashes. The other functions follow the (simplified) pure functional parsing pattern of returning a parsing result and the unparsed rest of the string. f parses a list of expressions (possibly a multiple application) . It uses a helper function m  that also parses a list of expressions and has a list of parses as result. e handles the remaining cases: lambdas, parenthesized expressions, and variables. Instead of generating a parsing tree, we directly generate the desired output.
Try it online!
Using interact ruined clean I/O behaviour. If you don't use the TIO link but run it at the  command line of your computer, you have to make sure that there is no trailing whitespace, it would be treated like a variable. You can do something like echo -n '\f.(\x.xx)\x.f(xx)' | ./prog. Alternatively, you could replace the last line by the previous version main=getLine>>=putStrLn.fst.f.(++")").

I think you can use interact instead of getLine and putStrLn.

That would (usually) give me an additional \n that I'd need to take care of, and I think I wanted a "normal" input ending with return instead of EOF.

I/O without a newline is fine with me.

And I thought it would need explanation, which I wanted to avoid. I've done it now.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
A day at the beach
Inspired by this challenge

Goal:
The goal is to draw waves crashing onto a beach.
Input:
You will be given 3 integers (in whatever format you want) as input.
The first integer will be the length of the drawing
The second integer will be the index of the sandbar, where the waves start to crest (at least 3 spaces from beach)
The third integer will be the spacing between waves (at least 3, can be greater than length of drawing, in which case you only draw one wave)
Output:
The output will be a box of characters which shows the waves crashing into the beach. The drawing should end when the first wave has completed crashing into the beach.
At first, the wave is shown as a swell (_-_).
As the wave passes the sandbar, it starts to crest (/c_).
Finally, the wave crashes into the beach (/c. => _-_ => ___ => __. ).
Examples:
Input: 14 4 6
Output:
-___________..
_-__________..
__-_________..
___-________..
___/c_______..
____/c______..
-____/c_____..
_-____/c____..
__-____/c___..
___-____/c__..
___/c____/c_..
____/c____/c..
-____/c____-_.
_-____/c_____.
__-____/c___..

Input: 10, 2, 11
Output:
-_______..
_-______..
_/c_____..
__/c____..
___/c___..
____/c__..
_____/c_..
______/c..
_______-_.
_________.
________..

Input:  6 0 3
c___..
/c__..
_/c_..
c_/c..
/c_-_.
_/c__.
c_/c..

Rules:
Standard Loopholes apply
This is code-golf so shortest code wins

· is not ASCII, which may exclude some languages. Can it be replaced by .?

@LuisMendo The beach is supposed to be the ASCII period. The example of wave crashing into the beach is due to the period being practically invisible otherwise.

Which leads me to the opposite question: can we use · instead of the ASCII period? (It's actually a rather big win in my code.)

Using either or should be fine. The idea is that the code output appears consistent with the example outputs.

JavaScript (ES6), 250 243 bytes
This code is assuming code page #1252 and is using the · character (0xB7). Takes input as 3 distinct parameters (a,b,c).
(a,b,c,R=n=>'_'.repeat(n-2),s=(x=b?'-':'c')+R(a-1)+'··')=>(g=j=>s+`
`+((F=`__·$,_-_·,/c··,-__,^${C=R(b>2?b:2)}__-,/c_,^c_,^_${S=R(c)},_··,___·,_-_·,_-_,${C}/c_,_/c,/c,${x+S}`.split`,`).map((r,i)=>s=i&8?s:s.replace(RegExp(r,'g'),F[i+8])),j--?g(j):''))(a)

How it works
This code starts with a string such as -______·· and applies successive regular expressions on each iteration to animate the waves.
For instance -__ is replaced with _-_.
At first, it looked like a reasonable idea. However, the fact that the string may start with a c (like it does in the 3rd test case) makes things significantly more complicated.
Test cases

f =

(a,b,c,R=n=>'_'.repeat(n-2),s=(x=b?'-':'c')+R(a-1)+'··')=>(g=j=>s+`
`+((F=`__·$,_-_·,/c··,-__,^${C=R(b>2?b:2)}__-,/c_,^c_,^_${S=R(c)},_··,___·,_-_·,_-_,${C}/c_,_/c,/c,${x+S}`.split`,`).map((r,i)=>s=i&8?s:s.replace(RegExp(r,'g'),F[i+8])),j--?g(j):''))(a)

console.log(f(14, 4, 6))
console.log(f(10, 2, 11))
console.log(f(6, 0, 3))

Batch, 273 243 bytes
@echo off
set f=for /l %%i in (0,1,%1)do call
set s=set b=
%s%..
%f% %s%_%%b%%
%f%:c %%i %2 %3
exit/b
:c
set/aw=%1%%%3
if %w%==0 %s%__-%b:~3%
if %w%==%2 %s%%b:_-=/c%
%s%_%b:~0,-4%%b:~-3%
%s%%b:__. =_.. %
%s%%b:/.=-_%
echo %b:~3%

Note: Trailing space on line 4. If only the two beach characters were different, I could save 3 bytes and actually beat JavaScript!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Attack, Decay, Sustain, Release
Sound synthesizers use envelope generators to control how certain parameters of the sound (such as overall loudness) change with time. In many synthesizers an envelope is defined by four parameters, as represented in the following figure from Wikipedia:

Attack time (A): time taken for the envelope to reach its maximum level, starting from zero, when the key is first pressed.
Decay time (D): time taken for the envelope to reach the specified sustain level.
Sustain level (S): level which is maintained, after the initial attack and decay, for as long as the key is being pressed.
Release time (R): time taken for the envelope to reach zero when the key is released.

The challenge
Input the four parameters A, D, S, R and plot the envelope.
Parameters will be integer values from 0 to 127.
The maximum level (reached at the end of the attack phase) will be assumed to be 127.
The horizontal segment at the sustain level will be assumed to have duration 64 (in the actual sound this duration is not fixed, but is determined by the amount of time that the key is held).
Format and further details
The output should be an image in raster or vector format. If it's raster, the polygonal line should occupy at least 50 pixels vertically an horizontally.
The image can be either displayed or produced as a file in a standard image format. The file can be written to disk, or its exact contents can be output, either to STDERR or as function return argument.
The graph need only contain the polygonal line that defines the envelope. The scale of each axis can be freely chosen. Other elements such as axis lines, numeric labels or line colors are optional.
Input means and format are flexible as usual. For example, you can take the four numbers in any order, or an array containing them. A program or a function can be provided. Standard loopholes are forbidden.
Shortest code in bytes wins.
Test cases
Input is in the format [A D S R]. Note that the scale is different in each figure (in accordance with the rule that scale can be freely chosen)
[15 30 70 40]

[64 64 64 64]

[0 10 50 80]

[0 0 90 80]

[5 50 0 0]

[5 50 0 80]

[24 32 127 48]

I was expecting a more simian challenge from the title!

@Ben That reference was intended too :-) I love Sleep deprivation!

MATL, 31 22 bytes
Oii64ivYsO127itO5$h&XG

Accepts four separate inputs ordered as A, D, R, S
Try it out at MATL Online
Explanation
0   % Push a literal 0 to the stack
ii  % Grab the first two inputs
64  % Push the number literal 64 to the stack
i   % Grab the third input
v   % Vertically concatenate all values
Ys  % Compute the cumulative sum
0   % Push the number literal 0 to the stack
127 % Push the number literal 127 to the stack
i   % Grab the fourth input
t   % Duplicate the fourth input
O   % Push the number literal 0 to the stack
5$h % Concatenate the last 5 elements on the stack
&XG % Plot the result using the first array as x and second array as y

TikZ, 195 193 181 177 172 167 163 160 159 bytes
Thanks to David Carlisle for his helpful answer here
\documentclass[tikz]{standalone}\begin{document}\tikz\def~#1{\typein[#1];}~\a~\s~\d~\r\def\u{)--(\a+\d}\draw(,)--(\a,127\u,\s\u+64,\s\u+\r+64,);\end{document}

Yes, you heard right TikZ.
Explanation
This uses a couple of techniques to achieve its goal.  The first thing is input.  Most people might not know that LATEX can take input.  Well it can.  This is achieved with the command \typein.  This will halt the compiler and request input from the user as assign it to a variable.
The other main technique is the use of \def.  \def in Tikz is absurdly powerful.  It essentially defines a piece of code and pastes it everywhere you call the variable.  In this code we define two things \typein[#1]{} so that we can assign our variables golfily and )--(\a+\d because this code shows up a bunch of times in the ungolfed version.
Here are two versions of the code (without the wrapper):
Golfed:
\documentclass[tikz]{standalone}\begin{document}\tikz\def~#1{\typein[#1];}~\a~\s~\d~\r\def\u{)--(\a+\d}\draw(,)--(\a,127\u,\s\u+64,\s\u+\r+64,);\end{document}

Ungolfed:
\typein[\a]{}\typein[\s]{}\typein[\d]{}\typein[\r]{}\draw(0,0)--(\a,127)--(\a+\d,)--(\a+\d+64,)--(\a+\d+\r+64,0);

Image:
Since I cannot upload a pdf image directly, and converting it to any other format seems to cause the line to disappear altogether, here is what an image might look like when opened in Preview (input for this image is [64 64 64 64]):

As you can see it is very thin.  However because it is a PDF image and not a raster image does not have to comply with thickness requirements.

I sincerely admire the fact that you know TikZ so well that it's the first solution that comes into your mind. (And if it wasn't, that's what legend will remember)

Doesn't input tikz\begin{document} work?

how about pictures?

How do you actually render this? pdflatex adsr.tex doesn't seem to work. — Oh wait, it does work, I just didn't expect it would request interactive input!

@WheatWizard imagemagick can convert PDF reasonably well if you do it right

@WheatWizard maybe upload that PDF somewhere and I may try to deal with it…

@WheatWizard see proposed edit. The image looks strange tbh, not like the lines are thin, they are instead "squared" and very little contrast (which I fixed by -normalize option)
Did you use some lossy compression in PDF? like jpeg, etc

Let us continue this discussion in chat.

Python 2, 83 80 79 bytes
from turtle import*
def f(A,D,S,R):X=A+D+64;map(goto,[A,A+D,X,X+R],[127,S,S,0])

Try it online (83-byte version, because it runs online)
Note that certain outputs may not be completely visible using Trinket, because of the way the canvas works. You'll need to download and install Python if you want it to work better.
Ungolfed:
from turtle import*
A,D,S,R=input()
goto(A,127)
goto(A+D,S)
goto(A+D+64,S)
goto(A+D+64+R,0)

This version doesn't work in Trinket, because Trinket doesn't support value unpacking of input.

You can use map in Python 2: lambda A,D,S,R:map(goto,[A,A+D,A+D+64,A+D+R+64],[127,S,S,0])

@xnor I get SuspensionError: Cannot call a function that blocks or suspends here on line undefined in main.py on Trinket. Have you confirmed that it works? I'm not sure if the error is unique to Trinket or not.

Works for me in 2.7.12.

@xnor Mmk, thanks. It's probably a limitation in Skulpt.

I submitted a simpler version of this program as an example to the Skulpt github repo, and they thought it was a nice find. Hopefully they'll be able to fix it, but the pace of their "turtle sprint" seems to be more of a walk.

Mathematica, 61 58 bytes
ListLinePlot[{Accumulate@{0,##3,64,#2},{0,127,#,#,0}}]&

 is the operator for Transpose and is rendered as a superscript T by Mathematica.
Takes the arguments in the order S, R, A, D and returns a vector graphics object.
Results for all seven test cases:

Click for larger version.

That was quick!

+1 for teaching me ListLinePlot :) And there's a ListStepPlot as well—so useful!

R, 66 63 bytes
function(A,D,S,R)plot(cumsum(c(0,A,D,64,R)),c(0,127,S,S,0),"l")

Displays the image, with axis labs being cumsum(c(0,A,D,64,R)) and c(0,127,S,S,0), as well axis lines and numeric labels.
Thanks to @Zahiro Mor for shaving off 3 bytes !
Previous answer :
function(A,D,S,R)plot(c(0,A,A+D,b<-A+D+64,b+R),c(0,127,S,S,0),"l")

you can use cumsum(c(0,A,D,64,R))  to replace the first term in the plot. with cumsum you will not need the b trick and still shave 3 bytes :)  function(A,D,S,R)plot(cumsum(c(0,A,D,64,R)),c(0,127,S,S,0),"l")

Matlab, 50 bytes
@(A,D,S,R)plot(cumsum([0,A,D,64,R]),[0,127,S,S,0])

This yields an anonymous function "ans" that has to be called as ans(A,D,S,R).

JavaScript (ES6) + HTML, 126 + 23 = 149

c=O.getContext`2d`;c.moveTo(a=0,z=O.height=128);g=(y,x=prompt())=>c.lineTo(a+=+x,y)||g;g(0)(s=z+~prompt())(s,64)(z);c.stroke()
<canvas id=O width=512>

Takes input one at a time in the order A, S, D, R.

JavaScript (ES6), 114 111 bytes

f=(a,d,s,r)=>`<svg width=446 height=128><path stroke=red fill=none d=M0,127L${a},0l${d},${127-s}h64l${r},${s}>`

<input type=number value=0 min=0 max=127 id=a><input type=number value=63 min=0 max=127 id=d><input type=number value=127 min=0 max=127 id=s><input type=number value=0 min=0 max=127 id=r>
<svg width=446 height=128><path stroke=red fill=none d=M0,127L0,0l63,0h64l0,127 /></svg>

Returns an SVG image suitable for innerHTML. Add 18 bytes for valid XML.

It's great how the figure is updated in real time!

This is great, I should learn SVG syntax sometime. Perhaps add default values to the <input>s?

@ETHproductions Did you have any particular defaults in mind? (Given that setting defaults won't actually trigger the initial graph anyway...)

I was thinking perhaps just 64,64,64,64. Normally I'd hardcode the correct output for the default input, but I see how that would be difficult here...

Haskell, 112 110 bytes
import Graphics.Gloss
(a#d)s r=display(InWindow""(600,300)(0,0))red$line$zip(scanl(+)0[a,d,64,r])[0,127,s,s,0]

Usage example: (0#10) 50 80.

This uses the Gloss library. The display function expects a window to plot in (here: a window without title (""), size 600x300, position (0,0) on desktop), a background color (red) and picture witch is a line along the path made by zipping the cumulative sum of [0,a,d,64,r] = [0,a,a+d,a+d+64,a+d+64+r] as the x coordinates and [0,127,s,s,0] as the y coordinates.
Edit: Thanks @xnor for 2 bytes!

Should be shorter to write scanl(+)0[a,d,64,r]

Processing, 134 108 + 14(call to size) = 148 122 bytes
First we need a call to size somewhere in the program so that the output will fit in the window (default at 100x100).
size(400,400);

And here's the actual function:
void g(int a,int b,int c,int d){line(0,127,a,0);line(a,0,b+=a,c=127-c);line(b,c,b+=64,c);line(b,c,b+d,127);}

Call it like f(15,20,70,40);
Screenshot
15, 20, 70, 40

My newer answer is more straightforward than the older answer, but I like the older one more (even if it is bigger).
Old answer (148 bytes)
size(400,400);

and the two functions
void f(int[]v){translate(0,127);l(v[0],-127);l(v[1],127-v[2]);l(64,0);l(v[3],v[2]);}void l(int x,int y){line(0,0,x,y);translate(x,y);}

Call it like f(int_array_containing_values); and the result will look something like: f(new int[]{15,20,70,40});

PHP, 149 130 bytes
[,$a,$d,$s,$r]=$argv;imagepolygon($i=imagecreatetruecolor(446,127),[0,127,$a,0,$d+=$a,$s,$d+=64,$s,$d+$r,127],5,999);imagepng($i);

takes input from command line arguments, writes image (PNG with graph blue on black) to stdout. Requires PHP 7.1 or later.
usage e.g.
# any OS with ImageMagick:
php -r '' <parameters> | display

# linux with feh:
php -r '' <parameters> | feh

+4 bytes for older PHP: Replace [,$a,$d,$s,$r] with list(,$a,$d,$s,$r).

There is a small hack in there: instead of using imageopenpolygon to hide the base line, the finishing polygon line is drawn outside the canvas. (y=127 would only display on an image with height >= 128.)
I could have saved more with color 99 or 9 instead of 999; but those are pretty hard to see on black. :)

SmileBASIC, 90 bytes
INPUT A,D,S,R
B=A+D+64W=#Y-S
GLINE.,#Y,A,0GLINE A,0,A+D,W
GLINE A+D,W,B,W
GLINE B,W,B+R,#Y

Bash + grace, 70 bytes
t=$[$1+$2]
echo "0 0
$1 127
$t $3
$[t+64] $3
$[t+64+$4] 0">f
xmgrace f

The script writes to file f the coordinates of each point, and xmgrace (the GUI version) reads the file and displays the plot using lines by default.
Run:
./plot_ADSR.sh 15 30 70 40

Output: (print screen)

I think this can be done directly by a grace script, if it can accept input, but I'm not familiar with its syntax. I'll look into it.
Explanation:
t=$[$1+$2]          # store the value of (A+D) for later usage
echo "0 0           # start writing the coordinates to file "f", first the origin
$1 127              # then (A, 127)
$t $3               # then (A + D, S)
$[t+64] $3          # then (A + D + 64, S)
$[t+64+$4] 0">f     # then (A + D + 64 + R, 0)
xmgrace f           # call xmgrace to plot the generated XY file

Go, 947 915 506 bytes
This is far from optimized, trying to learn the language while participating in these questions. Feel free to point out what I can do.

Condensed:
package main;import (."os";."image";k"image/png";c"image/color";."strconv";."math");func main(){g:=NewRGBA(Rect(0,0,127*4,127));a,_:=ParseFloat(Args[1],4);d,_:=ParseFloat(Args[2],4);s,_:=ParseFloat(Args[3],4);r,_:=ParseFloat(Args[4],4);z:=[5][]float64{{0,0},{a,127},{a+d,s},{a+d+64,s},{a+d+64+r,0}};for i:=1;i<len(z);i++{v,w,x,y:=z[i-1][0],z[i-1][1],z[i][0],z[i][1];m:=(y-w)/(x-v);t:=y-m*x;for v<=x{g.Set(int(Ceil(v)),127-int(Ceil(w)),c.RGBA{0,0,0,255});v+=.01;w=m*v+t}};f,_:=Create("o.png");k.Encode(f,g)}

Uncondenced:
package main

import (
    ."os"
    ."image"
    k"image/png"
    c"image/color"
    ."strconv"
    ."math"
    "fmt"
)

func main(){
    g := NewRGBA(Rect(0, 0, 127*4, 127))

    a, _ := ParseFloat(Args[1], 4)
    d, _ := ParseFloat(Args[2], 4)
    s, _ := ParseFloat(Args[3], 4)
    r, _ := ParseFloat(Args[4], 4)

    z := [5][]float64{{0,0},{a,127},{a+d,s},{a+d+64,s},{a+d+64+r,0}}
    for i:=1;i<len(z);i++{
        v,w,x,y:=z[i-1][0],z[i-1][1],z[i][0],z[i][1]
        m:=(y-w)/(x-v)
        t:=y-m*x
        for v<=x{
            g.Set(int(Ceil(v)),127-int(Ceil(w)), c.RGBA{0,0,0,255})
            v+=.01
            w=m*v+t
        }
    }
    f,_:=Create("o.png")
    k.Encode(f,g)
}

@LuisMendo it is. By default 0,0 is top left. Ill inverse everything as soon as I can.

Did you also update the golfed version and its byte count?

I never coded in go, so I don't know. Users here golf their code manually because they can save more bytes than a general minifier. Bad coding practices and tricks are welcomed here. For ex, wouldn't replacing struct objects with variables (like l1x, l1y, l1X, l1Y) be golfier perhaps?

@rugdealer This may help, in case you haven't seen it

Lost almost 400 bytes thanks to your link @LuisMendo

@seshoumara you're right. I was able to lose a lot from removing the structs.

@rugdealer Wow, that's a lot \o/

Very good, keep at it. For example, why do you work with floats and need Ceil if the input is integer numbers and a few coordinates are just a sum of ints? Also, Rect(0,0,127*4,127) can be Rect(0,0,508,127), and a file on Linux doesn't need an extension Create("o").

@seshoumara, seeing that Go does not provide a draw line function, I need to do it myself. If for example I have coords (0,0) and (1,3) I will be unable to draw the line that links them both with just ints. I use floats instead to be able to calculate the points in between, then I do a rough estimate as to where those points would be as an int. Unsure if what I'm saying is clear. In any case, this allows me to draw complete lines and not just dots. And yes I forgot that little detail for linux. Thanks!

Ouch, that's why. Maybe ask in the chat or check on the PPCG meta about using external libraries. I never needed them. I googled this as one such example for go.

dc, 120 bytes
Initially I thought I can't answer in dc, but I see that printing the syntax of a vector image is allowed.
?sR127r-sS[<svg><path d="M0 127 L]nrdn[ 0 L]n+dn32PlSn[ L]n64+dn32PlSn[ L]nlR+n[ 127" fill="none" stroke="red"/></svg>]p

The code calculates the translated coordinates of each point and generates the SVG syntax for the plot. Since an image editor has the origin at the top-left corner, I had to subtract the y values from height, 127 in this case, so that the image is shown as if the origin is at the bottom-left corner.
Run example: or Try it Online!
dc -f plot_ADSR.dc <<< "15 30 70 40"

Output:

<svg><path d="M0 127 L15 0 L45 57 L109 57 L149 127" fill="none" stroke="red"/></svg>

To display the image plot, save that exact output to a file and open it with Gimp, for example, or enter the text in an html page as I did above.
Explanation: dc is a reverse-polish desk calculator stack language
The script is a long concatenation of the SVG syntax string. The keyword M stands for move to coordinate and L stands for draw line from current position to given coordinate.
?                           # read input (in reverse order by default). Stack: RSDA
sR                          # pop top value, store it in register 'R'. Stack: SDA
127r-sS                     # push 127, swap top 2 values, pop them and push
                            #subtracting result, save it to 'S', pop it. Stack: DA
[<svg><path d="M0 127 L]n   # [..]n print string (push then pop). Stack: unchanged
rdn                         # swap, duplicate top, print (A) and pop it. Stack: AD
[ 0 L]n                     # printing
+dn                         # pop top 2 values, push addition result, duplicate it,
                            #print and pop it. Stack: (A+D)
32P                         # print a space
lSn                         # push value from register 'S', print and pop it.
                            #Stack: unchanged
[ L]n                       # printing
64+dn                       # push 64, pop top 2 values, push addition result,
                            #duplicate it, print and pop it. Stack: (A+D+64)
32PlSn[ L]n                 # print space, print register 'S', more printing
lR+n                        #push value from register 'R', pop top 2 values, push
                            #addition result, print it and pop it. Stack: empty
[ 127" fill="none" stroke="red"/></svg>]p   # printing

Processing, 111 bytes
size(400,128);line(0,127,a,0),line(a,0,a+d,127-s),line(a+d,127-s,a+d+64,127-s),line(a+d+64,127-s,a+d+64+r,127);

Used a simpler method of input compared to user41805.
Output (formatted)
0,0,90,80

0,10,50,80

5,50,0,0

5,50,0,80

15,30,70,40

24,32,127,48

64,64,64,64

Ungolfed code with formatting
void settings() {
  //size adjusts according to params
  size(a+d+64+r, 129);
}
void setup() {
  translate(1,0);
  background(255);
  strokeWeight(3);

  //axes
  line(0,127,600,127);
  line(0,0,0,127);

  //graph
  stroke(53,113,9);
  line(0,127,a,0);
  stroke(228,77,40);
  line(a,0,a+d,127-s);
  stroke(26,39,232);
  line(a+d,127-s,a+d+64,127-s);
  stroke(110,27,109);
  line(a+d+64,127-s,a+d+64+r,127);

  //save to file
  save("a"+a+"d"+d+"s"+s+"r"+r+".png");
}
int a=24,d=32,s=127,r=48;

This program will save your images to disk in the same folder.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
A sequence of sums of integers that aren't in the sequence
Background
Consider a sequence defined as follows:

The first element is 0;
The second element is 4;
From the third element onwards, its value can be calculated by:

Taking the set of integers from 0 up to the previous element of the sequence (inclusive or exclusive, it doesn't matter);
Removing any integers that have already appeared earlier in the sequence from the set;
Adding together the remaining elements of the set; that's the value you want.

Interestingly, this sequence doesn't seem to be on OEIS yet.
The task
Write a program or function which takes an integer n as input, and outputs the nth element of the sequence.
Test cases
The first few elements of the sequence are:

0
4
6 (1+2+3)
11 (1+2+3+5)
45 (1+2+3+5+7+8+9+10)
969 (1+2+3+5+7…10+12…44)
468930 (1+2+3+5+7…10+12…44+46…968)

Clarifications

Your program should in theory be able to handle arbitrary n if run on a variant of your language that has unboundedly large integers and access to an unlimited amount of memory. (Languages without bignums are unlikely to be able to get much beyond 468930, but that's no excuse to hardcode the answers.)
You may choose either 0-based or 1-based indexing for the sequence (e.g. it's up to you whether n=1 returns the first element, n=2 the second element, and so on; or whether n=0 returns the first element, n=1 the second element, and so on).
There are no requirements on the algorithm you use, nor on its efficiency; you may implement the definition of the sequence directly (even though it's really inefficient), and you may also implement a different algorithm which leads to the same results.

Victory condition
This is code-golf, so the shortest correct program, measured in bytes, wins.

Why not allow infinite output instead of taking input?

@JanDvorak: Because that forces all programs to use algorithms that generate every term; this method of writing the question leaves it up to the answerers whether they want to do that, or whether they want to use a closed-form formula (assuming there is one). So it gives more of a choice of strategies in solving the question.

I'd assume the sequence isn't there because 0,4 is a strange offset

@boboquack With (0,3), (0,2), (1,4) or similar variations, the sequence would be constant after a few terms.

Does the [math] tag make sense for this?

@mbomb007: I originally tagged with just [tag:code-golf] and [tag:sequence]. The current number of tags seems somewhat excessive, but I don't really want to get into an edit war, so I'm staying out of it.

Jelly, 13 12 9 bytes
rSạo4¥ð@¡

Uses 0-based indexing.
Try it online!
How it works
rSạo4¥ð@¡  Main link. No arguments. Implicit argument: 0

      ð    Collect everything to the left into a chain and start a new, dyadic one.
           The arity of the first chain is unknown at this point, as it isn't
           prefixed by ø, µ, or ð.
       @   Swap the arguments of the first chain. Swapping  arguments is only
           implemented for dyadic links, so this makes the chain dyadic.
        ¡  Read an integer n from STDIN and execute the chain n times. Taking the
           argument swap into account, the chain is executed first with 0 as left
           and right argument, then with the previous right argument as left
           argument and the previous return value as right argument.
           The return value of the last call is the return value of the quicklink
           and becomes the implicit output.

           Let's call the left argument x and the right argument y.
r            Range; yield [x, ..., y].
 S           Compute the sum of all integers in the range.
     ¥       Convert the two atoms to the left into a dyadic chain, and call that
             chain with arguments x and y.
   o4          Take the logical OR of x and 4, replacing a 0 with 4 and leaving
               positive integers untouched.
  ạ          Take the absolute difference of the sum to the left and the result of
             the logical OR to the right.

Python, 66 60 bytes
Thanks to @Dennis for shaving off 6 bytes!
f=lambda n:n>2and(f(n-1)-~f(n-2))*(f(n-1)-f(n-2))/2or(5-n)*n

It's not the golfiest piece of code ever, but it uses a formula that I made:

Where x on the right-hand side is f(n - 1), and y is f(n - 2).
Explanation:
The sum of continuous integers from a to b (inclusive) can be described by this formula:
amount * average

Where amount (amount of numbers) is described like so:
((a - b) - 1)

And average (the average of all numbers) is described like so:
(a + b) / 2

So the full formula is now:
  ((a - b) - 1)(a + b) / 2
= (a - b - 1)(a + b) / 2

The way we implement this formula into the final formula is to substitute a for f(n - 1), b for f(n - 2), which basically calculates the sum of all of the new terms, and add another f(n - 1) (which is now a) on, which is the sum of all previous terms.
Combining that together, we get:
  a + ((a - b - 1)(a + b) / 2)
= a + ((a^2 + ab - ab - b^2 - a - b) / 2)
= a + ((a^2 - b^2 - a - b) / 2)
= (a^2 - b^2 - a - b + 2a) / 2
= (a^2 - b^2 + a - b) / 2
= ((a + b)(a - b) + (a - b)) / 2
= (a + b + 1)(a - b) / 2

Replace a with x and b with y, and hey presto, you have to formula above.

Mathematica, 49 48 bytes
±2=4;±1=0;±n_:=Tr@Range@±(n-1)-Tr@Array[±#&,n-1]
(* or *)
±2=4;±1=0;±n_:=-Tr@Array[(k=±#)&,n-1]+Tr@Range@k

Uses CP-1252 encoding. Defines function PlusMinus (±). 1-indexed.
Explanation
±2=4;±1=0;±n_:=Tr@Range@±(n-1)-Tr@Array[±#&,n-1]

±2=4;±1=0;                                        (* Define ±1 and ±2 *)
          ±n_:=                                   (* ±n equals ... *)
               Tr@Range@±(n-1)                    (* Sum of (1, 2, ..., ±(n-1)) ... *)
                              -Tr@Array[±#&,n-1]  (* Minus the sum of previous terms *)

Python 2, 58 54 50 bytes
r=t=0
exec'r,t=t+r*~-r/2or 4,t-r;'*input()
print r

Try it online!

Oasis, 11 bytes
Code:
+>bc-*2/640

Explanation:
To visualize the relation of fn, let's take the example f5. To calculate f5, let's take a look at the following sum:
1 + 2 + 3 + 5 + 7 + 8 + 9 + 10
The bold part is just the same as f4. The 7 + 8 + 9 + 10 part is the range [fn-2 + 1, fn-1 - 1]. That makes the formula fn-1 + Σ [fn-2 + 1 ... fn-1 - 1] (Wolfram link):
fn = 0.5 × (fn-12 - fn-22 + fn-1 - fn-2)
Which can be rewritten to:
fn = 0.5 × ((fn-1 - fn-2)(fn-1 + fn-2) + (fn-1 - fn-2))
fn = 0.5 × ((fn-1 - fn-2)(fn-1 + fn-2 + 1))
Which is the formula that we will be using in the code:

Code explanation
The 640 part gives us the base cases:
a(0) = 0
a(1) = 4
a(2) = 6

The code that will be executed (which defines a(n)):
+>bc-*2/

+          # Add a(n + 1) and a(n + 2) implicitly
 >         # Add one to get a(n + 1) + a(n + 2) + 1
  b        # Push a(n + 1)
   c       # Push a(n + 2)
    -      # Subtract from each other
     *     # Multiply with the previous result
      2/   # Halve the result

Try it online!

Explanation? This has got me more curious than many of the other answers.

@ais523 I've added an explanation.

Julia, 39 33 32 bytes
!n=n<3?5n-n^2:sum(!(n-2)+1:!~-n)

0-based.
Thanks to @Dennis, saved 6 bytes.
Thanks to @GlenO, saved a byte.
Try it online!
Previous answer 1- based:
!n=n<4?2(n>1)n:sum(!(n-2)+1:!~-n)

Try it online!
Previous ungolfed answer 1-based :
f(n)=n<4?n<2?0:n*2:sum(f(n-2)+1:f(n-1))

Try it online!

To save an extra byte, use n<3?5n-n^2: rather than n<4?2(n>1)n: - note that it switches to using 0-based indexing, though.

@GlenO Thanks, 1 bytes saved!

PowerShell, 84 89 88 87 bytes
$OFS='+'
for($a=0,4;$a.Count-le($n="$args")){$a+=("$(1..$a[-1])"|iex)-("$a"|iex)}$a[$n]

Try it online!
Explanation
0-based indexing. Only works through n = 6 (on my Windows machine it crashes with a stack overflow for n = 7).
Using the same method as JungHwan Min's answer (sum of the range minus sum of previous terms).
Summing a range/array in PowerShell is long, so I'm using a trick of joining a n array with + to create a long expression (like 1+2+3+4...etc) and then sending it through iex (Invoke-Expression).
Since I need to do it twice, instead of using -join I'm setting the special variable $OFS, which stands for output field separator. When you stringify an array, this is the character used to the join the elements; it default to a space. So by setting it to + (once), I can replace something like $a-join'+'|iex with "$a"|iex.
A simple for loop keeps going until the sequence count is less than or equal to the input integer, then I return the $nth element.

@AdmBorkBork very nice! I really think that's worthy of a distinct answer; the method is different enough that it wouldn't feel like my own if I used it.

@AdmBorkBork nice, +1, and I did learn one thing from that: no ; needed after the for loop. Never realized that one before.

JavaScript (ES6), 47 bytes
f=(n,b=4,a=6)=>n?--n?f(n,a,(a+b+1)*(a-b)/2):b:0

Uses the recurrence relation that f(n) = sum(range(f(n-2) + 1, f(n-1) + 1)) for n > 2.

MATL, 17 16 bytes
OKi:"tP:yX-sv]G)

1-based indexing  is used. The code is very inefficient. For n = 6 it already exceeds the memory limit of the online compiler.
Try it online!
How it works
O       % Push 0
K       % Push 4
i       % Input n
:"      % Do the following n times
  t     %   Push a copy of the top array (or number)
  P:    %   Range from 1 to the last element of array
  y     %   Push a copy of the second-top number/array
  X-    %   Set difference
  s     %   Sum
  v     %   Concatenate everything into a column vector
]       % End
G)      % Get n-th entry of the array. Implicity display

For 20 bytes, the following version avoids the memory limitation. But there's still the data type limitation (double type can only guarantee that integers are accurately represented up to 2^53), so results are valid up to n = 8 only.
OKi:"t0)tQ*2/ys-v]G)

Try it online too!

PowerShell, 77 73 bytes
param($n)$a=0,4;1..$n|%{$a+=(0..$a[-1]|?{$_-notin$a})-join'+'|iex};$a[$n]

Try it online!
Implements the algorithm as defined, and is 0-indexed. Input of 6 is too much for TIO to handle.
Sets $a to be an array [0,4]. Loops from 1 up to input $n. In the loop, we take the range of numbers from 0 up to the biggest number we have $a[-1], and use a Where-Object clause |?{...} to pull out only those numbers that are not already present. That array of numbers is -joined together with +s, and then fed to iex (short for Invoke-Expression and similar to eval). That value is then array-concatenated onto the end of $a. Finally, we exit our loop, and take the $nth number in our array. That number is left on the pipeline, and output is implicit.

JavaScript, 123 119 bytes
(a,i=x=y=0)=>{r=[0,4];while(r.length<a){x++;y=0;for(i=0;i<r[x];i++){if(!r.includes(i)){y+=i;}}r.push(y)}return r[a-1];}

Try it online! This solution is 1-based, f(1) => 0.

Haskell, 42 bytes
f 0=0
f 1=4
f 2=6
f n=sum[1+f(n-2)..f$n-1]

Try it online!
This directly implements the recurrence that for n>2, f(n) equals f(n-1) plus the sum of the open interval from f(n-2) to f(n-1) which again is equal to the sum of the half-open interval from f(n-2) to f(n-1) inclusive.
f(0) = 0
f(1) = 4
f(2) = 6 = 1+2+3
f(3) = 11 = 1+2+3+5 = 6 + 5 = 6 + sum]4,6[ = f(2)+ sum]f(1),f(2)[ = sum]f(1),f(2)]
...
f(n) = sum]f(n-2),f(n-1)] = sum[f(n-2)+1,f(n-1)]

Haskell, 31 bytes
m#s=m:s#sum[m+1..s]
((0:4#6)!!)

Usage example: ((0:4#6)!!) 6 -> 468930. Try it online!.
Simple recursion, that keeps track of the maximum element m so far and the next value s.

Whenever I come to a new challenge, someone's always made a haskell answer better than any I could ever make XD

I always arrive at some mathsy challenge, think "Hey finally I can try out haskell!" CMD-F 'Haskell' – oh wait nope, this answer... wait, what? Gives up on haskell

Perl 6,  52 49 44  35 bytes
{(|(0,4 X 0),{[+](^.[0])-.[1],.[0]+.[1]}...*)[$_;0]}

Try it
{(0,(4,0),{[+](^.[0])-.[1],.[0]+.[1]}...*)[$_;0]}

Try it
{(0,(4,0),{[+](^.[0])-.[1],.sum}...*)[$_;0]}

Try it
{(0,4,6,{[+] $^a^..$^b}...*)[$_]}

Try it
Expanded:
{ # bare block lambda with implicit parameter ｢$_｣

  (
    # generate a sequence

    0, 4, 6,      # seed the sequence

    {             # lambda with placeholder parameters ｢$a｣ ｢$b｣
      [+]         # reduce with ｢&infix:<+>｣
          $^a     # n-2
          ^..     # Range that excludes the first value
          $^b     # n-1
    }
    ...           # keep generating values until
    *             # never stop

  )[ $_ ]         # get the value that was asked for (0 based index)
}

Python 2, 85 bytes
def g(n):
 if n<2:return n*4
 s=set(map(g,range(n)));return sum(set(range(max(s)))-s)

Try it online!

Batch, 108 bytes
@if %1==0 echo 0&exit/b
@set/ab=4,a=6
@for /l %%i in (2,1,%1)do @set/ac=(a+b+1)*(a-b)/2,b=a,a=c
@echo %b%

Port of my JavaScript answer.

dc, 47 bytes
?d1-scd/4*dd[d1+*2/r-dsn+dlnlc1-dsc0<x]sxlc0<xp

Works with integers as large as you want, up to the memory capacity of the computer.
Try it online!
0-based indexing, input on stdin, output on stdout. (There's also output on stderr, which is to be ignored.)
Sample runs:
$ for ((j=0;j<12;j++)){ echo -n "$j ";dc -f sumseq.dc <<<"$j";echo;} 2>/dev/null
0 0

1 4

2 6

3 11

4 45

5 969

6 468930

7 109947436950

8 6044219445882138462810

9 18266294354989892462984673364511343859409730

10 166828754731567805766174036610844675771635260155825966927845486666328\
837158267993261860

11 139159167026428037700805570917048711514125048327321592278500415852500\
422178720517080334552793040951056255170819719745908378102737875659900\
61575545777065220385544711322919415

This uses the same algorithm as the following solution in bash, which is (a little) more readable:
Pure bash, 60 bytes
for((n=s=$1?4:0,k=1;k<$1;k++,s+=(n=n++*n/2-s))){ :;}
echo $n

But the bash program only works for inputs up to 7, since it hits integer overflow beyond that.

><>, 43+3 = 46 bytes
Makes use of the formula presented in Adnan's and Qwerp-Derp's answers.
:2(?^&46v
}v?=&:&l<,2*{-$@:}+1+@:{::
*>n;>4

Expects the input to be present on the stack, so +3 bytes for the -v flag.
Try it online!

C# - 74 bytes
int A(int f){int e=4,i=1,s=0;for(;i++<f;)e=e*-~e/2-(s+=e);return f>0?e:0;}

Ungolfed:
int A(int f)
{
    int e = 4,
        i = 1,
        s = 0; // e is the last element, s is the sum of all previous elements
    for (; i++ < f; ) // calculate for indexes 1 through max (don't need the index, just a correct number of loop cycles)
        e = e * -~e / 2 - (s += e); // -~e => (e + 1), higher precedence to remove parentheses
    return f > 0 ? e : 0; //handle input 0 as a special case, which is 0
}

There is probably a way to convert this to a lambda to save even more, or something using the .Aggregate Function. Although currently I have no imports, so maybe it evens out?

Pyth - 15 bytes
ePu+Gs-UeGGQ,Z4

Test Suite.

Stax, 14 bytes
╟s╒π4╬╪♀○¢fΦå┼

Run and debug it
0-indexed.

Vyxal, 14 bytes
04"?(Dtɽ$F∑J)i

Try it Online!


text:
Make a picture into a sliding puzzle
Summary
The goal of this challenge is to create an undone image-version of a 15-puzzle / sliding puzzle also called taquin in french.
Details:
Given an input composed of:

an image,
an integer n,
an other integer r,

your program, or function, or anything else that fits, must output the same image (i.e. same size and format) as the input, but that underwent the following process:

divide the image into n² rectangles,
remove one of those rectangles, randomly,
move a random number of contiguous rectangles from the line/column affected by point (2.) so the hole created is filled and another one is generated in this line/column. This number can be 0 if the blank is in a corner or an edge.

Repeat (3.) r times.
Clarifications:

If you moved rectangles from the line in step (3.), you must move rectangles from the column the in the next repetition,
if you moved rectangles left-to-right in a line-step, they must be moved right-to-left in the next line-step, same for top-to-bottom and bottom-to-top concerning columns,
you may assume that n will be chosen so it divides the lengths of the sides of the picture.

A last point:
An animated .gif showing the whole process are very welcomed.
I propose to use the following picture (which is 1024x768), with n=16 and r=100 as a model, you can use any other picture (as long as it's relevant and complies with SE's rules, of course).
Note that standards loopholes policies apply.
This is code-golf, so the shorter submission wins !

Since an example was requested, here is one, made "by hand", with n=4 and r=1
Steps 1 and 2

Step 3 : line-wise, 2 rectangles to the left

The example suggests that the rectangles do not need to be the same size, do not need to cover the entire image, and should include lines drawn over the original image. Could you clarify this, by either changing the specification or the example?

@trichoplax : the example was drawn by hand with paint and quickness. I will redo-it properly.

@trichoplax : I must admit that I don't completely get your point, but this opening line isn't needed to understand the challenge, so I guess it's useless to keep it.

move a random number of contiguous rectangles can it be 0 rectangles? (it would be a pain to make the program change behavior when the blank is on an edge/corner)

@JungHwanMin : yes it can. Good remark, thanks !

Sorry I don't really understand what the random number is for in Step 3. Cold you elaborate? At first I thought it was the number of times to move a rectangle, but that appears to be r. Also, what does it mean that it can be 0?

@KodosJohnson The random number of step 3 is the number of rectangles you move at a time in this step. It can be 0, if you're stuck on a corner or an edge. r is the total number of repetitions of this step.

As a point of interest, cycling any 3 tiles will always result in a solvable state, and generally produces a much better shuffle.

@primo : Thanks for the comment ! How do you come up with this conclusion ?

@Frédéric AF Archer provides a fairly elegant proof in this paper (proof of Lemma 1, Theorem 3). In essence, he is showing that each single piece slide can be obtained by 3-cycles, and thus all of A15 (note that the pieces are numbered slightly out of order to obtain this proof).

@primo : thanks for the ref ! I'll read that, and perhaps add to the challenge the possibility to move 3 squares at every step !

Mathematica, 246 bytes
ImageAssemble@(n=Nest)[k=RandomInteger;q=Reverse;({t,r}=1~k~2;q[o=n[q/@#&,#,r]&@*(n[#&,#,t]&)])[o@#/.{a___,b:_~RepeatedNull~k[Position[o@#,i][[1,2]]-1],i,c___}:>{a,i,b,c}]&,MapAt[(i=#~ImageAdd~1)&,#~ImagePartition~Scaled[1/#2],{1,#2}~k~2],#3]&

Anonymous function. Contains U+F3C7, corresponding to Mathematica's Transpose operator. This function takes an Image object and returns an Image object.
Sample Animation, with n=16 and r=100
After 5000 iterations:
(click image for larger version)
Explanation
Initialization
n=Nest

Store the Nest function (repeating operation) in n.
k=RandomInteger;q=Reverse;

Store the RandomInteger function in k, and Reverse function in q.
Splitting the image
#~ImagePartition~Scaled[1/#2]

Partition the input image into (second input)^2 tiles.
{1,#2}~k~2

Generate two RandomIntegers between 1 and the second input. This selects a random tile.
MapAt[(i=#~ImageAdd~1)&, ..., {1,#2}~k~2]

Make that tile white. Store it in i.
Moving Tiles
{t,r}=1~k~2

Generate two random integers from 0 to 1, and store them in t and r, respectively. This randomly selects direction.
o=n[q/@#&,#,r]&@*(n[#&,#,t]&)

Define function o: the composition of

a function transposing the input t times.
a function reversing each row r times.

o@#
Apply o to the input.
Position[o@#,i][[1,2]]

Find the column of i (white image).
k[ ... -1]

Subtract one and find a random integer between 0 and that number. This randomly chooses how many tiles to move.
o@#/.{a___,b:_~RepeatedNull~ ... ,i,c___}:>{a,i,b,c}

When the said number of tiles occur before an i (white image), switch their places.
(... q[o= ... ])[ ... ]

Reverse the o function and apply that to the result of above operation. This un-reverses and un-transposes the image.
Looping and Image Assembly
(n=Nest)[ ... ,#3]

Repeat the above process (third input) times.
ImageAssemble@

Put the images together.

Nice answer ! Thanks for the details !