202c58f77546ddf9da67eb8c789d6a1861d33b47
[feisty_meow.git] / huffware / huffotronic_scripts / comfortable_sitting_v7.5.txt
1 
2 // huffware script: comfortable sitting, by fred huffhines.
3 //
4 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
5 // do not use it in objects without fully realizing you are implicitly accepting that license.
6 //
7
8 //////////////
9
10 // global constants...
11
12 string NOTEWORTHY_SIGNATURE = "#sitting";
13     // the notecard must begin with this as its first line for it to be
14     // recognized as our configuration card.
15
16 //////////////
17
18 // global variables that are loaded from a notecard.
19
20 vector AVATAR_ROTATION = <0, 0, -90>;  // star chair.
21 //vector AVATAR_ROTATION = <0, 0, 0>;
22     // the euler vector for rotation of the avatar after sitting, in degrees.
23     // the rotation vector should be tailored to the object.
24
25 vector AVATAR_POSITION = <-0.1, -0.28, -0.1>;  // star chair.
26 //vector AVATAR_POSITION = <0.34, 0, 0>;
27     // the position of the sitting offset from the object center.   also needs to be
28     // tailored to the particular object.
29
30 integer GOTO_WHICH_FLOOR = 1;
31     // when serving as an elevator, this is a way to cause the teleport offset
32     // to go to a particular floor.  the real z position is calculated from
33     // this times the floor size in meters.  note that floors are numbered
34     // starting at 1 (one).
35     
36 float FLOOR_SIZE_IN_METERS = 0.0;
37     // when the script is used in an elevator, this specifies the height of the
38     // floors.  our current scheme will only work if that is constant between
39     // the floors.
40
41 float BASE_FLOOR_HEIGHT = 0.0;
42     // the position of the first floor in meters.  this will not affect the
43     // position calculations unless floor size is non-zero.
44
45 integer UNSEAT_AFTERWARDS = FALSE;
46     // if this is true, then the avatar is unseated just after sitting down.
47     
48 float PAUSE_BEFORE_EVICTION = 0.28;
49     // the number of seconds that the avatars get to sit before we pop them
50     // out of the chair/teleporter/whatever.
51
52 vector CAMERA_EYE_OFFSET = <3, 2, 1.5>;  // star chair.
53     // the offset for the camera after the avatar sits down.
54 //relative to the avatar?
55
56 vector CAMERA_TARGET = <-3, 0, 1>;  // star chair.
57     // the location where the camera is looking at once the avatar sits down.
58 //relative to the avatar?
59
60 //////////////
61
62 // global variables used in processing notecards...
63
64 integer pending_response_id;  // set to uniquely identify the notecard read in progress.
65 list global_config_list;  // a collection of configuration parameters from our notecard.
66 integer global_config_index;  // allows wrap-around feature, which we don't use here.
67
68 //////////////
69
70 // interfaces for library scripts we rely on...
71
72 // requires noteworthy library.
73 // in this odd case, where we are trying to shrink script count, the noteworthy library
74 // is embedded inside here.
75 //////////////
76 // do not redefine these constants.
77 integer NOTEWORTHY_HUFFWARE_ID = 10010;
78     // the unique id within the huffware system for the noteworthy script to
79     // accept commands on.  this is used in llMessageLinked as the num parameter.
80 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
81     // this pattern is an uncommon thing to see in text, so we use it to separate
82     // our commands in link messages.
83 string HUFFWARE_ITEM_SEPARATOR = "{|||}";
84     // used to separate lists of items from each other when stored inside a parameter.
85     // this allows lists to be passed as single string parameters if needed.
86 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
87 string BAD_NOTECARD_INDICATOR = "bad_notecard";
88     // indicates that the notecard reading process has failed to find an appropriate one.
89 string NOTECARD_READ_CONTINUATION = "continue!";
90     // returned as first parameter if there is still more data to handle.
91 // commands available via the noteworthy library:
92 string READ_NOTECARD_COMMAND = "#read_note#";
93     // command used to tell the script to read notecards.  needs a signature to find
94     // in the card as the first parameter, and a randomly generated response code for
95     // the second parameter.  the response code is used to uniquely identify a set of
96     // pending notecard readings (hopefully).  the signature can be blank.
97     // the results will be fired back as the string value returned, which will have
98     // as first element the notecard's name (or BAD_NOTECARD_INDICATOR if none was
99     // found) and as subsequent elements an embedded list that was read from the
100     // notecard.  this necessarily limits the size of the notecards that we can read
101     // and return.
102 string READ_SPECIFIC_NOTECARD_COMMAND = "#read_thisun#";
103     // like the read notecard command, but specifies the notecard name to use.  only that
104     // specific notecard file will be consulted.  first and second parm are still signature
105     // and response code, third parm is the notecard name.
106 //
107 //////////////
108 // joins a list of parameters using the parameter sentinel for the library.
109 string wrap_parameters(list to_flatten)
110 { return llDumpList2String(to_flatten, HUFFWARE_PARM_SEPARATOR); }
111 //////////////
112
113 // establishes the sitting parameters including camera offsets.
114 setup_seating_arrangements()
115 {
116     llUnSit(llAvatarOnSitTarget());  // no one gets to ignore a script change.        
117     vector new_rot = AVATAR_ROTATION;
118     new_rot *= DEG_TO_RAD;  // convert to radians.
119     rotation quat = llEuler2Rot(new_rot);  // convert to quaternion.
120     // get our position set up and take into account the elevator position.
121     vector position = AVATAR_POSITION;
122 //rename that variable to be "which floor to go to"
123     if (FLOOR_SIZE_IN_METERS != 0) {
124         vector temp = llGetPos();
125         integer my_floor = (integer) ((temp.z - BASE_FLOOR_HEIGHT ) / FLOOR_SIZE_IN_METERS) + 1;
126 //log_it("my floor is " + (string)my_floor);
127         float add_in = (float)(GOTO_WHICH_FLOOR - my_floor) * FLOOR_SIZE_IN_METERS;
128 //log_it("decided to add in z: " + (string)add_in);
129         position += <0, 0, add_in>;        
130     }
131     // also we make this absolute by taking out the object's own rotation.
132     // it's hard enough in life for z components to not mean z axis.
133     position /= llGetRot();
134     llSitTarget(position, quat / llGetRot());
135 //hmmm: do we need same rot treatment on camera things?    
136 //hmmm: trying it.
137     // now set the camera position to avoid having random viewpoint.
138     llSetCameraEyeOffset(CAMERA_EYE_OFFSET / llGetRot());
139     llSetCameraAtOffset(CAMERA_TARGET / llGetRot());
140 }
141
142 // this function fires off a request to the noteworthy library via a link message.
143 // noteworthy will look for a notecard with our particular signature in it and
144 // if it finds one, it will read the configuration therein.  an empty string is
145 // returned if noteworthy couldn't find anything.
146 request_configuration()
147 {
148     // try to find a notecard with our configuration.
149     pending_response_id = -1 * (integer)randomize_within_range(23, 80000, FALSE);
150     string parms_sent = wrap_parameters([NOTEWORTHY_SIGNATURE, pending_response_id]);
151 //call direct into noteworthy.
152 noteworthy_handle_link_message(LINK_THIS, NOTEWORTHY_HUFFWARE_ID, READ_NOTECARD_COMMAND, parms_sent);
153         
154 //    llMessageLinked(LINK_THIS, NOTEWORTHY_HUFFWARE_ID, READ_NOTECARD_COMMAND,
155 //         parms_sent);
156 }
157
158 // processes link messages received from the noteworthy library.
159 handle_link_message(integer which, integer num, string msg, key id)
160 {
161     if ( (num != NOTEWORTHY_HUFFWARE_ID + REPLY_DISTANCE)
162             || (msg != READ_NOTECARD_COMMAND) )
163         return;  // not for us.
164 //log_it("handl: msg=" + msg + " id=" + id);
165     // process the result of reading the notecard.
166     list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
167     string notecard_name = llList2String(parms, 0);
168 //log_it("raw is " + llList2String(parms, 1));
169     integer response_for = llList2Integer(parms, 1);
170 //log_it("resp cod=" + pending_response_id + " but this for=" + response_for);
171 //if (response_for != pending_response_id) log_it("bad response code???");    
172     if (response_for != pending_response_id) return;  // oops, this isn't for us.
173     if (notecard_name == BAD_NOTECARD_INDICATOR) {
174         // we hated the notecards we found, or there were none.
175         log_it("We apologize; there seem to be no notecards with a first line of '"
176             + NOTEWORTHY_SIGNATURE
177             + "'.  We can't read any configuration until that situation improves.");
178     } else {
179 //log_it("got to handle link");
180         // snag all but the first two elements for our config now.
181         global_config_list += llList2List(parms, 2, -1);
182         // make sure we shouldn't keep going.
183         if (notecard_name != NOTECARD_READ_CONTINUATION) {
184             // a valid notecard has been found.
185             global_config_index = 0;  // we are starting over in the config list.
186 //            log_it("read notecard \"" + notecard_name + "\":");
187             // and process the file as a set of definitions.
188             process_ini_config();
189             // now that we have a new set of parameters, use them.
190             setup_seating_arrangements();
191         }
192     }
193 }
194
195 ///////////////
196
197 // consumes the notecard in a very application specific way to retrieve our configuration items.
198 // the example script only looks for two variables: name and description.  if those are found in
199 // the sample card, then they are proudly shown.
200 parse_variable_definition(string to_parse)
201 {
202     string content;  // filled after finding a variable name.
203     if ( (content = get_variable_value(to_parse, "avatar_rotation")) != "") {
204         AVATAR_ROTATION = (vector)content;
205 //        log_it("** got avatar_rotation of '" + content + "'");
206     } else if ( (content = get_variable_value(to_parse, "avatar_position")) != "") {
207         AVATAR_POSITION = (vector)content;
208 //        log_it("** got avatar_position of '" + content + "'");
209     } else if ( (content = get_variable_value(to_parse, "goto_which_floor")) != "") {
210         GOTO_WHICH_FLOOR = (integer)content;
211 //        log_it("** got GOTO_WHICH_FLOOR of '" + content + "'");
212     } else if ( (content = get_variable_value(to_parse, "floor_size_in_meters")) != "") {
213         FLOOR_SIZE_IN_METERS = (float)content;
214 //        log_it("** got FLOOR_SIZE_IN_METERS of '" + content + "'");
215     } else if ( (content = get_variable_value(to_parse, "base_floor_height")) != "") {
216         BASE_FLOOR_HEIGHT = (float)content;
217 //        log_it("** got BASE_FLOOR_HEIGHT of '" + content + "'");
218     } else if ( (content = get_variable_value(to_parse, "unseat_afterwards")) != "") {
219         UNSEAT_AFTERWARDS = (integer)content;
220 //        log_it("** got unseat_afterwards of '" + content + "'");
221     } else if ( (content = get_variable_value(to_parse, "pause_before_eviction")) != "") {
222         PAUSE_BEFORE_EVICTION = (float)content;
223 //        log_it("** got pause_before_eviction of '" + content + "'");
224     } else if ( (content = get_variable_value(to_parse, "camera_eye_offset")) != "") {
225         CAMERA_EYE_OFFSET = (vector)content;
226 //        log_it("** got camera_eye_offset of '" + content + "'");
227     } else if ( (content = get_variable_value(to_parse, "camera_target")) != "") {
228         CAMERA_TARGET = (vector)content;
229 //        log_it("** got camera_target of '" + content + "'");
230 //    } else {
231 //        log_it("unknown variable seen: " + to_parse);
232     }
233 }
234
235 initialize()
236 {
237     // reset our relevant variables.
238     global_config_list = [];
239     global_config_index = 0;
240
241     // announce that we're open for business.
242 ///    log_it("started, free mem=" + (string)llGetFreeMemory());
243
244     // request that the noteworthy library start looking for our notecard.
245     request_configuration();
246     
247     integer indy = 32;
248     while (indy >= 0) {
249         indy = find_in_inventory_partial("noteworthy", INVENTORY_SCRIPT);
250         if (indy >= 0) {
251             llRemoveInventory(llGetInventoryName(INVENTORY_SCRIPT, indy));
252         }
253     }
254     
255 }
256
257 //////////////
258 // from hufflets...
259 //
260
261 integer debug_num = 0;
262
263 // a debugging output method.  can be disabled entirely in one place.
264 log_it(string to_say)
265 {
266     debug_num++;
267     // tell this to the owner.    
268     llOwnerSay(llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
269     // say this on an unusual channel for chat if it's not intended for general public.
270 //    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
271     // say this on open chat that anyone can hear.  we take off the bling for this one.
272 //    llSay(0, to_say);
273 }
274
275 // locates the string "text" in the list to "search_in".
276 integer find_in_list(list search_in, string text)
277
278     integer len = llGetListLength(search_in);
279     integer i; 
280     for (i = 0; i < len; i++) { 
281         if (llList2String(search_in, i) == text) 
282             return i; 
283     } 
284     return -1;
285 }
286
287 // returns TRUE if the "prefix" string is the first part of "compare_with".
288 integer is_prefix(string compare_with, string prefix)
289 { return (llSubStringIndex(compare_with, prefix) == 0); }
290
291 // returns a number at most "maximum" and at least "minimum".
292 // if "allow_negative" is TRUE, then the return may be positive or negative.
293 float randomize_within_range(float minimum, float maximum, integer allow_negative)
294 {
295     if (minimum > maximum) {
296         // flip the two if they are reversed.
297         float temp = minimum; minimum = maximum; maximum = temp;
298     }
299     float to_return = minimum + llFrand(maximum - minimum);
300     if (allow_negative) {
301         if (llFrand(1.0) < 0.5) to_return *= -1.0;
302     }
303     return to_return;
304 }
305
306 // strips the spaces off of the beginning and end of a string.
307 string strip_spaces(string to_strip)
308 {
309     // clean out initial spaces.
310     while (llGetSubString(to_strip, 0, 0) == " ")
311         to_strip = llDeleteSubString(to_strip, 0, 0);
312     // clean out ending spaces.
313     while (llGetSubString(to_strip, -1, -1) == " ")
314         to_strip = llDeleteSubString(to_strip, -1, -1);
315     return to_strip;
316 }
317
318 // parses a variable definition to find the name of the variable and its value.
319 // this returns two strings [X, Y], if "to_split" is in the form X=Y.
320 list separate_variable_definition(string to_split)
321 {
322     integer equals_indy = llSubStringIndex(to_split, "=");
323     // we don't support missing an equals sign, and we don't support it as the first character.
324     if (equals_indy <= 0) return [];  // no match.
325     string x = llGetSubString(to_split, 0, equals_indy - 1);
326     string y = llGetSubString(to_split, equals_indy + 1, -1);
327     to_split = "";  // save space.
328     return [ strip_spaces(x), strip_spaces(y) ];
329 }
330
331 // returns a non-empty string if "to_check" defines a value for "variable_name".
332 // this must be in the form "X=Y", where X is the variable_name and Y is the value.
333 string get_variable_value(string to_check, string variable_name)
334 {
335     list x_y = separate_variable_definition(to_check);
336     if (llGetListLength(x_y) != 2) return "";  // failure to parse a variable def at all.
337     if (!is_prefix(llList2String(x_y, 0), variable_name)) return "";  // no match.
338     return llList2String(x_y, 1);  // a match!
339 }
340
341 // examines all entries that we got from the notecard to see if any contain definitions.
342 // this is basically an INI file reader, but it uses a list instead of a file.
343 // ini files provide a format with multiple sections of config information, like so:
344 //    [section_1]
345 //    name1=value1
346 //    name2=value2 ...etc...
347 //    [section_2]
348 //    name1=value1 ...etc...
349 process_ini_config()
350 {
351 //    log_it("scanning notecard for variable definitions...");
352     integer indy;
353     integer count = llGetListLength(global_config_list);
354     string section_name;  // set later if we see one.
355
356     // iterate across the items in our configuration to look for ones that are not done yet.            
357     for (indy = global_config_index; indy < count; indy++) {
358         string line = llList2String(global_config_list, indy);
359         // search for a section beginning.
360         if (llGetSubString(line, 0, 0) == "[") {
361             // we found the start of a section name.  now read the contents.
362             indy++;  // skip section line.
363             section_name = llGetSubString(line, 1, -2);
364             log_it("reading section: " + section_name);
365         }
366         integer sec_indy;
367         for (sec_indy = indy; sec_indy < count; sec_indy++) {
368             // read the lines in the section.
369             line = llList2String(global_config_list, sec_indy);
370             if (llGetSubString(line, 0, 0) != "[") {
371                 // try to interpret this line as a variable setting.  this is just
372                 // one example of a way to handle the config file; one might instead
373                 // want to do something below once a whole section is read.
374                 parse_variable_definition(line);
375                 indy = sec_indy;  // track that we've passed this line.
376             } else {
377                 // we're at the beginning of a new section now, so start processing its
378                 // configuration in the outer loop.
379                 indy = sec_indy - 1;  // set indy to proper beginning of section.
380                 global_config_index = indy;  // remember where we had read to.
381                 sec_indy = count + 3;  // skip remainder of inner loop.
382             }
383         }
384     }
385
386     global_config_index = 0;  // reset outer position if want to re-read.
387 }
388
389 // locates the item with "name_to_find" in the inventory items with the "type".
390 // a value from 0 to N-1 is returned if it's found, where N is the number of
391 // items in the inventory.
392 integer find_in_inventory_partial(string name_to_find, integer inv_type)
393 {
394     integer num_inv = llGetInventoryNumber(inv_type);
395     if (num_inv == 0) return -1;  // nothing there!
396     integer inv;
397     for (inv = 0; inv < num_inv; inv++) {
398         if (is_prefix(llGetInventoryName(inv_type, inv), name_to_find))
399             return inv;
400     }
401     return -2;  // failed to find it.
402 }
403
404 //////////////
405 // huffware script: auto-retire, by fred huffhines, version 1.9.
406 // distributed under BSD-like license.
407 //   partly based on the self-upgrading scripts from markov brodsky and jippen faddoul.
408 // the function auto_retire() should be added *inside* a version numbered script that
409 // you wish to give the capability of self-upgrading.
410 //   this script supports a notation for versions embedded in script names where a 'v'
411 // is followed by a number in the form "major.minor", e.g. "grunkle script by ted v8.2".
412 // when the containing script is dropped into an object with a different version, the
413 // most recent version eats any existing ones.
414 //   keep in mind that this code must be *copied* into your script you wish to add
415 // auto-retirement capability to.
416 //
417 // example usage of the auto-retirement script:
418 //
419 // default {
420 //    state_entry() {
421 //        auto_retire();  // make sure newest addition is only version of script.
422 //    }
423 // }
424 auto_retire() {
425     string self = llGetScriptName();  // the name of this script.
426     list split = compute_basename_and_version(self);
427     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
428     string basename = llList2String(split, 0);  // script name with no version attached.
429     string version_string = llList2String(split, 1);  // the version found.
430     integer posn;
431     // find any scripts that match the basename.  they are variants of this script.
432     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
433         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
434         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
435             // found a basic match at least.
436             list inv_split = compute_basename_and_version(curr_script);
437             if (llGetListLength(inv_split) == 2) {
438                 // see if this script is more ancient.
439                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
440                 if ((float)inv_version_string < (float)version_string) {
441                     // remove script with same name from inventory that has inferior version.
442                     llRemoveInventory(curr_script);
443                 }
444             }
445         }
446     }
447 }
448 //
449 // separates the base script name and version number.  used by auto_retire.
450 list compute_basename_and_version(string to_chop_up)
451 {
452     if (llSubStringIndex(to_chop_up, " ") < 0) return [];  // no space found, not a valid name to work on.
453         
454     string basename = to_chop_up;  // script name with no version attached.
455     
456     integer posn;
457     // minimum script name is 2 characters plus version.
458     for (posn = llStringLength(to_chop_up) - 1;
459         (posn >= 2) && (llGetSubString(to_chop_up, posn, posn) != " ");
460         posn--) {
461         // find the space.  do nothing else.
462     }
463     if (posn < 2) return [];  // no space found.
464     string full_suffix = llGetSubString(to_chop_up, posn, -1);
465     // ditch the space character for our numerical check.
466     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
467     // strip out a 'v' if there is one.
468     if (llGetSubString(chop_suffix, 0, 0) == "v")
469         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
470     // if valid floating point number and greater than zero, that works for our version.
471     if ((float)chop_suffix > 0.0) {
472         // this is a big success right here.
473         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
474         return [ basename, chop_suffix ];
475     }
476     // seems like we found nothing useful.
477     return [];
478 }
479 //
480 //////////////
481
482 // end hufflets
483 //////////////
484
485 //////////////
486 // from noteworthy:
487
488 // huffware script: noteworthy library, by fred huffhines.
489 //
490 // a handy approach to reading a notecard.  this version supports requiring
491 // a 'signature' in the notecard's first line, so that multiple notecards can
492 // exist in an object without being misinterpreted.  the script is accessed via
493 // its link message API, so it can be used in an object without all this code
494 // needing to be embedded in another script.  it also supports queuing up requests
495 // to read notecards, so multiple scripts can use it to read their specific
496 // notecards without any special handling (besides waiting a bit longer).
497 //
498 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
499 // do not use it in objects without fully realizing you are implicitly accepting that license.
500 //
501
502 // constants that can be adapted to your needs...
503
504 integer DEBUGGING = FALSE;
505     // if this is true, then a lot of extra noise is generated when notecards are read.
506
507 float TIME_OUT_ON_ONE_NOTECARD = 120.0;
508     // we allow one line of a notecard this long to be read before we decide it's hosed.
509     // some sims are very very slow, and a time-out of one minute has been found lacking;
510     // we saw at least one case where the first notecard line to be read took longer than
511     // 60 seconds.  that's why we keep cranking this time-out up...
512
513 // constants that should not be changed...
514
515 // outcomes from handling a line in a notecard.
516 integer STILL_READING = -8;  // the notecard seems good, but isn't finished.
517 integer BAD_NOTECARD = -9;  // this notecard doesn't have our signature.
518 integer DONE_READING = -10;  // the notecard is finished being read.
519
520 integer LIST_ELEMENT_GUESS = 200;  // guess at how many bytes average list element uses.
521
522 integer MAXIMUM_LINES_USED = 4;
523     // we will read this many lines at a time from the appropriate notecard.
524 // global variables...
525
526 string requested_signature = "";
527     // if this is non-empty, then it must be found in the first line of the script.
528
529 integer only_read_one_notecard = FALSE;  // true if just one specific notecard should be used.
530
531 string global_notecard_name;  // the name of the card we're reading now.
532 key global_query_id = NULL_KEY;  // the identifier of our data query.
533 integer current_response_code = 0;  // the code that our client uses for its reading.
534 list global_query_contents;  // the lines we have read from the notecard.
535
536 integer line_number = 0;  // which line are we at in notecard?
537
538 integer found_signature_line = FALSE;  // did we find our first line in a notecard yet?
539
540 integer trying_notecard_at = -1;  // where we are currently looking for a good notecard.
541
542 list pending_signatures;  // signatures from queued requests for reading.
543 list pending_response_codes;  // response codes for the queued requests.
544 list pending_notecard_names;  // card names if it's a specific request.
545
546 //////////////
547
548 startup_initialize()
549 {
550     llSetTimerEvent(0.0);
551     pending_signatures = [];
552     pending_response_codes = [];
553     pending_notecard_names = [];
554     current_response_code = 0;
555 }
556
557 reset_for_reading(string signature, integer response_code_in)
558 {
559     requested_signature = signature;
560     current_response_code = response_code_in;
561     llSetTimerEvent(TIME_OUT_ON_ONE_NOTECARD);  // don't allow a read to happen forever.
562     global_query_contents = [];
563     global_notecard_name = "";
564     line_number = 0;
565     found_signature_line = FALSE;
566     trying_notecard_at = -1;
567     global_query_id = NULL_KEY;
568 }
569
570 // use the existing global notecard setting to start reading.
571 select_specific_notecard()
572 {
573     global_query_id = NULL_KEY;  // reset the query id so we don't get bogus answers.
574     line_number = 0;  // reset line number again.
575     global_query_id = llGetNotecardLine(global_notecard_name, 0);
576 }
577
578 // picks the notecard at the "index" (from 0 to num_notecards - 1) and
579 // starts reading it.
580 select_notecard(integer index)
581 {
582     global_query_id = NULL_KEY;  // reset the query id so we don't get bogus answers.
583     string card_specified = llGetInventoryName(INVENTORY_NOTECARD, index);
584     if (card_specified == "") return;   // not good.  bad index.
585     global_notecard_name = card_specified;
586     line_number = 0;  // reset line number again.
587     // we have a new file name, so load up the destinations, hopefully.
588     global_query_id = llGetNotecardLine(global_notecard_name, 0);
589 }
590
591 // increments our index in the count of notecards that the object has, and start
592 // reading the next notecard (at the index).
593 integer try_next_notecard()
594 {
595     if (only_read_one_notecard) {
596         return FALSE;  // we were only going to try one.
597     }
598     // reset some values that might have applied before.
599     global_notecard_name = "";
600     // skip to the next card.
601     trying_notecard_at++;
602     // make sure we're not over the count of cards.
603     if (trying_notecard_at >= llGetInventoryNumber(INVENTORY_NOTECARD)) {
604         // this is a problem.  we didn't find anything suitable.
605         return FALSE;
606     }
607     // so, now we'll try the next notecard to look for our signature.
608     select_notecard(trying_notecard_at);
609     return TRUE;
610 }
611
612 // process a line of text that we received from the current notecard.
613 integer handle_notecard_line(key query_id, string data)
614 {
615     // if we're not at the end of the notecard we're reading...
616     if (data != EOF) {
617         // there's more to read in the notecard still.
618         if (data != "") {
619             // make sure we even have a signature to look for.
620             if (!found_signature_line && (requested_signature == "")) {
621                 // no signature means that we always find it.
622                 found_signature_line = TRUE;
623             }
624             // did we already get our signature?  if not, see if this is it.
625             if (!found_signature_line && (data != requested_signature) ) {
626                 // this is a bad notecard.  skip it.
627                 if (!try_next_notecard()) {
628                     // we have no more to work with.
629                     return BAD_NOTECARD;
630                 }
631                 return STILL_READING;  // we'll keep going.
632             } else if (!found_signature_line && (data == requested_signature) ) {
633                 // this is a good signature line, so record that and then skip it.
634                 found_signature_line = TRUE;
635             } else {
636                 if (DEBUGGING
637                     && ( ( (requested_signature == "") && (line_number == 0) )
638                         || ( (requested_signature != "") && (line_number == 1) ) ) ) {
639                     log_it("started reading " + global_notecard_name + "...");
640                 }
641                 // don't record any lines that are comments.
642                 if ( (llGetSubString(data, 0, 0) != "#")
643                     && (llGetSubString(data, 0, 0) != ";") ) {
644                     // add the non-blank line to our list.
645                     global_query_contents += data;
646                     // make sure we still have enough space to keep going.
647                     if (llGetListLength(global_query_contents) >= MAXIMUM_LINES_USED) {
648                         // ooh, make sure we pause before blowing our heap&stack.
649                         send_reply(LINK_THIS, [ NOTECARD_READ_CONTINUATION,
650                             current_response_code ], READ_NOTECARD_COMMAND, TRUE);                
651                     }
652                 }
653             }
654         }
655         line_number++;  // increase the line count.
656         // reset the timer rather than timing out, if we actually got some data.
657         llSetTimerEvent(TIME_OUT_ON_ONE_NOTECARD);        
658         // request the next line from the notecard.
659         global_query_id = llGetNotecardLine(global_notecard_name, line_number);
660         if (global_query_id == NULL_KEY) {
661 //log_it("failed to restart notecard reading.");
662             return DONE_READING;
663 //is that the best outcome?
664         }
665         return STILL_READING;
666     } else {
667         // that's the end of the notecard.  we need some minimal verification that it
668         // wasn't full of garbage.
669         if (!found_signature_line) {
670             if (DEBUGGING) log_it("never found signature in " + global_notecard_name);
671             if (!try_next_notecard()) {
672                 return BAD_NOTECARD;  // we failed to find a good line?
673             } else {
674                 // the next notecard's coming through now.
675                 return STILL_READING;
676             }
677         } else {
678 //            if (DEBUGGING) log_it("found signature.");
679             // saw the signature line, so this is a good one.
680             return DONE_READING;
681         }
682     }
683 }
684
685 // only sends reply; does not reset notecard process.
686 send_reply(integer destination, list parms, string command,
687     integer include_query)
688 {
689 //log_it("froyo: curre code=" + current_response_code);
690 //integer items = llGetListLength(parms);
691 //if (include_query) items += llGetListLength(global_query_contents);
692 //log_it("pre-sending " + (string)items + " items, mem=" + (string)llGetFreeMemory());
693
694    if (!include_query) {
695         handle_link_message(destination, NOTEWORTHY_HUFFWARE_ID + REPLY_DISTANCE,
696             command, llDumpList2String(parms, HUFFWARE_PARM_SEPARATOR));
697     } else {
698         handle_link_message(destination, NOTEWORTHY_HUFFWARE_ID + REPLY_DISTANCE,
699             command,
700             llDumpList2String(parms + global_query_contents, HUFFWARE_PARM_SEPARATOR));
701     }
702     global_query_contents = [];
703 //log_it("post-sending, mem=" + (string)llGetFreeMemory());
704 }
705
706 // a simple version of a reply for a command that has been executed.  the parameters
707 // might contain an outcome or result of the operation that was requested.
708 send_reply_and_reset(integer destination, list parms, string command,
709     integer include_query)
710 {
711     llSetTimerEvent(0.0);  // stop the timer, since we're about to reply.
712     send_reply(destination, parms, command, include_query);
713 //log_it("about to reset response code");
714     current_response_code = 0;  // reset back to default so we can start another read.
715     global_query_id = NULL_KEY;  // reset so we accept no more data.
716 }
717
718 // if there are other pending notecard reads, this goes to the next one listed.
719 dequeue_next_request()
720 {
721     if (llGetListLength(pending_signatures)) {
722         // get the info from the next pending item.
723         string sig = llList2String(pending_signatures, 0);
724         integer response_code_temp = llList2Integer(pending_response_codes, 0);
725         string notecard = llList2String(pending_notecard_names, 0);
726         // whack the head of the queue since we grabbed the info.
727         pending_signatures = llDeleteSubList(pending_signatures, 0, 0);
728         pending_response_codes = llDeleteSubList(pending_response_codes, 0, 0);
729         pending_notecard_names = llDeleteSubList(pending_notecard_names, 0, 0);
730         if (llStringLength(notecard)) {
731             global_notecard_name = notecard;
732             select_specific_notecard();
733         } else {
734             reset_for_reading(sig, response_code_temp);
735         }
736     }
737 }
738
739 // deals with one data server answer from the notecard.
740 process_notecard_line(key query_id, string data)
741 {
742     // try to consume a line from the notecard.
743     integer outcome = handle_notecard_line(query_id, data);
744     if (outcome == DONE_READING) {
745         // that was a valid notecard and we read all of it.
746         if (DEBUGGING) log_it("finished reading " + global_notecard_name + ".");
747         // send back the results.
748         send_reply_and_reset(LINK_THIS, [ global_notecard_name, current_response_code ],
749             READ_NOTECARD_COMMAND, TRUE);
750     } else if (outcome == BAD_NOTECARD) {
751         // bail; this problem must be addressed by other means.
752         if (DEBUGGING) log_it("failed to find an appropriate notecard");
753         send_reply_and_reset(LINK_THIS, [ BAD_NOTECARD_INDICATOR, current_response_code ],
754             READ_NOTECARD_COMMAND, FALSE);
755     } else if (outcome == STILL_READING) {
756         // we have a good card and are still processing it.
757         return;
758     } else {
759         if (DEBUGGING) log_it("unknown outcome from handle_notecard_line");
760         // again, bail out.  we have no idea what happened with this.
761         send_reply_and_reset(LINK_THIS, [ BAD_NOTECARD_INDICATOR, current_response_code ],
762             READ_NOTECARD_COMMAND, FALSE);
763     }
764     // if we have reached here, we should crank up the next queued notecard reading.
765     dequeue_next_request();
766 }
767
768 // processes requests from our users.
769 noteworthy_handle_link_message(integer which, integer num, string msg, key id)
770 {
771     if (num != NOTEWORTHY_HUFFWARE_ID) return;  // not for us.
772
773     if (msg == READ_NOTECARD_COMMAND) {
774         only_read_one_notecard = FALSE;  // general inquiry for any card.
775         list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
776 //log_it("read notecard--parms are: " + (string)parms);
777         string signature = llList2String(parms, 0);
778         integer response_code_temp = llList2Integer(parms, 1);
779 //log_it("got signature " + signature + " and respcode " + (string)response_code_temp);
780 //holding:        if (!current_response_code) {
781             // go ahead and process this request; we aren't busy.
782             reset_for_reading(signature, response_code_temp);
783             if (!try_next_notecard()) {
784                 if (DEBUGGING) log_it("failed to find any appropriate notecards at all.");
785                 send_reply_and_reset(LINK_THIS, [ BAD_NOTECARD_INDICATOR, response_code_temp ],
786                     READ_NOTECARD_COMMAND, FALSE);
787                 return;
788             }
789 //holding:        } else {
790 //holding:            // we're already busy.
791 //holding://            send_reply_and_reset(LINK_THIS, [ BUSY_READING_INDICATOR, response_code_temp ],
792 //holding://                READ_NOTECARD_COMMAND, FALSE);
793 //holding:            // stack this request; another is in progress.
794 //holding:            pending_signatures += signature;
795 //holding:            pending_response_codes += response_code_temp;
796 //holding:            pending_notecard_names += "";
797 //holding:        }
798     } else if (msg == READ_SPECIFIC_NOTECARD_COMMAND) {
799         only_read_one_notecard = TRUE;  // they want one particular card.
800         list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
801 //log_it("read specific--parms are: " + (string)parms);
802         string signature = llList2String(parms, 0);
803         integer response_code_temp = llList2Integer(parms, 1);
804         string notecard_name = llList2String(parms, 2);
805 //log_it("got signature " + signature + " and respcode " + (string)response_code_temp);
806 //holding:        if (!current_response_code) {
807             // go ahead and process this request; we aren't busy.
808             reset_for_reading(signature, response_code_temp);
809             global_notecard_name = notecard_name;  // set our global.
810             select_specific_notecard();
811 //holding:        } else {
812 //holding:            // we're already busy.
813 //holding://            send_reply_and_reset(LINK_THIS, [ BUSY_READING_INDICATOR, response_code_temp ],
814 //holding://                READ_NOTECARD_COMMAND, FALSE);
815 //holding:            // stack this request; another is in progress.
816 //holding:            pending_signatures += signature;
817 //holding:            pending_response_codes += response_code_temp;
818 //holding:            pending_notecard_names += notecard_name;
819 //holding:        }
820     }
821 }
822
823     
824 default
825 {
826     state_entry() { if (llSubStringIndex(llGetObjectName(),  "huffotronic") < 0) state real_default; }
827     on_rez(integer parm) { state rerun; }
828 }
829 state rerun { state_entry() { state default; } }
830
831 state real_default
832 {
833     state_entry() {
834         auto_retire();  // make sure newest addition is only version of script.
835 /////not needed now        llSleep(1.0);  // snooze just a bit to let noteworthy start up?
836         startup_initialize();
837         initialize();  // start asking about the notecards.
838         setup_seating_arrangements();  // use our current defaults for sitting posn.
839     }
840
841     on_rez(integer parm) { llResetScript(); }
842
843     changed(integer change) {
844         if (change & CHANGED_INVENTORY) {
845 //            llSleep(3.14159265358);  // delay to avoid interfering with upgrade.
846             llResetScript(); 
847         }
848         if (!(change & CHANGED_LINK)) return;  // don't care.
849         if (!UNSEAT_AFTERWARDS) return;  // nothing else below is needed.
850         if (llAvatarOnSitTarget() == NULL_KEY) return;  // no one there, so ditto.
851         // now give them a bit of time to rest before dumping them.
852         llSetTimerEvent(PAUSE_BEFORE_EVICTION);
853     }
854     
855     timer() {
856         if (current_response_code != 0) {
857             llSetTimerEvent(0.0);  // stop any timer now.
858             // let the caller know this has failed out.
859             if (DEBUGGING) log_it("time out processing '" + requested_signature + "'");
860             send_reply_and_reset(LINK_THIS, [ BAD_NOTECARD_INDICATOR, current_response_code ],
861                 READ_NOTECARD_COMMAND, FALSE);
862             current_response_code = 0;  // we gave up on that one.
863             dequeue_next_request();  // get next reading started if we have anything to read.
864         } else {
865             // perform short range teleport, effectively...
866             llUnSit(llAvatarOnSitTarget());  // ha, got that guy back up.
867             llSetTimerEvent(0.0);  // reset timer.
868         }
869     }
870
871     // process the response from the noteworthy library.
872     link_message(integer which, integer num, string msg, key id)
873     { handle_link_message(which, num, msg, id); }
874
875     dataserver(key query_id, string data) {
876         // make sure this data is for us.
877         if (global_query_id != query_id) return;
878         // yep, seems to be.
879         process_notecard_line(query_id, data);
880     }            
881 }
882