normalized perms on all files, to avoid relying on any stored executable bits in...
[feisty_meow.git] / huffware / huffotronic_scripts / huff-search_brainiac_v48.1.txt
1 
2 // huffware script: huff-search brainiac, by fred huffhines
3 //
4 //    this script is one portion of a search system.  it is the brain for an object
5 // that can find nearby objects by a partial name match.  this script should be
6 // located in the root primitive.  it also requires an up-to-date jaunting library
7 // in the same primitive.  see the (hopefully) enclosed documentation for more details.
8 //    more implementation notes are stored at the back of the file.
9 //
10 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
11 // do not use it in objects without fully realizing you are implicitly accepting that license.
12 //
13
14 // global settings that can be very useful to change...
15
16 integer MAX_MATCHES = 17;
17     // by default we try to match one object per rod so we can point at them.
18
19 float MAX_SPIRAL_RADIUS = 72.0;
20     // the farthest that the object will travel from its home while searching.
21     // this is an important factor in the searchbert's range of vision; the other is
22     // the sensor range, below.
23     // ensure that it has access to the lands within this range or it might get stuck.
24     // you can also set the TRAVERSE_LANDS flag to false to make for safer searches when
25     // surrounded by a lot of banned lands.
26
27 float SENSOR_MAX_RANGE = 96.0;
28     // the maximum range that we try to sense objects at.  this is distinct from the spiral
29     // radius because often the range of movement is constrained by land conditions, where
30     // one might still want a large sensor radius to see as many things as possible in range.
31     // note though that searches will keep matching the things nearest to them if neither
32     // the position nor the angle nor object positions have changed.
33
34 float SPIRAL_LOOPS = 7;
35     // how many loops there are in the spiral.  this is measured by how many times the
36     // spiral cuts across the positive x-axis (that is, the zero angle vector) from
37     // the center of the spiral to the radius (that is, from <0, 0, 0> to <radius, 0, 0>).
38
39 integer TOTAL_STEPS = 42;
40     // how many positions within the spiral will the object travel to?  the first step
41     // is step 0, which is the center of the spiral.  positions 1 through TOTAL_STEPS
42     // spiral outward from the zero position, where the distance from the center at
43     // TOTAL_STEPS should be MAX_SPIRAL_RADIUS or less.
44     
45 integer MAX_SPIRAL_TRAVERSALS = 1;
46     // how many different spirals are we allowed for the same search?  this will let the
47     // search engine cover more ground than with just one spiral, to allow different
48     // objects to be exposed.
49
50 integer HUFF_SEARCH_CHAT_CHANNEL = 0;
51     // the channel where the object listens for commands.  the default is to use open
52     // chat for this, but some people may want it more specific.
53
54 // this flag is important to keep as false for wright plaza and other areas with script traps
55 // (where the perms allow objects to enter, but then their scripts are stopped dead).
56 integer TRAVERSE_LANDS = FALSE;
57     // if this is false, then the searchbert will stick to the land owner's land where it started.
58     // but if it's true, then searchbert will cross into other people's lands too, but if there
59     // are some weird border or permission conditions about object re-entry or scripts being able
60     // to run, that can be quite problematic.
61
62 integer TRAVELLING_UPWARDS = FALSE;
63     // if this is true, the searchbert will climb in the vertical direction also.
64
65 float MAX_UPWARDS_DISTANCE = 30.0;
66     // the farthest away that the searchbert will fly during an upwards search.
67
68 float SEARCH_ROD_ANGULAR_SWEEP = PI_BY_TWO;
69     // angular arc of the sensor cone, placeholder.
70
71 integer SEARCH_OBJECT_TYPE = 7;
72     // the kind of objects to find.  default is anything.
73
74 // these enable or disable items in the list displayed to the user for matches.
75 integer SHOW_NAME = TRUE;
76 integer SHOW_POSITION = TRUE;
77 integer SHOW_UUID = TRUE;
78
79 // the style of how searchbert presents its arms.
80 integer PRESENT_ARMS_STYLE = 0;  // PAS_CENTERED is the default.
81
82 //////////////
83
84 // constants that are not configurable in a notecard...
85
86 integer DEBUGGING = FALSE;  // set to true to make the script noisier.
87
88 // SENSOR_TYPE_ALL: a constant that tells the sensor to look for (ACTIVE|PASSIVE|AGENT).
89 integer SENSOR_TYPE_ALL = 7;
90
91 integer LARGEST_STRING = 800;  // the longest string we try to build at once.
92
93 //////////////
94
95 // global constants that aren't as useful to change...
96
97 float MINIMUM_HEIGHT_ABOVE_GROUND = 0.14;
98     // the closest we allow the searcher to get to the ground.  any lower and our search
99     // rods might be dragging around under ground.
100
101 float FAST_TIMER_INTERVAL = 0.12;
102     // the time between jumps when we're doing our search spiral.  this is the fastest
103     // the object can spin around its spiral trajectory, but it's more limited than by
104     // just this number; llSetPrimitiveParams is used for jaunting and it has a delay of
105     // 0.2 seconds built into it.
106
107 integer NORMAL_TIMER_INTERVAL = 14;
108     // how frequently we check for things to do, in seconds.
109
110 float STARTUP_TIME_ALLOWED = 50.0;  // number of seconds before declaring a timeout.
111
112 integer MAX_STEP_SNOOZES = 81;
113     // number of timer hits to allow before giving up on jaunt.
114
115 float SNOOZE_BEFORE_RESET = 300;
116     // number of seconds before a scan will automatically reset.  hopefully this is
117     // enough time for the user to follow the trail to the detected object.
118     
119 // imported interfaces below...
120
121 // huff-search pointer API:
122 //////////////
123 // do not redefine these constants.
124 integer HUFF_SEARCH_POINTER_HUFFWARE_ID = 10032;
125     // the unique id within the huffware system for this script.
126 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
127     // this pattern is an uncommon thing to see in text, so we use it to separate
128     // our commands in link messages.
129 string HUFFWARE_ITEM_SEPARATOR = "{|||}";
130     // used to separate lists of items from each other when stored inside a parameter.
131     // this allows lists to be passed as single string parameters if needed.
132 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
133 //////////////
134 string HUFF_SEARCH_RESET = "#reset#";
135     // returns the script to its starting state.
136 // constants for controlling how searchbert presents its arms when pointing.  they are the
137 // Present Arms Styles (PAS).
138 integer PAS_CENTERED = 0;
139     // original style of arm positioning for searchbert.  the arms are centered at the root prim's
140     // center, and they point towards the target.
141 string HUFF_SEARCH_POINT_PARTY = "#point_particles#";
142     // aim at an object and show a particle stream leading to it.  parms are a UUID key for the
143     // target, the target location vector and a PAS value.
144 string HUFF_SEARCH_JUST_POINT = "#just_point#";
145     // aim at an object, but don't do any particles.  parms are the target vector
146     // and a PAS value.
147 string HUFF_SEARCH_SENSEI = "#sensor#";
148     // set up a sensor request for a search pattern.  pings will cause
149     // the pattern to be sought in names of nearby objects.  the parameters are:
150     // (1) the maximum range for the sensor, (2) the arc angle to use in sensing,
151     // (3) the search pattern to look for in object names, (4) the maximum number
152     // of matches to look for, (5) the type of objects to find (e.g. SENSOR_TYPE_ALL
153     // or other values).
154 string HUFF_SEARCH_STOP_SENSE = "#stop_sensor#";
155     // turn off the sensor but don't totally reset.
156 string HUFF_SEARCH_PING = "#ping#";
157     // cause the searcher to actively sensor ping the targets.
158 string HUFF_SEARCH_MATCH_EVENT = "#match#";
159     // fired at the root prim when matches are found for the search term.
160     // the payload is a list of matched item pairs [item key, location].
161 //////////////
162
163 // the armature button pushing API.
164 // (we have subclassed the simple button pushing API for searchbert armature.)
165 //////////////
166 integer BUTTON_PUSHER_HUFFWARE_ID = 10029;
167     // a unique ID within the huffware system for this script.
168 //////////////
169 string BUTTON_PUSHED_ALERT = "#btnp";
170     // this event is generated when the button is pushed.  the number parameter will be
171     // the huffware id plus the reply distance.  the id parameter in the link message will
172     // contain the name of the button that was pushed.
173 //////////////
174 string CHECK_ARMS_BUTTON_NAME = "^checkarms";
175     // this is the signal given to the armature script that it should check the
176     // number of arms present on searchbert.  if the number is fine, it will
177     // push the arms are good button back at the brainiac (using the button
178     // push api plus reply distance).
179 string ARMS_ARE_GOOD_BUTTON_NAME = "^goodarmz";
180     // the event sent back by the searchbert armature when all arms are ready
181     // to go.
182 string PROBLEM_WITH_MY_THUMBS_BUTTON_NAME = "^ouch";
183     // a problem was noticed with the number of arms and we could not fix it.
184     // the brain needs to try reconfiguring again.
185 //////////////
186
187 // searchbert menus API.
188 //////////////
189 // do not redefine these constants.
190 integer SEARCHBERT_MENUS_HUFFWARE_ID = 10034;
191     // the unique id within the huffware system for this script.
192 //////////////
193 string SM_CONFIGURE_INFO = "#sm-info#";
194     // sets important information this script will use, such as (1) the channel for listening.
195 string SM_POP_MAIN_MENU_UP = "#sm-main#";
196     // causes the main menu to be displayed.  this requires an avatar name and avatar key for the
197     // target of the menu.
198 //////////////
199 string SM_EVENT_MENU_CLICK = "#sm-clik#";
200     // the user has requested a particular menu item that this script cannot fulfill.  the
201     // event is generated back to the client of this script for handling.  it will include (1) the
202     // menu name in question, (2) the item clicked, (3) the avatar name, and (4) the avatar key.
203 //////////////
204
205 // card configurator link message API:
206 //////////////
207 // do not redefine these constants.
208 integer CARD_CONFIGURATOR_HUFFWARE_ID = 10042;
209     // the unique id within the huffware system for the card configurator script to
210     // accept commands on.  this is used in llMessageLinked as the num parameter.
211 //////////////
212 string BAD_NOTECARD_TEXT = "*badcrd*";
213     // the sign that we hated the notecards we found, or there were none.
214 string FINISHED_READING_NOTECARDS = "**finished**";
215     // the sign that we are done plowing through the card we found.
216 string BEGIN_READING_NOTECARD_COMMAND = "#read-cfg#";
217     // requests that the configurator find a good notecard and read its contents.
218     // it should send the contents via the alert below.  first parm is the signature and
219     // second is the wrapped list of valid item prefixes.
220 string READ_PARTICULAR_NOTECARD_COMMAND = "#read-note#";
221     // requests that the configurator find a good notecard and read its contents.
222     // it should send the contents via the alert below.  first two parms are the same as
223     // begin reading notecard, and the third parameter is the name of the specific notecard.
224 string CARD_CONFIG_RECEIVED_ALERT = "#cfg-event-upd#";
225     // this message is sent when the configurator has found some data updates or has finished
226     // reading the configuration file.
227 //////////////
228
229 // jaunting library API:
230 //////////////
231 // do not redefine these constants.
232 integer JAUNT_HUFFWARE_ID = 10008;
233     // the unique id within the huffware system for the jaunt script to
234     // accept commands on.  this is used in llMessageLinked as the num parameter.
235 //////////////
236 // commands available via the jaunting library:
237 string JAUNT_COMMAND = "#jaunt#";
238     // command used to tell jaunt script to move object.  pass a vector with the location.
239 //
240 //////////////
241
242 // global variables used in the script.
243
244 // configuration variables...
245 integer all_setup_finished = FALSE;  // have we read our configuration yet?
246 integer configuration_pending = FALSE;  // true if the setup process (config and arms) is still going on.
247 integer listening_handle = 0;  // tracks our handle for listening to commands.
248
249 // matching variables...
250 string global_target_name = "";  // the name of the object being sought.
251
252 list global_matches_found;  // a list of keys that match the specified search terms.
253 list global_positions_found;  // matches list of positions for the detected objects.
254
255 // jaunting variables...
256
257 vector global_home_posn;  // the location where the search bot is located.
258 vector last_safe_target;  // the last place we jaunted to that was safe.
259
260 integer next_step_snoozes_left;  // pauses allowed before deciding jaunt will not respond.
261
262 integer jaunt_responses_awaited = 0;  // true when a jaunt is pending.
263 integer last_jaunt_was_success = FALSE;  // result of jaunting received by message.
264
265 vector current_rotation = <0.0, 0.0, 0.0>;
266   // the current rotation around each axis for object.
267
268 // spiral variables...
269
270 integer global_current_step = 0;  // the current position in the search spiral.
271 float spiral_start_angle = 0.0;  // how many radians to offset spiral by for this pass.
272 integer global_current_pass = 0;  // which spiral number are we working on?
273
274 integer tried_jump_homeward = FALSE;
275     // when retracing to home, this records if we already tried the jump home that should
276     // come in between the spiral jaunt.
277
278 integer retracing_steps = FALSE;
279     // this is true when we are trying to get back home after finishing our spirals.
280
281 // object maintenance variables...
282
283 integer reset_for_next_timer = FALSE;  // true when next timer hit should do a reset.
284
285 integer running_a_search = FALSE;  // true if the object is seeking matches.
286
287 //////////////
288
289 // constants that should not be messed with.
290
291 float MAX_SLACK_DISTANCE = 0.01;  // how close we need to be to a target.
292
293 integer ALL_SEEKER_ALERT = -1;  // communicates with all search rods.
294
295 integer last_time_ordered_stop_sensing = 0;
296     // tracks when we last tried to order the search rods to stop sensing matches.
297
298 // jaunting variables...
299
300 vector last_jaunt_target;
301     // where we're currently headed.  this variable is mostly for record keeping, so we want
302     // to update it whenever we jaunt someplace.
303
304 //////////////
305
306 //hmmm: copy this to hufflets
307
308 // sets the timer safely, to get around a second life bug that sometimes
309 // drops the timer set unless there's a reset first.  nasty!
310 set_timer(float interval)
311 {
312     llSetTimerEvent(0);
313     llSetTimerEvent(interval);
314 }
315
316 //////////////
317
318 // main functions for getting work done as the searchbert...
319
320 // pointing that doesn't use particles, but just aims a search rod.
321 aim_at_position(integer which_seeker, vector targetPosition, integer pas_style) {
322     list paramList = [targetPosition, pas_style];
323     request_from_seeker(which_seeker, llDumpList2String(paramList,
324         HUFFWARE_PARM_SEPARATOR), HUFF_SEARCH_JUST_POINT);
325 }
326
327 // tells the rod at "which_seeker" link to do a sensor scan.
328 start_sensing(integer which_seeker, float max_range, float arc_angle, string search_pattern,
329     integer matches_sought, integer object_type)
330 {
331     list paramList = [max_range, arc_angle, search_pattern, matches_sought, object_type];
332     request_from_seeker(which_seeker, llDumpList2String(paramList,
333         HUFFWARE_PARM_SEPARATOR), HUFF_SEARCH_SENSEI);
334 }
335
336 // tells all of the seeker search rods to stop sensing matches.
337 stop_sensing()
338 {
339     // make sure that we are not just blasting this order over and over.
340     if (llGetUnixTime() != last_time_ordered_stop_sensing) {
341         last_time_ordered_stop_sensing = llGetUnixTime();
342         request_from_seeker(ALL_SEEKER_ALERT, "", HUFF_SEARCH_STOP_SENSE);
343     }
344 }
345
346 // tell the seeker arms to find what we asked them about.
347 request_ping() { request_from_seeker(ALL_SEEKER_ALERT, "", HUFF_SEARCH_PING); }
348
349 //////////////
350
351 // teleports to the vector specified.  this invokes a method in the jaunting library
352 // which will return its result asynchronously.  thus we can't just expect that we
353 // have arrived at the target by the end of this function; we need to get back the
354 // IPC message in linked_message.
355 jaunt_to_target(vector target)
356 {
357     if (!TRAVERSE_LANDS) {
358         // this is an important restriction since we don't want to get trapped in weird
359         // land perm screwups, like not being able to re-enter the land where we started,
360         // if that parcel option is set.
361         if (llGetLandOwnerAt(llGetPos()) != llGetLandOwnerAt(target)) {
362             return;
363         }
364     }
365     
366     // reset our snoozer count, since we're doing a new jaunt now.
367     next_step_snoozes_left += MAX_STEP_SNOOZES;
368     jaunt_responses_awaited++;
369     // record the current target.
370     last_jaunt_target = target;
371
372     float minimum_rod_angle_addition = 0.2;
373     float maximum_rod_angle_addition = 10.8;
374     // add small random amounts to the current rotation to expose more matches.
375     current_rotation +=
376         <(minimum_rod_angle_addition + llFrand(maximum_rod_angle_addition)) * DEG_TO_RAD,
377         (minimum_rod_angle_addition + llFrand(maximum_rod_angle_addition)) * DEG_TO_RAD,
378         (minimum_rod_angle_addition + llFrand(maximum_rod_angle_addition)) * DEG_TO_RAD>;
379     rotation new_rot = llEuler2Rot(current_rotation);
380 //    log_it("new rot to " + (string)new_rot + " based on " + (string)current_rotation);
381     llMessageLinked(LINK_THIS, JAUNT_HUFFWARE_ID, JAUNT_COMMAND,
382         (string)target + HUFFWARE_PARM_SEPARATOR + (string)new_rot);
383 }
384
385 // provides the position on a spiral that has "loops" total loops (counted by
386 // how many times a line from the center to the outer "radius" is crossed).
387 // this provides an x and y offset from 0,0 for where the spiral should be if
388 // one were to walk it in "total_steps" (where the center is step 0).  this is
389 // given for the current "step" one is at.  the "start_angle" is the number of
390 // radians to start at for the spiral, to allow different areas to be traversed.
391 vector trace_spiral(float loops, float radius, integer total_steps, integer step,
392     float start_angle)
393 {
394     float total_radians = TWO_PI * loops;
395     float angle_per_step = total_radians / (float)total_steps;
396     float distance = radius / (float)total_steps * (float)step;
397     float current_angle = start_angle + angle_per_step * (float)step;
398     float current_z = 0;
399     if (TRAVELLING_UPWARDS) {
400         // add in the vertical distance for this step.
401         current_z = MAX_UPWARDS_DISTANCE / total_steps * step;
402     }
403     return <distance * llCos(-current_angle), distance * llSin(-current_angle), current_z>;
404 }
405
406 // this describes the list of matches in local chat.
407 chat_about_matches()
408 {
409     integer len = llGetListLength(global_matches_found);
410     if (!len) {
411         llSay(0, global_target_name + " not found within a distance of "
412             + (string) (SENSOR_MAX_RANGE + MAX_SPIRAL_RADIUS) + " meters from here.");
413         return;
414     }
415     string addition;
416     if (len != 1) addition = "es";
417     string match_description = (string)len + " match" + addition + " for search "
418         + "pattern \'" + global_target_name + "\':\n";
419     integer i;
420     // only show a maximum number of matches as we have seeker objects.
421     if (len > MAX_MATCHES) len = MAX_MATCHES;
422     for (i = 0; i < len; i++) {
423         if (llStringLength(match_description) > LARGEST_STRING) {
424             llSay(0, "\n" + match_description);
425             match_description = "";
426         } else if ( (i != 0) && (SHOW_NAME || SHOW_POSITION || SHOW_UUID) ) {
427             match_description += "\n";
428         }
429         key targetKey = llList2Key(global_matches_found, i);
430         if (SHOW_NAME) match_description += llKey2Name(targetKey) + " ";
431         if (SHOW_POSITION) {
432             vector targetPos = llList2Vector(global_positions_found, i);
433             match_description += "@ " + vector_to_string(targetPos) + " ";
434         }
435         if (SHOW_UUID) match_description += "[" + (string)targetKey + "]";
436     }
437     llSay(0, "\n" + match_description);
438 }
439
440 // once we accumulate a set of matches, we want to show them off.
441 show_matches()
442 {
443     llSetRot(llEuler2Rot(ZERO_VECTOR));  // set the object to point at the zero vector.    
444     reset_rod(ALL_SEEKER_ALERT);  // clean up any current pointing first.
445     chat_about_matches();  // say where the matches are.
446     
447     integer i;
448     integer which_locater = 0;  // which pointer to use.
449     // only show a maximum number of matches as we have seeker objects.
450     integer len = llGetListLength(global_matches_found);
451     if (len > MAX_MATCHES) len = MAX_MATCHES;
452     for (i = 0; i < len; i++) {
453         key targetKey = llList2Key(global_matches_found, i);
454         vector targetPos = llList2Vector(global_positions_found, i);
455         point_at_with_particles(which_locater++, targetKey, targetPos, PRESENT_ARMS_STYLE);
456     }
457 }
458
459 // makes sure that a target we are given is above ground.  this used to do a
460 // lot more checking, but really being above ground is the most important thing
461 // for us to check at this level of the code.
462 vector clean_target(vector to_clean)
463 {
464     vector to_return = to_clean;
465     float ground_height = llGround(to_return - llGetPos());
466 //log_it("ground height here: " + (string)ground_height);
467
468     // we'll adjust the basic ground height by adding in the object's height.
469     list bounds = llGetBoundingBox(llGetKey());
470 //hmmm: we have found a bug in opensim in that the bounding box only covers the root prim.
471 // this needs to be reported.
472     vector min = llList2Vector(bounds, 0);
473     vector max = llList2Vector(bounds, 1);
474 //log_it("calcd: min=" + (string)min + " max=" + (string)max);
475
476 //real math    float distance_to_add = llVecDist(<0, 0, min.z>, <0, 0, max.z>) / 2.0;
477 //below is bogus math for opensim currently.
478     float distance_to_add = llVecDist(<0, 0, min.z>, <0, 0, max.z>) * 1.1;
479     
480 //log_it("distance_to_add: " + (string)distance_to_add);
481     if (to_return.z - MINIMUM_HEIGHT_ABOVE_GROUND <= ground_height + distance_to_add) {
482         // patch up the height to be above ground.
483         to_return.z = ground_height + distance_to_add + MINIMUM_HEIGHT_ABOVE_GROUND;
484     }
485     return to_return;
486 }
487
488 // shows all the matches by pointing our seekers at them and emitting a targeted
489 // trail of particles.  this method should only be called after the final jaunt
490 // back to home has occurred.
491 show_off_what_was_found()
492 {
493     // show the positions of what was found.
494     show_matches();
495     set_timer(SNOOZE_BEFORE_RESET);
496     reset_for_next_timer = TRUE;
497 }
498
499 // stops the device from travelling around and asking for help from the search rods.
500 integer finish_spiral_traversal()
501 {
502 //log_it("got to finish spiral...");
503     stop_sensing();  // turn off all sensors.
504
505     // are we close enough to home to declare victory?
506     if (llVecDist(llGetPos(), global_home_posn) > MAX_SLACK_DISTANCE) {
507         if (!tried_jump_homeward) {
508             // there are enough here; we completed early.
509             tried_jump_homeward = TRUE;
510 //log_it("finish spiral sees us as too far from home, jaunting there.");
511             jaunt_to_target(global_home_posn);
512             return FALSE;
513         } else {
514             // we already tried a jump home.  dang, let's try spiraling.
515 //log_it("finish spiral failed jaunt home, continuing spiral.");
516             tried_jump_homeward = FALSE;  // reset that we tried this.
517             return TRUE;
518         }
519     }
520
521 //log_it("finish spiral success, showing off matches");
522     
523     // this object has done enough spiraling.
524     set_timer(NORMAL_TIMER_INTERVAL);  // turn off jump timer.
525     running_a_search = FALSE;  // reset our state since the search is done.
526     show_off_what_was_found();
527     return FALSE;
528 }
529
530 // our timer handling function; this will move the search engine to the next place on
531 // the current spiral (or to the start of the next spiral) when it is called.
532 // if we're not currently running a search, then it will just periodically update the
533 // sub-prims to make sure they have the latest versions.
534 handle_timer()
535 {
536     if (!all_setup_finished) {
537         complain_about_config(!configuration_pending);
538         return;  // should not get here.
539     }
540     
541     if (reset_for_next_timer) {
542         // this timer intends a reset so we don't just keep pointing forever.
543         llSay(0, "Timed Out: resetting matches now.");
544         reset_search();
545         return;
546     }
547
548     if (!running_a_search) {
549 //log_it("exiting timer since not searching.");
550         return;
551     }
552
553 //llSay(0, "next search move!");
554             
555     // make sure we don't allow too many pauses while awaiting a jaunt completion.
556     if (next_step_snoozes_left-- <= 0) {
557         log_it("waiting to arrive failed!  ran out of snoozes trying to get to "
558             + (string)last_jaunt_target);
559     } else if (jaunt_responses_awaited) {
560         // not ready to do next step yet.
561         return;
562     }
563     if (next_step_snoozes_left < 0) {
564 //log_it("got below zero in next step snoozes!");
565         next_step_snoozes_left = 0;
566     }
567     
568     if (llGetListLength(global_matches_found) < MAX_MATCHES) {
569         // tell the sensor arms to look for stuff right here.
570         request_ping();
571     }
572
573     // make sure we're not already done finding enough objects.
574     if (llGetListLength(global_matches_found) >= MAX_MATCHES) retracing_steps = TRUE;
575     
576     // check whether we're trying to get home again, rather than moving forward.
577     if (retracing_steps) {
578 //log_it("retrace steps in timed move.");
579         integer keep_going = finish_spiral_traversal();
580         if (!keep_going) return;
581     }
582
583     // see if the object has reached the end of its tether and should report
584     // home with results.  we do this by taking a spiral pass outwards from home
585     // and a return pass to get back to home.  if we've used up all our spiral
586     // traversals, then it's time to stay home and show the matches.
587     integer done_with_this_spiral = FALSE;
588     if (global_current_pass % 2 == 0) {
589         // even passes are outward bound ones.  we're done when we've gotten to TOTAL_STEPS.
590         if (global_current_step++ > TOTAL_STEPS) done_with_this_spiral = TRUE;
591     } else {
592         // odd passes are for returning to home.  those are done when they hit zero.
593         if (global_current_step-- <= 0) done_with_this_spiral = TRUE;
594     }
595     
596     if (done_with_this_spiral) {
597         // now evaluate whether we're totally done or just need to move to next spiral,
598         // whether inward or outward.
599         if (++global_current_pass < 2 * MAX_SPIRAL_TRAVERSALS) {
600             // just step to the next spiral.
601 //log_it("moving to next spiral");
602             if (global_current_pass % 2 == 0) {
603                 // even passes are outward bound ones.
604                 global_current_step = 0;
605                 // add some different angular rotation to get more matches for this spiral.
606                 spiral_start_angle += TWO_PI / (MAX_SPIRAL_TRAVERSALS + 1);
607             } else {
608                 // odd passes are for returning to home.
609                 global_current_step = TOTAL_STEPS;
610             }
611 //hmmm: not currently resetting that angle for next search.
612         } else {
613 //log_it("done with spiral mode, now retracing steps.");
614             // we finished the search pattern.
615             retracing_steps = TRUE;
616             global_current_pass--;  // try spiraling back.
617             global_current_step = TOTAL_STEPS;
618             return;
619         }
620     }        
621
622     // normal activity here--pick the next place on the spiral to look for objects.        
623     vector new_posn = trace_spiral(SPIRAL_LOOPS, MAX_SPIRAL_RADIUS,
624         TOTAL_STEPS, global_current_step, spiral_start_angle);
625 //log_it("next step " + (string)global_current_step + " to " + (string)new_posn);        
626     // go to that location now, or rather, when the jaunting library gets the message.
627     vector new_target = clean_target(new_posn + global_home_posn);
628     jaunt_to_target(new_target);
629 }
630
631 // makes sure we are ready to run.  TRUE is returned if we're good.
632 integer test_health()
633 {
634     if (!configuration_pending && !all_setup_finished) {
635         llSay(0, "Configuration is not good yet; retrying.");
636         return FALSE;
637     }
638     return TRUE;
639 }
640
641 // deals with the jaunter telling us about a completed jump.
642 process_jaunt_response(string str)
643 {
644     jaunt_responses_awaited--;  // one less response being awaited.
645     if (jaunt_responses_awaited < 0) {
646         if (DEBUGGING)
647             log_it("erroneously went below zero for jaunt responses!");
648         jaunt_responses_awaited = 0;
649     }
650     // unpack the reply.
651     list parms = llParseString2List(str, [HUFFWARE_PARM_SEPARATOR], []);
652     last_jaunt_was_success = (integer)llList2String(parms, 0);
653     vector posn = (vector)llList2String(parms, 1);
654 //log_it("got a reply for a jaunt request, success=" + (string)last_jaunt_was_success + " posn=" + (string)posn);
655     if (last_jaunt_was_success) {
656         last_safe_target = posn;
657     } else {
658         // we had a problem getting to the expected destination, so go to the last place we were
659         // completely safely able to reach.  we should have no problem returning there, since that's
660         // where we should have been coming from when we failed to reach the intended destination.
661 //log_it("bkwd retracing to " + (string)last_safe_target);
662         jaunt_to_target(last_safe_target);
663     }
664 }
665
666 reset_search()
667 {
668     global_current_step = 0;
669     global_current_pass = 0;
670     global_matches_found = [];
671     global_positions_found = [];
672     next_step_snoozes_left = 4;  // reset to small num, since this is additive.
673     reset_for_next_timer = FALSE;
674     running_a_search = FALSE;
675     tried_jump_homeward = FALSE;
676     retracing_steps = FALSE;
677     jaunt_responses_awaited = 0;
678     current_rotation = <0.0, 0.0, 0.0>;
679     // fix a global 'constant' that can't be pre-initiatlized in LSL.
680     SEARCH_ROD_ANGULAR_SWEEP = (PI_BY_TWO / 4.0);
681         // PI_BY_TWO / 4 is 22.25 degrees, which when turned into a sensor cone
682         // will be a range of 45 degrees around the zero vector.
683
684     set_timer(NORMAL_TIMER_INTERVAL);  // back to slow timer hits.
685     reset_rod(ALL_SEEKER_ALERT);  // reset the pointers to camber position.
686     llSetRot(llEuler2Rot(ZERO_VECTOR));  // set the object to point at the zero vector.
687
688     // set the home position to wherever we happen to be right now.
689     global_home_posn = clean_target(llGetPos());
690     llSetPos(global_home_posn);  // get us off the ground.
691     last_safe_target = global_home_posn;    
692 }
693
694 initialize()
695 {
696     llSay(0, "Initializing... this may take a few seconds.");
697     auto_retire();
698     llSleep(0.2);  // we ensure part of the claim above by waiting for sub-scripts to start.
699     // cannot initialize this in statics for some reason...
700     SEARCH_OBJECT_TYPE = SENSOR_TYPE_ALL;
701     request_configuration("");
702 }
703
704 // complete the initialization once we know our configuration.
705 finish_initializing()
706 {
707     all_setup_finished = TRUE;  // cancel the time-out checker.
708     configuration_pending = FALSE;
709
710     // in case we already have some arms, clean up their pointing states.
711     reset_search();
712     // set the position of rotation back to zero.
713     llSetRot(<0.0, 0.0, 0.0, 1.0>);
714     // listen for commands from our chat channel.
715     listening_handle = llListen(HUFF_SEARCH_CHAT_CHANNEL, "", NULL_KEY, "");
716
717     llSay(0, "Running and ready to search.  Touch for more instructions.");
718
719     set_timer(NORMAL_TIMER_INTERVAL);    
720 }
721
722 // this points the rods at all angles we possibly can to get the best coverage.
723 // if show_particles is true, then a demo mode is used that points at the positions
724 // that the rods are aiming at.
725 skew_rod_angles(integer show_particles)
726 {
727     reset_rod(ALL_SEEKER_ALERT);
728         // point everyone straight up for the moment.        
729     float radius = 4.0;  // arbitrary distance of target we're aiming at.
730     integer which_child;
731     integer total_searchers = llGetNumberOfPrims() - 1;
732     float angle_per_step = TWO_PI / (float)total_searchers;
733     // use a circle for the x and y coordinates.
734     for (which_child = 0; which_child < total_searchers; which_child++) {
735         vector spinner = <
736             radius * llCos((float)which_child * angle_per_step),
737             radius * llSin((float)which_child * angle_per_step),
738             radius * llCos((float)which_child * angle_per_step / 2.0)>;
739         vector target_location = llGetPos() + spinner;
740         if (!show_particles) {
741             aim_at_position(which_child, target_location, PAS_CENTERED);
742         } else {
743             point_at_with_particles(which_child, NULL_KEY, target_location, PAS_CENTERED);
744         }
745     }
746 }
747
748 // if "noisy" is true, this says out loud that the searchbert is busy.
749 integer check_if_search_pending(integer noisy)
750 {
751     if (running_a_search) {
752         if (noisy) llSay(0, "A search is still pending.  Please wait for that to finish.");
753         return TRUE;  // still working on a search.
754     }
755     return FALSE;  // not busy.
756 }
757
758 // processes a message coming back from a search rod or from the jaunter library.
759 handle_link_message(integer which, integer num, string msg, key id)
760 {
761     if ( (num == CARD_CONFIGURATOR_HUFFWARE_ID + REPLY_DISTANCE)
762             && (msg == CARD_CONFIG_RECEIVED_ALERT) ) {
763         // the first element of the list will still be the notecard name.
764         consume_configuration(llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []));
765         return;
766     }
767     
768     if ( (num == BUTTON_PUSHER_HUFFWARE_ID +  REPLY_DISTANCE)
769             && (msg == BUTTON_PUSHED_ALERT) ) {
770         if (id == ARMS_ARE_GOOD_BUTTON_NAME) {
771             finish_initializing();
772         } else if (id == PROBLEM_WITH_MY_THUMBS_BUTTON_NAME) {
773             complain_about_config(TRUE);
774         }
775         return;
776     }
777     
778     if (num == JAUNT_HUFFWARE_ID + REPLY_DISTANCE) {
779         if (msg == JAUNT_COMMAND) {
780             process_jaunt_response(id);
781         }
782         return;
783     }
784     
785     list parms;
786     
787     if ( (num == SEARCHBERT_MENUS_HUFFWARE_ID + REPLY_DISTANCE) && (msg == SM_EVENT_MENU_CLICK) ) {
788         parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
789         process_menu_choice(llList2String(parms, 0), llList2String(parms, 2), llList2String(parms, 3),
790             llList2String(parms, 1));
791         return;
792     }
793     
794     if (num != HUFF_SEARCH_POINTER_HUFFWARE_ID + REPLY_DISTANCE) return;  // not for us.
795     if (msg != HUFF_SEARCH_MATCH_EVENT) return;  // also not for us.
796         
797     // make sure this is not already redundant, before doing a costly list search.
798     if (llGetListLength(global_matches_found) >= MAX_MATCHES) {
799         // we have enough already.
800         stop_sensing();
801         return;
802     }
803 //hmmm: searchbert arms are still backwards.
804     
805 //log_it("unpacking " + (string)llStringLength(id) + " byte string.");
806     // fluff out the list back from the encoded string.
807     parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
808 //log_it("received " + (string)llGetListLength(parms) + " element list from string.");
809
810     while (llGetListLength(parms) > 1) {
811         // unpack the match that one of our seekers found for us.
812         key found = (string)llList2String(parms, 0);
813         if (find_in_list(global_matches_found, found) < 0) {
814             vector posn = (vector)llList2String(parms, 1);
815             // that key wasn't already listed, so we can drop it in the list.
816             global_matches_found += found;
817             global_positions_found += posn;
818         }
819         // truncate the list by removing those two pieces we already handled.
820         parms = llDeleteSubList(parms, 0, 1);
821         if (llGetListLength(global_matches_found) >= MAX_MATCHES) {
822             // we can bail out of the list processing now; we have enough already.
823             parms = [];
824         }
825     }
826 }
827
828 // uses the configuration item as the value of one of our variables, if we can figure out
829 // the name involved.
830 apply_variable_definition(string var, string value)
831 {
832 //log_it("[" + var + "=" + value + "]");
833     if (var == "max_matches") MAX_MATCHES = (integer)value;
834     else if (var == "max_spiral_radius") MAX_SPIRAL_RADIUS = (float)value;
835     else if (var == "sensor_max_range") SENSOR_MAX_RANGE = (float)value;
836     else if (var == "huff_search_chat_channel") {
837         // we have to hook up our ears to the new channel here.
838         if (listening_handle) llListenRemove(listening_handle);
839         HUFF_SEARCH_CHAT_CHANNEL = (integer)value;
840         listening_handle = llListen(HUFF_SEARCH_CHAT_CHANNEL, "", NULL_KEY, "");
841     } else if (var == "traverse_lands") TRAVERSE_LANDS = (integer)value;
842     else if (var == "spiral_loops") SPIRAL_LOOPS = (integer)value;
843     else if (var == "total_steps") TOTAL_STEPS = (integer)value;
844     else if (var == "max_spiral_traversals") MAX_SPIRAL_TRAVERSALS = (integer)value;
845     else if (var == "search_rod_angular_sweep") SEARCH_ROD_ANGULAR_SWEEP = (float)value;
846     else if (var == "travelling_upwards") TRAVELLING_UPWARDS = (integer)value;
847     else if (var == "max_upwards_distance") MAX_UPWARDS_DISTANCE = (float)value;
848     else if (var == "search_type") SEARCH_OBJECT_TYPE = (integer)value;
849     else if (var == "show_name") SHOW_NAME = (integer)value;
850     else if (var == "show_position") SHOW_POSITION = (integer)value;
851     else if (var == "show_uuid") SHOW_UUID = (integer)value;
852     else if (var == "present_arms") PRESENT_ARMS_STYLE = (integer)value;
853     else {
854         if (DEBUGGING)
855             log_it("unknown variable '" + var + "' tried to define value = " + value);
856     }
857 }
858
859 // we have to consume the configuration in digestible chunks, since the pieces may
860 // be too large for sending in link messages.
861 consume_configuration(list config_chunk)
862 {
863     string notecard_name = llList2String(config_chunk, 0);
864     if (notecard_name == BAD_NOTECARD_TEXT) {
865         complain_about_config(FALSE);
866         return;
867     } else if (notecard_name == FINISHED_READING_NOTECARDS) {
868         // we're ready to make use of our new configuration now.
869         if (DEBUGGING)
870             log_it("Configuration has been read, need validation of limbs.");
871         configuration_pending = FALSE;  // no longer waiting for notecard config.
872         // configure the menu system to know what channel to talk about.
873         llMessageLinked(LINK_THIS, SEARCHBERT_MENUS_HUFFWARE_ID, SM_CONFIGURE_INFO,
874             wrap_parameters([HUFF_SEARCH_CHAT_CHANNEL]));
875         // now check our arms to make sure they're all ready.
876         llMessageLinked(LINK_THIS, BUTTON_PUSHER_HUFFWARE_ID, BUTTON_PUSHED_ALERT, CHECK_ARMS_BUTTON_NAME);
877         return;
878     }
879     
880     integer sandy;
881     // scan the configuration items two at a time, but skip the notecard name at slot zero.
882     for (sandy = 1; sandy < llGetListLength(config_chunk); sandy += 2) {
883         string var = llList2String(config_chunk, sandy);
884         string value = llList2String(config_chunk, sandy + 1);
885         apply_variable_definition(var, value);
886     }
887     // clear the list out now that we've eaten its contents.
888     config_chunk = [];
889 }
890
891 //////////////
892
893 // sends a message to the "which_seeker" search object.  the "parameters" should be a
894 // string-ized list of parameters.  the "command" is the specific action requested.
895 request_from_seeker(integer which_seeker, string parameters, string command)
896 {
897     integer linkNumber = which_seeker + 2;
898     if (which_seeker == ALL_SEEKER_ALERT) linkNumber = LINK_ALL_OTHERS;
899     llMessageLinked(linkNumber, HUFF_SEARCH_POINTER_HUFFWARE_ID, command, parameters);
900 }
901
902 // aim the specified seeker rod at the object with the key and position.
903 point_at_with_particles(integer which_seeker, key targetId, vector targetPosition, integer pas_style)
904 {
905     list paramList = [targetId, targetPosition, pas_style];
906     request_from_seeker(which_seeker, llDumpList2String(paramList, HUFFWARE_PARM_SEPARATOR),
907         HUFF_SEARCH_POINT_PARTY);
908 }
909
910 // stop the particle stream running at the specified search rod.
911 reset_rod(integer which_seeker) { request_from_seeker(which_seeker, "", HUFF_SEARCH_RESET); }
912
913 // support for reading configuration from notecards...
914
915 string CARD_CONFIGURATOR_SIGNATURE = "#searchbert";
916     // the notecard signature we use for our configuration.
917
918 // tries to load a searchbert configuration notecard with the name specified.  if it's blank,
919 // then any config notecard will do.
920 request_configuration(string notecard_name)
921 {
922     if (DEBUGGING) log_it("have hit request_configuration.");
923     all_setup_finished = FALSE;
924     configuration_pending = TRUE;
925     // figure out whether we have a pre-chosen configuration or not.
926     if (llStringLength(notecard_name) == 0) {
927         // start reading the configuration from whatever card.
928         llMessageLinked(LINK_THIS, CARD_CONFIGURATOR_HUFFWARE_ID,
929             BEGIN_READING_NOTECARD_COMMAND, CARD_CONFIGURATOR_SIGNATURE + HUFFWARE_PARM_SEPARATOR
930             + wrap_item_list([]));
931     } else {
932         // get the specific one they wanted.
933         if (DEBUGGING) log_it("Reading configuration from notecard: " + notecard_name);
934         llMessageLinked(LINK_THIS, CARD_CONFIGURATOR_HUFFWARE_ID,
935             READ_PARTICULAR_NOTECARD_COMMAND, CARD_CONFIGURATOR_SIGNATURE + HUFFWARE_PARM_SEPARATOR
936             + wrap_item_list([]) + HUFFWARE_PARM_SEPARATOR
937             + notecard_name);
938     }
939
940     // make sure we complete this in time.
941     set_timer(STARTUP_TIME_ALLOWED);
942 }
943
944 // this is used when we've totally failed to start up properly.
945 // if "arms_problem" is true, then the issue is considered to be that the seeker arms
946 // are missing.
947 complain_about_config(integer arms_problem)
948 {
949     configuration_pending = FALSE;  // it's failed, so we no longer pause for it.
950     string explanation = "something prevented me from putting my seeker arms back on";
951     if (!arms_problem) explanation = "either no notecard had the prefix '"
952         + CARD_CONFIGURATOR_SIGNATURE + "'\n"
953         + "or this sim is very busy and timed out";
954     // we hated the notecards we found, or there were none, or our arms are still ripped off.
955     llOwnerSay("Sorry...  " + explanation + ".\nI will restart now to try again.");
956     llSleep(4);
957     llResetScript();
958 }
959
960 // handles when a menu has been clicked on.
961 process_menu_choice(string menu_name, string av_name, string av_key, string which_choice)
962 {
963     if (menu_name == "main") {
964         if (which_choice == "Matches") {
965             // if there are any current matches, describe them again.
966             if (llGetListLength(global_matches_found)) show_off_what_was_found();
967             else llSay(0, "There are no current matches.");
968             return;
969         } else if (which_choice == "Reset") {
970             carefully_reset_search_list(av_key);
971             return;
972         }
973     }
974 //other things will come...    
975     
976     if (DEBUGGING)
977         log_it("non-implemented menu: " + menu_name + "/" + which_choice + " for " + av_name);
978 }
979
980 // reset the search list and get ready for a new search.
981 carefully_reset_search_list(key id)
982 {
983     if (check_if_search_pending(FALSE)) {
984         // only allow reset while running if it's the owner.
985         if (id != llGetOwner()) {
986             check_if_search_pending(TRUE);  // be noisy now.
987             return;  // we're busy.
988         }
989         llOwnerSay("Stopping active search.");
990         retracing_steps = TRUE;
991         return;
992     }
993     llSay(0, "Resetting matches.");
994     reset_search();
995 }
996
997 //////////////
998 // from hufflets...
999
1000 //////////////
1001 // huffware script: auto-retire, by fred huffhines, version 2.8.
1002 // distributed under BSD-like license.
1003 //   !!  keep in mind that this code must be *copied* into another
1004 //   !!  script that you wish to add auto-retirement capability to.
1005 // when a script has auto_retire in it, it can be dropped into an
1006 // object and the most recent version of the script will destroy
1007 // all older versions.
1008 //
1009 // the version numbers are embedded into the script names themselves.
1010 // the notation for versions uses a letter 'v', followed by two numbers
1011 // in the form "major.minor".
1012 // major and minor versions are implicitly considered as a floating point
1013 // number that increases with each newer version of the script.  thus,
1014 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
1015 // and "hazmap v3.2" is a more recent version.
1016 //
1017 // example usage of the auto-retirement script:
1018 //     default {
1019 //         state_entry() {
1020 //            auto_retire();  // make sure newest addition is only version of script.
1021 //        }
1022 //     }
1023 // this script is partly based on the self-upgrading scripts from markov brodsky
1024 // and jippen faddoul.
1025 //////////////
1026 auto_retire() {
1027     string self = llGetScriptName();  // the name of this script.
1028     list split = compute_basename_and_version(self);
1029     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
1030     string basename = llList2String(split, 0);  // script name with no version attached.
1031     string version_string = llList2String(split, 1);  // the version found.
1032     integer posn;
1033     // find any scripts that match the basename.  they are variants of this script.
1034     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
1035         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
1036         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
1037             // found a basic match at least.
1038             list inv_split = compute_basename_and_version(curr_script);
1039             if (llGetListLength(inv_split) == 2) {
1040                 // see if this script is more ancient.
1041                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
1042                 // must make sure that the retiring script is completely the identical basename;
1043                 // just matching in the front doesn't make it a relative.
1044                 if ( (llList2String(inv_split, 0) == basename)
1045                     && ((float)inv_version_string < (float)version_string) ) {
1046                     // remove script with same name from inventory that has inferior version.
1047                     llRemoveInventory(curr_script);
1048                 }
1049             }
1050         }
1051     }
1052 }
1053 //
1054 // separates the base script name and version number.  used by auto_retire.
1055 list compute_basename_and_version(string to_chop_up)
1056 {
1057     // minimum script name is 2 characters plus a version.
1058     integer space_v_posn;
1059     // find the last useful space and 'v' combo.
1060     for (space_v_posn = llStringLength(to_chop_up) - 3;
1061         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
1062         space_v_posn--) {
1063         // look for space and v but do nothing else.
1064     }
1065     if (space_v_posn < 2) return [];  // no space found.
1066     // now we zoom through the stuff after our beloved v character and find any evil
1067     // space characters, which are most likely from SL having found a duplicate item
1068     // name and not so helpfully renamed it for us.
1069     integer indy;
1070     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
1071         if (llGetSubString(to_chop_up, indy, indy) == " ") {
1072             // found one; zap it.  since we're going backwards we don't need to
1073             // adjust the loop at all.
1074             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
1075         }
1076     }
1077     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
1078     // ditch the space character for our numerical check.
1079     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
1080     // strip out a 'v' if there is one.
1081     if (llGetSubString(chop_suffix, 0, 0) == "v")
1082         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
1083     // if valid floating point number and greater than zero, that works for our version.
1084     string basename = to_chop_up;  // script name with no version attached.
1085     if ((float)chop_suffix > 0.0) {
1086         // this is a big success right here.
1087         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
1088         return [ basename, chop_suffix ];
1089     }
1090     // seems like we found nothing useful.
1091     return [];
1092 }
1093 //
1094 //////////////
1095
1096 integer debug_num = 0;
1097 // a debugging output method.  can be disabled entirely in one place.
1098 log_it(string to_say)
1099 {
1100     debug_num++;
1101     // tell this to the owner.    
1102     llWhisper(0, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
1103     // say this on an unusual channel for chat if it's not intended for general public.
1104 //    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
1105     // say this on open chat that anyone can hear.  we take off the bling for this one.
1106 //    llSay(0, to_say);
1107 }
1108
1109 // joins a list of parameters using the parameter sentinel for the library.
1110 string wrap_parameters(list to_flatten)
1111 { return llDumpList2String(to_flatten, HUFFWARE_PARM_SEPARATOR); }
1112
1113 string wrap_item_list(list to_wrap)
1114 { return llDumpList2String(to_wrap, HUFFWARE_ITEM_SEPARATOR); }
1115
1116 // returns the index of the first occurrence of "pattern" inside
1117 // the "full_string".  if it is not found, then a negative number is returned.
1118 integer find_substring(string full_string, string pattern)
1119 { return llSubStringIndex(llToLower(full_string), llToLower(pattern)); }
1120
1121 // returns TRUE if the "prefix" string is the first part of "compare_with".
1122 integer is_prefix(string compare_with, string prefix)
1123 { return find_substring(compare_with, prefix) == 0; }
1124
1125 // encases a list of vectors in the expected character for the jaunting library.
1126 string wrap_vector_list(list to_wrap)
1127 {
1128     integer len = llGetListLength(to_wrap);
1129     integer i;
1130     string to_return;
1131     for (i = 0; i < len; i++) {
1132         if (i > 0) to_return += "|";
1133         to_return += llList2String(to_wrap, i);
1134     }
1135     return to_return;
1136 }
1137
1138 // locates the string "text" in the list to "search_in".
1139 integer find_in_list(list search_in, string text)
1140
1141     integer len = llGetListLength(search_in);
1142     integer i; 
1143     for (i = 0; i < len; i++) { 
1144         if (llList2String(search_in, i) == text) 
1145             return i; 
1146     } 
1147     return -1;
1148 }
1149
1150 integer float_precision = 2;  // number of digits used when printing floats.
1151
1152 //hmmm: in hufflets yet???
1153 string float_to_string(float to_print)
1154 {
1155     string to_return = (string)to_print;
1156     // find out where the decimal point is in the string.
1157     integer decimal_point_posn = llSubStringIndex(to_return, ".");
1158     if (decimal_point_posn < 0) return to_return;
1159     return llGetSubString(to_return, 0, decimal_point_posn + float_precision);
1160 }
1161
1162 //hmmm: in hufflets yet???
1163 string vector_to_string(vector to_print)
1164 {
1165     string to_return = "<";
1166     to_return += float_to_string(to_print.x);
1167     to_return += ", ";
1168     to_return += float_to_string(to_print.y);
1169     to_return += ", ";
1170     to_return += float_to_string(to_print.z);
1171     to_return += ">";
1172     return to_return;
1173 }
1174
1175 // end hufflets.
1176 //////////////
1177
1178 default {
1179     state_entry() { if (llSubStringIndex(llGetObjectName(), "huffotronic") < 0) state real_default; }
1180     on_rez(integer parm) { state rerun; }
1181 }
1182 state rerun { state_entry() { state default; } }
1183
1184 state real_default {
1185     state_entry() { initialize(); }
1186     
1187     state_exit() { set_timer(0); }
1188     
1189     on_rez(integer parm) { state default; }
1190     
1191     timer() { handle_timer(); }
1192
1193     link_message(integer which, integer num, string str, key id)
1194     { handle_link_message(which, num, str, id); }
1195
1196     changed(integer change) {
1197         if (change & CHANGED_INVENTORY) {
1198             llSleep(1.4);  // snooze to allow other things to react first.
1199             request_configuration("");  // see if there's a card update.
1200         }
1201     }
1202
1203     listen(integer chan, string name, key id, string msg) {
1204         if (msg == "#reset") {
1205             carefully_reset_search_list(id);
1206         } else if (is_prefix(msg, "#find ")) {
1207             // needs arms for this trick.
1208             if (!test_health()) state default;
1209             // try to locate the object the user has specified.
1210             if (check_if_search_pending(TRUE)) return;  // we're busy.
1211             reset_search();  // clean out prior state.
1212             global_target_name = llDeleteSubString(msg, 0, 5);  // Delete "#find " from msg
1213             running_a_search = TRUE;  // record that we're searching.
1214             // point all the rods in as many different directions as we can.
1215             skew_rod_angles(FALSE);
1216             // look for any objects near each seeker and in the direction it's pointing.
1217             // we double the arc we might need to try to get more matches.
1218             start_sensing(ALL_SEEKER_ALERT, SENSOR_MAX_RANGE,
1219                 SEARCH_ROD_ANGULAR_SWEEP, global_target_name, MAX_MATCHES, SEARCH_OBJECT_TYPE);
1220             // start stepping through our search spirals.
1221             set_timer(FAST_TIMER_INTERVAL);
1222             llSay(0, "Searching for " + global_target_name);
1223         } else if (is_prefix(msg, "#initialize")) {
1224             llResetScript();
1225         } else if (is_prefix(msg, "#skew")) {
1226             set_timer(SNOOZE_BEFORE_RESET);
1227             reset_for_next_timer = TRUE;
1228             skew_rod_angles(TRUE);
1229         } else if (is_prefix(msg, "#channel")) {
1230             HUFF_SEARCH_CHAT_CHANNEL = (integer)llDeleteSubString(msg, 0, 7);
1231             llSay(0, "Changed listening channel to " + (string)HUFF_SEARCH_CHAT_CHANNEL + ".");
1232             llMessageLinked(LINK_THIS, SEARCHBERT_MENUS_HUFFWARE_ID, SM_CONFIGURE_INFO,
1233                 wrap_parameters([HUFF_SEARCH_CHAT_CHANNEL]));
1234             apply_variable_definition("huff_search_chat_channel", (string)HUFF_SEARCH_CHAT_CHANNEL);
1235         }
1236     }
1237     
1238     touch_start(integer num) {
1239         // make sure we have already been set up.
1240         if (!test_health()) state default;
1241
1242         if (check_if_search_pending(TRUE)) return;
1243         
1244         // send a request to the menu script for the users' clicks...
1245         integer indy;
1246         for (indy = 0; indy < num; indy++) {
1247             // request new menu popup for each av that clicked.
1248             llMessageLinked(LINK_THIS, SEARCHBERT_MENUS_HUFFWARE_ID, SM_POP_MAIN_MENU_UP, 
1249                 wrap_parameters([llDetectedName(indy), llDetectedKey(indy)]));
1250         }
1251     }
1252 }
1253
1254 /////////
1255 // original attributions:
1256 // Special Particle Sensor "Brain" Script
1257 // Written by Christopher Omega
1258 // Tasks: Listen to the owner, Parse the owner's message, Signal individual locators
1259 // to reset, Or point at a certain object within 96 meters of the apparatus.
1260 /////////
1261
1262 // note by fred huffhines:
1263 //   much of this script was originally written by the attributed authors above.  however,
1264 //   i have spent a ton of time improving and adding features to this pair of scripts...
1265 //   (the brain and the search pointer).  i've added pattern matching (rather than needing
1266 //   to know exact names for the search targets), added the spiral search traversal method
1267 //   to improve search behavior and get more results, improved the particle streams, and
1268 //   many other bits.  i just recently added configurability from notecards for searchbert
1269 //   options and a menuing system to provide help and runtime control over some of the
1270 //   options (v46.3 or so?).  wheeee, it's been a lot of fun.
1271 //      --fred.
1272 //   more changes added recently, may-june 2012: selection of the types of objects to find,
1273 //   using the bit patterns for active, passive, and agent.  control over what items are printed
1274 //   in match list (object uuid, name, and location).  and the "present arms style", that controls
1275 //   how searchbert points at the matches.
1276