-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorbits.w
13454 lines (11149 loc) · 493 KB
/
orbits.w
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass{report}
% ****** TURN OFF HARDWARE TABS BEFORE EDITING THIS DOCUMENT ******
%
% Should you ignore this admonition, tabs in the program code will
% not be respected in the LaTeX-generated program document.
% If that should occur, simply pass this file through
% expand to replace the tabs with sequences of spaces.
% This program is written using the Nuweb Literate Programming
% tool:
%
% http://sourceforge.net/projects/nuweb/
%
% For information about Literate Programming, please visit the
% site: http://www.literateprogramming.com/
\setlength{\oddsidemargin}{0cm}
\setlength{\evensidemargin}{0cm}
\setlength{\topmargin}{0cm}
\addtolength{\topmargin}{-\headheight}
\addtolength{\topmargin}{-\headsep}
\setlength{\textheight}{22.5cm}
\setlength{\textwidth}{16.5cm}
\setlength{\marginparwidth}{1.25cm}
\setcounter{tocdepth}{6}
\setcounter{secnumdepth}{6}
\newcommand{\dense}{\setlength{\itemsep}{-1ex}}
% Keep section numbers from colliding with title in TOC
\usepackage{tocloft}
\cftsetindents{subsection}{4em}{4em}
\cftsetindents{subsubsection}{6em}{5em}
% Enable PDF output and hyperlinks within PDF files
\usepackage[unicode=true,pdftitle={Fourmilab Orbits},pdfauthor={John Walker},colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref}
% Enable inclusion of graphics files
\usepackage{graphicx}
% Enable proper support for appendices
\usepackage[toc,titletoc,title]{appendix}
% Support text wrapping around figures
\usepackage{wrapfig}
\title{\bf Fourmilab Orbits \\
{\rm for Second Life}
}
\author{
by \href{http://www.fourmilab.ch/}{John Walker}
}
\date{
March 2021 \\
\vspace{12ex}
\includegraphics[width=3cm]{figures/fourlogo_640.png}
}
\begin{document}
\pagenumbering{roman}
\maketitle
\tableofcontents
\chapter{Introduction}
\pagenumbering{arabic}
% The following allows disabling the build number and date and
% time inclusion in programs during periods of active development.
% The build number continues to be incremented as a record, but
% we embed zero values here to avoid having files which are not
% otherwise changed be updated by Nuweb. Such unnecessary updates
% would generate a large number of meangless Git transactions which
% would only confuse the record of genuine changes to the code.
%
% When it's time to go into production, re-enable the include of
% build.w to restore the build number configuration control
% facility.
%
%i build.w
@d Build number @{0@}
@d Build date and time @{1900-01-01 00:00@}
\subsection{Build number consistency checking}
The following code is used to check that subsidiary scripts and
the scripts within objects we create are from the same build number
as the Deployer. This check is only made when explicitly requested
via the ``Test version'' command: since during development it will
almost always be the case that the latest scripts have not yet been
installed in objects we aren't actively testing. We use
{\tt llOwnerSay()} instead of {\tt tawk()} to report discrepancies,
allowing this code to be used in simple scripts which don't have
that function.
\subsection{Check build number in Deployer scripts}
The {\tt LM\_AS\_VERSION} message requests a Deployer script to check
its build number against that of the Deployer and report any
discrepancy.
@d Check build number in Deployer scripts
@{
// LM_AS_VERSION (543): Check version consistency
} else if (num == LM_AS_VERSION) {
if ("@<Build number@>" != str) {
llOwnerSay(llGetScriptName() +
" build mismatch: Deployer " + str +
" Local @<Build number@>");
}
@}
\subsubsection{Check build number in created objects}
This code, inserted in the {\tt massChannel} message processor in
objects (for example, planets and numerical integration masses) we
create, checks build number and reports discrepancies.
@d Check build number in created objects
@{
} else if (ccmd == "VERSION") {
if ("@<Build number@>" != llList2String(msg, 1)) {
llOwnerSay(llGetScriptName() +
" build mismatch: Deployer " + llList2String(msg, 1) +
" Local @<Build number@>");
}
@}
\subsubsection{Forward build number check to objects we've created}
Objects created by the Deployer, for example Solar System planets and
Numerical Integration masses, may, in turn, create their own objects
such as {\tt flPlotLine} cylinders to trace orbital paths. Since these
objects listen only to messages from their creator, which is not the
Deployer, objects which create other objects must forward the {\tt
VERSION} message from the Deployer to them so that they may check their
own build number. Note that we forward the build number we received
from the Deployer, not the object's own, which might not be the same.
@d Forward build number check to objects we've created
@{
llRegionSay(@<massChannel@>,
llList2Json(JSON_ARRAY, [ "VERSION", llList2String(msg, 1) ]));
@}
\chapter{Utility Functions}
This and the following chapter define a variety of functions which
are used in various places throughout the scripts in the product.
Because LSL does not have either source-level includes or separate
compilation, each script is entirely self-contained and must define
all of the functions is uses. Consequently, we use the Literate
Programming macro facility much like the ``program library'' of a
computer in the 1950s, providing a collection of functions whose
source code may be included in scripts which require them simply by
citing their scrap names in their headers.
\section{Constants and Settings}
The following definitions are constants used widely within the
program and global settings. They are incorporated directly within
the scripts by macro expansion, avoiding script storage.
\subsection{Communication channel}
This is the channel used by objects to communicate with one another.
Objects created by a deployer only respond to messages sent by that
deployer, avoiding interference even if multiple deployers and models
are running in the same region and using the same channel.
@d massChannel @( -982449822 @)
\subsection{Standard colours}
We use the following colour code, derived from the
\href{https://en.wikipedia.org/wiki/Electronic_color_code#Resistor_code}{resistor
colour code}, for a variety of purposes: choosing colours for bodies in
galactic centre simulations, identifying orbit trails, etc.
@d Colour:0:black @{ <0, 0, 0> @}
@d Colour:1:brown @{ <0.3176, 0.149, 0.1529> @}
@d Colour:2:red @{ <0.8, 0, 0> @}
@d Colour:3:orange @{ <0.847, 0.451, 0.2784> @}
@d Colour:4:yellow @{ <0.902, 0.788, 0.3176> @}
@d Colour:5:green @{ <0.3216, 0.5608, 0.3961> @}
@d Colour:6:blue @{ <0.00588, 0.3176, 0.5647> @}
@d Colour:7:violet @{ <0.4118, 0.4039, 0.8078> @}
@d Colour:8:grey @{ <0.4902, 0.4902, 0.4902> @}
@d Colour:9:white @{ <1, 1, 1> @}
@d Colour:10:silver @{ <0.749, 0.745, 0.749> @}
@d Colour:11:gold @{ <0.7529, 0.5137, 0.1529> @}
\section{Floating point hexadecimal encoding and decoding}
The {\tt fuis} and {\tt suif} functions encode and decode {\tt float}
values as Base64 encoded six character strings. This is a fast
and compact encoding which preserves all of the (sorely limited)
precision of a these numbers. These functions are based upon
code developed by Strife Onizuka and contributed to the LSL
Library.
\subsection{Encode floating point number as base64 string}
\label{fuis}
The {\tt fuis} function encodes its floating point argument as a six
character string encoded as base64. This version is modified from the
original in the LSL Library. By ignoring the distinction between $+0$
and $-0$, this version runs almost three times faster than the
original. While this does not preserve floating point numbers
bit-for-bit, it doesn't make any difference in our calculations.
@d fuis: Encode floating point number as base64 string
@{
string fuis(float a) {
// Detect the sign on zero. It's ugly, but it gets you there
// integer b = 0x80000000 & ~llSubStringIndex(llList2CSV([a]), "-"); // Sign
/* Test for negative number, ignoring the difference between
+0 and -0. While this does not preserve floating point
numbers bit-for-bit, it doesn't make any difference in
our calculations and is almost three times faster than
the original code above. */
integer b = 0;
if (a < 0) {
b = 0x80000000;
}
if (a) { // Is it greater than or less than zero ?
// Denormalized range check and last stride of normalized range
if ((a = llFabs(a)) < 2.3509887016445750159374730744445e-38) {
b = b | (integer) (a / 1.4012984643248170709237295832899e-45); // Math overlaps; saves CPU time
// We never need to transmit infinity, so save the time testing for it.
// } else if (a > 3.4028234663852885981170418348452e+38) { // Round up to infinity
// b = b | 0x7F800000; // Positive or negative infinity
} else if (a > 1.4012984643248170709237295832899e-45) { // It should at this point, except if it's NaN
integer c = ~-llFloor(llLog(a) * 1.4426950408889634073599246810019);
// Extremes will error towards extremes. The following corrects it
b = b | (0x7FFFFF & (integer) (a * (0x1000000 >> c))) |
((126 + (c = ((integer) a - (3 <= (a *= llPow(2, -c))))) + c) * 0x800000);
// The previous requires a lot of unwinding to understand
} else {
// NaN time! We have no way to tell NaNs apart so pick one arbitrarily
b = b | 0x7FC00000;
}
}
return llGetSubString(llIntegerToBase64(b), 0, 5);
}
@| fuis @}
\subsubsection{Encode vector as base64 string}
The {\tt fv} function encodes the three components of a vector as
consecutive {\tt fuis} base64 strings.
@d fv: Encode vector as base64 string
@{
string fv(vector v) {
return fuis(v.x) + fuis(v.y) + fuis(v.z);
}
@| fv @}
\subsection{Decode base64-encoded floating point number}
The {\tt siuf} function decodes a floating point number encoded with
{\tt fuis}.
@d siuf: Decode base64-encoded floating point number
@{
float siuf(string b) {
integer a = llBase64ToInteger(b);
if (0x7F800000 & ~a) {
return llPow(2, (a | !a) + 0xffffff6a) *
(((!!(a = (0xff & (a >> 23)))) * 0x800000) |
(a & 0x7fffff)) * (1 | (a >> 31));
}
return (!(a & 0x7FFFFF)) * (float) "inf" * ((a >> 31) | 1);
}
@| siuf @}
\subsubsection{Decode base64-encoded vector}
This is a helper function to decode a vector packed as three
consecutive {\tt siuf}-encoded floats.
@d sv: Decode base64-encoded vector
@{
vector sv(string b) {
return(< siuf(llGetSubString(b, 0, 5)),
siuf(llGetSubString(b, 6, 11)),
siuf(llGetSubString(b, 12, -1)) >);
}
@| sv @}
\section{Edit floating point numbers in parsimonious representation}
LSL's conversion of floating point numbers to decimal strings leaves
much to be desired when the goal is displaying values to a user
as opposed to diagnostic output for developers. While there are
flexible editing routines for both decimal and scientific notation
in the LSL Library, they are very slow and consume a large amount
of scarce script memory. Our {\tt ef} function takes the string
produced by casting a floating point number to a string and makes
it more primate-friendly by eliding trailing zeroes and deleting
the decimal point if the number is integral. The function may be
called on a string containing one or more numbers; the numbers are
re-formatted without modifying the surrounding text.
\subsection{Edit floating point number to readable representation}
Note that this function takes a string as an argument. If you're
passing a number, you must cast it to a string or else use the
{\tt efr} helper function below.
@d ef: Edit floating point number to readable representation
@{
string ef(string s) {
integer p = llStringLength(s) - 1;
while (p >= 0) {
// Ignore non-digits after numbers
while ((p >= 0) &&
(llSubStringIndex("0123456789", llGetSubString(s, p, p)) < 0)) {
p--;
}
// Verify we have a sequence of digits and one decimal point
integer o = p - 1;
integer digits = 1;
integer decimals = 0;
while ((o >= 0) &&
(llSubStringIndex("0123456789.", llGetSubString(s, o, o)) >= 0)) {
o--;
if (llGetSubString(s, o, o) == ".") {
decimals++;
} else {
digits++;
}
}
if ((digits > 1) && (decimals == 1)) {
// Elide trailing zeroes
while ((p >= 0) && (llGetSubString(s, p, p) == "0")) {
s = llDeleteSubString(s, p, p);
p--;
}
// If we've deleted all the way to the decimal point, remove it
if ((p >= 0) && (llGetSubString(s, p, p) == ".")) {
s = llDeleteSubString(s, p, p);
p--;
}
// Done with this number. Skip to next non digit or decimal
while ((p >= 0) &&
(llSubStringIndex("0123456789.", llGetSubString(s, p, p)) >= 0)) {
p--;
}
} else {
// This is not a floating point number
p = o;
}
}
return s;
}
@| ef @}
\subsubsection{Edit float to readable representation}
This helper function casts its float argument to a string and calls
{\tt ef} to edit it to a readable string.
@d eff: Edit float to readable representation
@{
string eff(float f) {
return ef((string) f);
}
@| eff @}
\subsubsection{Edit vector to readable representation}
This helper function casts its vector argument to a string and calls
{\tt ef} to edit it to a readable string. It takes advantage of
the ability of {\tt ef} to process multiple numbers in its input
string.
@d efv: Edit vector to readable representation
@{
string efv(vector v) {
return ef((string) v);
}
@| efv @}
\section{Transform local to region co-ordinates}
@d l2r: Transform local to region co-ordinates
@{
vector l2r(vector loc) {
return (loc * llGetRootRotation()) + llGetRootPosition();
}
@| l2r @}
\section{Find a linked prim by name}
Find a linked prim by name avoids having to slavishly link prims in
order in complex builds to reference them later by link number. You
should only call this once, in {\tt state\_entry()}, and then save the
link numbers in global variables. Returns the prim number or $-1$ if
no such prim was found. Caution: if there are more than one prim with
the given name, the first will be returned without warning of the
duplication.
@d findLinkNumber: Find a linked prim by name
@{
integer findLinkNumber(string pname) {
integer i = llGetLinkNumber() != 0;
integer n = llGetNumberOfPrims() + i;
for (; i < n; i++) {
if (llGetLinkName(i) == pname) {
return i;
}
}
return -1;
}
@| findLinkNumber @}
\section{Send a message to the interacting user in chat}
The {\tt tawk} function communicates with a user with whom
we're interacting in a variety of ways. If the user has
sent us a command, their key will have been stored in the
global {\tt whoDat} and we direct the message to them.
If that user is our owner, we use {\tt llOwnerSay}, which
avoids the dreaded risk of being blocked due to a message
flood, which can only be lifted by restarting the region.
Otherwise, we use {\tt llRegionSayTo}, running the risk in
the interest of communication. If we aren't in communication
with a user, we send the message to local chat on the public
channel.
@d tawk: Send a message to the interacting user in chat
@{
tawk(string msg) {
if (whoDat == NULL_KEY) {
// No known sender. Say in nearby chat.
llSay(PUBLIC_CHANNEL, msg);
} else {
/* While debugging, when speaking to the owner, use llOwnerSay()
rather than llRegionSayTo() to avoid the risk of a runaway
blithering loop triggering the gag which can only be removed
by a region restart. */
if (owner == whoDat) {
llOwnerSay(msg);
} else {
llRegionSayTo(whoDat, PUBLIC_CHANNEL, msg);
}
}
}
@| tawk @}
\section{Argument parsing}
These functions assist in parsing of arguments in commands entered
by the user in chat, submitted by scripts, or read from notecards
for various purposes.
\subsection{Transform vector and rotation arguments to canonical form}
The simple-minded parsing performed by {\tt llParseString2List()}
does not understand vector and rotation arguments, which are
delimited by angle brackets and may contain spaces between the
brackets which are ignored. These embedded spaces will, however,
cause the argument to be broken into pieces and mis-interpreted
if left in place. The {\tt fixArgs()} function takes a command
line and deletes all embedded spaces between brackets, guaranteeing
that they are parsed as a single argument.
@d fixArgs: Transform vector and rotation arguments to canonical form
@{
string fixArgs(string cmd) {
cmd = llStringTrim(cmd, STRING_TRIM);
integer l = llStringLength(cmd);
integer inbrack = FALSE;
integer i;
string fcmd = "";
for (i = 0; i < l; i++) {
string c = llGetSubString(cmd, i, i);
if (inbrack && (c == ">")) {
inbrack = FALSE;
}
if (c == "<") {
inbrack = TRUE;
}
if (!((c == " ") && inbrack)) {
fcmd += c;
}
}
return fcmd;
}
@| fixArgs @}
\subsection{Consolidate quoted arguments}
In some commands we wish to allow quoted arguments which may contain
spaces. Since {\tt llParseString2List()} does not understand this
syntax and breaks arguments unconditionally at spaces, this function
post-processes an argument list and consolidates arguments from one
which starts with a quote to one which ends with a quote into a single
argument list item. For consistency, a single argument which starts
and ends with a quote has the quotes removed. Note that multiple
spaces within quoted arguments are compressed to a single space. You
can, if you wish, first process an argument list with {\tt fixArgs} to
canonicalise vectors and rotations, then post-process the list parsed
from its result with {\tt fixQuotes} to handle quoted arguments.
@d fixQuotes: Consolidate quoted arguments
@{
list fixQuotes(list args) {
integer i;
integer n = llGetListLength(args);
for (i = 0; i < n; i++) {
string arg = llList2String(args, i);
if (llGetSubString(arg, 0, 0) == "\"") {
/* Argument begins with a quote. If it ends with one,
strip them and we're done. */
if (llGetSubString(arg, -1, -1) == "\"") {
args = llListReplaceList(args,
[ llGetSubString(arg, 1, -2) ], i, i);
} else {
/* Concatenate arguments until we find one that ends
with a quote, then replace the multiple arguments
with the concatenation. */
string rarg = llGetSubString(arg, 1, -1);
integer looking = TRUE;
integer j;
for (j = i + 1; looking && (j < n); j++) {
string narg = llList2String(args, j);
if (llGetSubString(narg, -1, -1) == "\"") {
rarg += " " + llGetSubString(narg, 0, -2);
looking = FALSE;
} else {
rarg += " " + narg;
}
}
if (!looking) {
args = llListReplaceList(args, [ rarg ], i, j - 1);
}
}
}
}
return args;
}
@| fixQuotes @}
\subsection{Test argument, allowing abbreviation}
Tests the first characters of {\tt str} against the abbreviation
{\tt abbr}. This is a case-sensitive test: if you wish it to be
case-insensitive, convert the string to the same case as the
abbreviation before calling.
@d abbrP: Test argument, allowing abbreviation
@{
integer abbrP(string str, string abbr) {
return abbr == llGetSubString(str, 0, llStringLength(abbr) - 1);
}
@| abbrP @}
\subsection{Parse an on/off parameter}
Parse a parameter which is ``on'' or ``off'', returning 1 or 0
respectively. If the parameter is neither, display an error and return
$-1$. In a number of places we allow parameters which can be ``on'',
``off'', or something else: this is accomplished simply by testing for
the other cases with {\tt abbrP()} or another comparison before calling
{\tt onOff()}.
@d onOff: Parse an on/off parameter
@{
integer onOff(string param) {
if (abbrP(param, "on")) {
return TRUE;
} else if (abbrP(param, "of")) {
return FALSE;
} else {
tawk("Error: please specify on or off.");
return -1;
}
}
@| onOff @}
\subsection{Edit an on/off parameter}
Return a string indicating whether the Boolean state is on or off.
@d eOnOff: Edit an on/off parameter
@{
string eOnOff(integer p) {
if (p) {
return "on";
}
return "off";
}
@| eOnOff @}
\subsection{Parse extended colour specification}
\label{exColour}
Colours for source objects are specified using an extended
notation which allows specification of transparency and glow
in addition to colour components:
\begin{verse}
{\tt <} {\em red}{\tt ,} {\em green}{\tt ,} {\em blue}{\tt ,}
{\em alpha}{\tt ,} {\em glow} {\tt >}
\end{verse}
\noindent
where all components are in the range $[0,1)]$. For colour channels,
the value gives the intensity of that component. For {\tt alpha}, 0
denotes transparent and 1 opaque, and {\tt glow} is the intensity of
glow with 0 no glow and 1 maximum intensity.
@d exColour: Parse extended colour specification
@{
list exColour(string s) {
if ((llGetSubString(s, 0, 0) == "<") &&
(llGetSubString(s, -1, -1) == ">")) {
list l = llParseStringKeepNulls(llGetSubString(s, 1, -2), [ "," ], [ ]);
integer n = llGetListLength(l);
if (n >= 3) {
vector colour = < llList2Float(l, 0),
llList2Float(l, 1),
llList2Float(l, 2) >;
float alpha = 1;
float glow = 0;
if (n >= 4) {
alpha = llList2Float(l, 3);
if (n >= 5) {
glow = llList2Float(l, 4);
}
}
return [ colour, alpha, glow ];
}
}
return [ <1, 1, 1>, 1, 0 ]; // Default: solid white, no glow
}
@| exColour @}
\section{Trace path with particle system}
If {\tt paths} is set, trace the path of a body as it moves by
depositing ribbon particles behind it. This is a cheap way to show
trajectories, but has the limitations of all particle systems. It
works very poorly for rotating bodies, as the direction of particle
emission changes with the orientation of the object to which it is
attached.
@d Trace path with particle system @'@'
@{
if (paths) {
llParticleSystem(
[ PSYS_PART_FLAGS, PSYS_PART_EMISSIVE_MASK |
PSYS_PART_INTERP_COLOR_MASK |
PSYS_PART_RIBBON_MASK,
PSYS_SRC_PATTERN, PSYS_SRC_PATTERN_DROP,
PSYS_PART_START_COLOR, @1,
PSYS_PART_END_COLOR, @1,
PSYS_PART_START_SCALE, <0.75, 0.75, 1>,
PSYS_PART_END_SCALE, <0.75, 0.75, 1>,
PSYS_SRC_MAX_AGE, 0,
PSYS_PART_MAX_AGE, 8.0,
PSYS_SRC_BURST_RATE, 0.0,
PSYS_SRC_BURST_PART_COUNT, 60
]);
} else {
llParticleSystem([ ]);
}
@}
\section{Kaboom: Destroy object}
When we want to emphatically get rid of an object, for example when
a body wanders beyond the range we wish to display or two masses in
a numerical integration simulation collide, {\tt kaboom()} generates
an explosion particle effect, plays a detonation sound, and commands
the object to self-destruct.
@d kaboom: Destroy object
@{
kaboom(vector colour) {
llPlaySound(Collision, 1);
llParticleSystem([
PSYS_SRC_PATTERN, PSYS_SRC_PATTERN_EXPLODE,
PSYS_SRC_BURST_RADIUS, 0.05,
PSYS_PART_START_COLOR, colour,
PSYS_PART_END_COLOR, colour,
PSYS_PART_START_ALPHA, 0.9,
PSYS_PART_END_ALPHA, 0.0,
PSYS_PART_START_SCALE, <0.3, 0.3, 0>,
PSYS_PART_END_SCALE, <0.1, 0.1, 0>,
PSYS_PART_START_GLOW, 1,
PSYS_PART_END_GLOW, 0,
PSYS_SRC_MAX_AGE, 0.1,
PSYS_PART_MAX_AGE, 0.5,
PSYS_SRC_BURST_RATE, 20,
PSYS_SRC_BURST_PART_COUNT, 1000,
PSYS_SRC_ACCEL, <0, 0, 0>,
PSYS_SRC_BURST_SPEED_MIN, 2,
PSYS_SRC_BURST_SPEED_MAX, 2,
PSYS_PART_FLAGS, 0
| PSYS_PART_EMISSIVE_MASK
| PSYS_PART_INTERP_COLOR_MASK
| PSYS_PART_INTERP_SCALE_MASK
| PSYS_PART_FOLLOW_VELOCITY_MASK
]);
llSleep(1); // Need to wait to allow particles and sound to play
llDie();
}
@| kaboom @}
\chapter{Mathematical and Geometric Functions}
This is a collection of commonly-used functions which are not provided
by LSL. They are used frequently in positional astronomy and
geometric modelling.
\section{Constants}
The following mathematical and astronomical constants are declared
here as macros, which allows them to be substituted in code without
occupying separate storage as global variables.
Base of the natural logarithms, $e$.
@d Ke @( 2.718281828459045 @)
Epoch J2000: we write this as an integer so that it may be used as
such or cast to a float as desired.
@d J2000 @( 2451545 @)
Days in a Julian century.
@d JulianCentury @( 36525.0 @)
Semi-major axis of Moon's orbit
@d MoonSemiMaj @( 384401 @)
\subsection{Gravitational constant}
We define the gravitational constant in a system of units where
length is measured in astronomical units, mass in solar masses, and
time in years.
@d Gravitational constant in astronomical units
@{
float G_SI = 6.6732e-11; // (Newton Metre^2) / Kilogram^2
float AU = 149504094917.0; // Metres / Astronomical unit
float M_SUN = 1.989e30; // Kilograms / Mass of Sun
float YEAR = 31536000; // Seconds / Year (365.0 * 24 * 60 * 60)
@}
From Newton's second law:
\[
F = m a
\]
with units
\[
{\rm Newton} = \frac{\rm kg}{{\rm sec}^2}
\]
the fundamental units of the gravitational constant are:
\begin{eqnarray*}
G & = & {\rm N}\ {\rm m}^2 / {\rm kg}^2 \\
& = & ({\rm kg}\ {\rm m} / {\rm sec}^2)\ {\rm m}^2 / {\rm kg}^2 \\
& = & {\rm kg}\ {\rm m}^3 / {\rm sec}^2\ {\rm kg}^2 \\
& = & {\rm m}^3 / {\rm sec}^2\ {\rm kg}
\end{eqnarray*}
The conversion factor, therefore, between the SI gravitational
constant and its equivalent in our units is:
\[
{\tt GRAV\_CONV} = {\tt AU}^3 / {\tt YEAR}^2\ {\tt M\_SUN}
\]
and the gravitational constant itself is obtained by dividing the
SI definition by this conversion factor.
\[
{\tt GRAVCON} = {\tt G\_SI} / {\tt GRAV\_CONV}
\]
Now define our gravitational units. Because LSL does not support
compile-time arithmetic, we'll have to initialise them when the
script starts running.
@d Gravitational constant in astronomical units
@{
float GRAV_CONV; // ((AU * AU * AU) / ((YEAR * YEAR) * M_SUN))
float GRAVCON; // (G_SI / GRAV_CONV)
@}
This is the code to initialise these constants.
@d Initialise gravitational constant in astronomical units
@{
GRAV_CONV = ((AU * AU * AU) / ((YEAR * YEAR) * M_SUN));
GRAVCON = G_SI / GRAV_CONV;
@}
\subsection{Standard gravitational parameters}
In a two body gravitational system, the standard gravitational
parameter:
\[
\mu = G M
\]
of the central mass determines the trajectories of much smaller
masses under its gravitational influence: for objects in elliptical
orbits, their orbital periods. $G$ is the Newtonian gravitational
constant and $M$ is the mass of the central body. Here we define
$\mu$ for bodies in the solar system. These values use a length
unit of metres and a time unit of seconds, with $\mu$ having
dimensions of ${\rm m}^3\,{\rm s}^{-2}$.
@d GM:Sun @{ 1.32712440018e20 @}
%d GM:Mercury @{ 2.2032e13 @}
%d GM:Venus @{ 3.24859e14 @}
@d GM:Earth @{ 3.986004418e14 @}
%d GM:Mars @{ 4.282837e13 @}
@d GM:Jupiter @{ 1.26686534e17 @}
@d GM:Saturn @{ 3.7931187e16 @}
@d GM:Uranus @{ 5.793939e15 @}
@d GM:Neptune @{ 6.836529e15 @}
@d GM:Pluto @{ 8.71e11 @}
\section{Range reduction of angles}
Computations such as evaluation of periodic terms in planetary
theories and mean motion since an epoch often result in angles
which are larger than a full circle. Using such angles may
result in loss of precision, particularly in single precision
arithmetic. These functions take an angle of arbitrary magnitude
and reduce it to the range of a full circle.
\subsection{Range reduce an angle in radians}
The argument, an angle in radians, is reduced to an angle in the
interval $[0,2\pi)$.
@d fixangr: Range reduce an angle in radians
@{
float fixangr(float a) {
return a - (TWO_PI * (llFloor(a / TWO_PI)));
}
@| fixangr @}
\subsection{Range reduce an angle in degrees}
The argument, an angle in radians, is reduced to an angle in the
interval $[0,360)$.
@d fixangle: Range reduce an angle in degrees
@{
float fixangle(float a) {
return a - (360.0 * llFloor(a / 360.0));
}
@| fixangle @}
\section{Spherical and rectangular co-ordinates}
These functions convert between spherical (often characterised as
longitude, latitude, and radius) and rectangular (Cartesian)
co-ordinates.
\subsection{Spherical to rectangular co-ordinate conversion}
Convert spherical co-ordinates (often referred to as $(L, B, R)$ or
$(\lambda, \beta, r)$ to rectangular $(X,Y,Z)$. The scale factor is
not specified, and the units of the rectangular co-ordinates will be
the same as those of the radius in the spherical.
@d sphRect: Spherical to rectangular co-ordinate conversion
@{
vector sphRect(float l, float b, float r) {
return < r * llCos(b) * llCos(l),
r * llCos(b) * llSin(l),
r * llSin(b) >;
}
@| sphRect @}
\subsection{Rectangular to spherical co-ordinate conversion}
Convert rectangular $(X,Y,Z)$ co-ordinates to spherical co-ordinates
(often referred to as $(L, B, R)$ or $(\lambda, \beta, r)$. The scale
factor is not specified, and the units of the rectangular co-ordinates
will be the same as those of the radius in the spherical.
@d rectSph: Rectangular to spherical co-ordinate conversion
@{
vector rectSph(vector rc) {
float r = llVecMag(rc);
return < llAtan2(rc.y, rc.x), llAsin(rc.z / r), r >;
}
@| rectSph @}
\section{Signs and Magnitudes}
Functions for manipulating floating point and integer values.
\subsection{Sign of argument}
Returns $-1$ if the argument is negative, $1$ if positive, and $0$ if
it is zero. (Yes, this is like the BASIC function---so mock me.)
@d sgn: Sign of argument
@{
integer sgn(float v) {
if (v == 0) {
return 0;
} else if (v > 0) {
return 1;
}
return -1;
}
@| sgn @}
\subsection{Test if value is NaN}
When parsing orbital elements, we initialise unspecified arguments to
IEEE 754 not-a-number (NaN) to distinguish from, say, zero, which is a
valid specification for many elements. This function tests its
argument and returns {\tt TRUE} if it is NaN\@@. This may be used
anywhere else you wish to make this test.
@d spec: Test if value is NaN
@{
integer spec(float e) {
return ((string) e) != "NaN";
}
@| spec @}
\section{Hyperbolic Trigonometric Functions}
When computing hyperbolic trajectories, we require hyperbolic
trigonometric functions. Here we define them in terms of functions
which are implemented in LSL.
\begin{eqnarray*}
\sinh x & = & \frac{e^x - e^{-x}}{2} \\
\cosh x & = & \frac{e^x + e^{-x}}{2} \\
\tanh x & = & \frac{\sinh x}{\cosh x}
\end{eqnarray*}
@d Hyperbolic trigonometric functions
@{
float flSinh(float x) {
return (llPow(@<Ke@>, x) - llPow(@<Ke@>, -x)) / 2;
}
float flCosh(float x) {
return (llPow(@<Ke@>, x) + llPow(@<Ke@>, -x)) / 2;
}
float flTanh(float x) {
return flSinh(x) / flCosh(x);
}
@| flSinh flCosh flTanh @}
\section{Random Unit Vector Generation}
Generate a unit vector in a direction which is uniformly distributed on
the unit sphere. Getting this right is more subtle than you might
think. We use Marsaglia's method, as described in Marsaglia, G.
``Choosing a Point from the Surface of a Sphere.'' {\em Ann\@@.
Math\@@. Stat\@@.} {\bf 43}, 645--646, 1972.
@d randVec: Random Unit Vector Generation
@{
vector randVec() {
integer outside = TRUE;
while (outside) {
float x1 = 1 - llFrand(2);
float x2 = 1 - llFrand(2);
if (((x1 * x1) + (x2 * x2)) < 1) {
outside = FALSE;
float x = 2 * x1 * llSqrt(1 - (x1 * x1) - (x2 * x2));
float y = 2 * x2 * llSqrt(1 - (x1 * x1) - (x2 * x2));
float z = 1 - 2 * ((x1 * x1) + (x2 * x2));
return < x, y, z >;
}
}
return ZERO_VECTOR; // Can't happen, but idiot compiler errors otherwise
}