1: # LearningOnline Network with CAPA
2: # Functionplot responses
3: #
4: # $Id: functionplotresponse.pm,v 1.99 2012/08/17 18:02:15 www Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::functionplotresponse;
30: use strict;
31: use Apache::response();
32: use Apache::lonlocal;
33: use Apache::lonnet;
34: use Apache::run;
35: use LONCAPA;
36:
37: BEGIN {
38: &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
39: 'plotobject','plotvector',
40: 'functionplotvectorrule','functionplotvectorsumrule',
41: 'drawvectorsum',
42: 'functionplotcustomrule',
43: 'functionplotrule','functionplotruleset',
44: 'functionplotelements'));
45: }
46:
47: #
48: # Use old Java or HTML5/Javascript for GeoGebra? Depends on browser!
49: # Return a true value if HTML5 should be used.
50:
51: sub useHTML5 {
52: if ($env{'browser.type'} eq 'chrome') { return 1; }
53: if (($env{'browser.type'} eq 'safari') &&
54: ($env{'browser.os'} eq 'mac')) { return 1; }
55: return 0;
56: }
57:
58: #
59: # HTML5 version does not understand "_" in IDs
60: #
61: sub appid {
62: my ($id)=@_;
63: $id=~s/\_/rid/gs;
64: $id=~s/\W//gs;
65: return $id;
66: }
67:
68: #
69: # Routines to start the applet (Java) or the HTML5/JavaScript
70: #
71: # There can be a number of applets on a page, each called ggbApplet_$id,
72: # where $id is the "_"-concatenated part and responseid
73: #
74:
75: sub geogebra_startcode {
76: my ($id,$width,$height)=@_;
77: if (&useHTML5()) {
78: return &html5_geogebra_startcode(@_);
79: } else {
80: return &java_geogebra_startcode(@_).
81: &java_geogebra_code_param();
82: }
83: }
84:
85: sub geogebra_endcode {
86: if (&useHTML5()) {
87: return '';
88: } else {
89: return &java_geogebra_endcode();
90: }
91: }
92:
93: sub geogebra_default_parameters {
94: my ($id)=@_;
95: if (&useHTML5()) {
96: return '';
97: } else {
98: return &java_geogebra_default_parameters($id);
99: }
100: }
101: # === Java code
102:
103: sub java_geogebra_startcode {
104: my ($id,$width,$height)=@_;
105: my $appid=&appid($id);
106: $width=int(1.*$width);
107: $height=int(1.*$height);
108: unless ($width) { $width=700; }
109: unless ($height) { $height=400; }
110: return (<<ENDSTARTCODE);
111: <applet name="ggbApplet$appid" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
112: codebase="/adm/geogebra/" width="$width" height="$height" MAYSCRIPT>
113: <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
114: ENDSTARTCODE
115: }
116:
117: sub java_geogebra_endcode {
118: return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
119: }
120:
121: sub java_geogebra_code_param {
122: return '<param name="ggbBase64" value="'.&geogebra_internal_program().'" />';
123: }
124:
125: # === HTML5 code
126:
127: sub html5_geogebra_startcode {
128: my ($id,$width,$height)=@_;
129: my $appid=&appid($id);
130: $width=int(1.*$width);
131: $height=int(1.*$height);
132: unless ($width) { $width=700; }
133: unless ($height) { $height=400; }
134: my $code=&geogebra_internal_program();
135: return (<<ENDSTARTCODE);
136: <article class="geogebraweb" data-param-enableLabelDrags="false" data-param-enableShiftDragZoom="false"
137: data-param-width="$width" data-param-height="$height" data-param-id="ggbApplet$appid"
138: data-param-ggbbase64="$code"></article>
139: ENDSTARTCODE
140: }
141:
142: #
143: # This is the internal GeoGebra bytecode which defines the spline functions
144: #
145: sub geogebra_internal_program {
146: return
147: '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';
148: }
149:
150: #
151: # The standard set of parameters inside <applet>
152: #
153: sub java_geogebra_default_parameters {
154: my ($id)=@_;
155: my $appid=&appid($id);
156: return(<<ENDDEFAULTPARAMETERS);
157: <param name="image" value="/adm/lonIcons/lonanim.gif" />
158: <param name="boxborder" value="false" />
159: <param name="centerimage" value="true" />
160: <param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_export.jar, geogebra_algos.jar, geogebra_javascript.jar, geogebra_properties.jar, jlatexmath.jar, jlm_cyrillic.jar, jlm_greek.jar" />
161: <param name="cache_version" value="4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0" />
162: <param name="framePossible" value="false" />
163:
164: <param name="showResetIcon" value="false" />
165: <param name="showAnimationButton" value="false" />
166: <param name="enableRightClick" value="false" />
167: <param name="errorDialogsActive" value="true" />
168: <param name="enableLabelDrags" value="false" />
169: <param name="showMenuBar" value="false" />
170: <param name="showToolBar" value="false" />
171: <param name="showToolBarHelp" value="false" />
172: <param name="showAlgebraInput" value="false" />
173: <param name="enableShiftDragZoom" value="false" />
174: <param name="allowRescaling" value="false" />
175: <param name="enableLabelDrags" value="false" />
176: <param name="ggbOnInitParam" value="ggbApplet$appid" />
177: ENDDEFAULTPARAMETERS
178: }
179:
180: #
181: # This subroutine is called by LON-CAPA at </problem>
182: # Each applet on the page will call function ggbOnInit when it is done loading
183: # This function in turn will call the respective function registered by start_init_script
184: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
185: #
186:
187: sub init_script {
188: if ($#Apache::functionplotresponse::callscripts>=0) {
189: my $script='';
190: foreach my $id (@Apache::functionplotresponse::callscripts) {
191: $script.="if (param=='ggbApplet".&appid($id)."') { loaded_$id=true; }\n";
192: }
193: $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
194: ") { setTimeout('ggbInitAll()',200) }";
195: my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts));
196: my $html5init='';
197: if (&useHTML5()) {
198: $html5init=
199: '<script type="text/javascript" language="javascript" src="/adm/geogebra/html5/web/test42/web/web.nocache.js"></script>';
200: }
201: return (<<ENDGGBINIT);
202: $html5init
203: <script type="text/javascript">
204: // <![CDATA[
205: // Function that each applet will call when loaded
206: // It will pass "its" parameter
207: // Set flags for when an applet is loaded, wait till all are loaded, and then some
208: function ggbOnInit(param) {
209: $script
210: }
211: function ggbInitAll() {
212: $calls
213: }
214: // ]]>
215: </script>
216: ENDGGBINIT
217: }
218: }
219:
220: #
221: # Each Geogebra applet is supposed to call this when parameters change
222: # Changes the hidden fields on the web page
223: #
224: sub update_script {
225: my ($id)=@_;
226: my $appid=&appid($id);
227: return (<<ENDUPDATESCRIPT);
228: <script type="text/javascript">
229: // <![CDATA[
230: function updatePointCoordinates_$id(coordinateName) {
231: var x = document.ggbApplet$appid.getXcoord(coordinateName);
232: var y = document.ggbApplet$appid.getYcoord(coordinateName);
233: document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
234: document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
235: }
236: // ]]>
237: </script>
238: ENDUPDATESCRIPT
239: }
240:
241: #
242: # Register the above update-handler for a variable
243: #
244:
245: sub update_register {
246: my ($id,$variable)=@_;
247: my $appid=&appid($id);
248: return "document.ggbApplet$appid.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
249: }
250:
251: #
252: # Set a point coordinate variable
253: #
254: sub set_point_coordinate {
255: my ($id,$variable,$x,$y,$fixed)=@_;
256: my $appid=&appid($id);
257: my $mult=($fixed?'a*':'');
258: # Get rid of wild exponents, make sure it's a number
259: $x=1.*$x;
260: $y=1.*$y;
261: # GeoGebra does not understand "E"
262: $x=~s/[e|E]/\*10\^/;
263: $x=~s/\+//;
264: $y=~s/[e|E]/\*10\^/;
265: $y=~s/\+//;
266: return (<<ENDSETVARIABLE);
267: document.ggbApplet$appid.evalCommand("a=1");
268: document.ggbApplet$appid.evalCommand("$variable=$mult($x,$y)");
269: document.ggbApplet$appid.setLabelVisible("$variable",false);
270: ENDSETVARIABLE
271: }
272:
273: #
274: # Set a slope coordinate variable
275: #
276: sub set_slope_coordinate {
277: my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed)=@_;
278: my $appid=&appid($id);
279: my $xvariable=$variable.'x';
280: my $yvariable=$variable.'y';
281: my $domain=$xmax-$xmin;
282: my $range=$ymax-$ymin;
283: my $xinterval=$domain/100.;
284: my $yinterval=$range/200.;
285: my $mult=($fixed?'a*':'');
286: return (<<ENDSETSVARIABLE);
287: document.ggbApplet$appid.evalCommand("a=1");
288: document.ggbApplet$appid.evalCommand("$xvariable=Slider[$xinterval,$domain,$xinterval]");
289: document.ggbApplet$appid.setVisible("$xvariable", false);
290: document.ggbApplet$appid.evalCommand("$xvariable=$xrel");
291: document.ggbApplet$appid.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
292: document.ggbApplet$appid.setVisible("$yvariable", false);
293: document.ggbApplet$appid.evalCommand("$yvariable=$yrel");
294: document.ggbApplet$appid.evalCommand("$variable=$mult($xvariable+x($pointname),$yvariable+y($pointname))");
295: document.ggbApplet$appid.setLabelVisible("$variable", false);
296: ENDSETSVARIABLE
297: }
298:
299: #
300: # Input field name for a coordinate variable
301: #
302:
303: sub field_name {
304: my ($id,$variable,$name)=@_;
305: return "HWVAL_$id\_$variable\_$name";
306: }
307:
308: #
309: # Generate an input field for a coordinate variable
310: #
311:
312: sub generate_input_field {
313: my ($id,$variable,$x,$y)=@_;
314: $Apache::functionplotresponse::inputfields.=
315: "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
316: "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
317: }
318:
319: #
320: # Initialize a new point coordinate variable at set a listener on it
321: #
322: sub new_point_coordinate {
323: my ($id,$variable,$x,$y,$fixed)=@_;
324: if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
325: $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
326: }
327: if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
328: $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
329: }
330: &generate_input_field($id,$variable,$x,$y);
331: return &set_point_coordinate($id,$variable,$x,$y,$fixed).&update_register($id,$variable);
332: }
333:
334: #
335: # Initialize a new slope coordinate variable at set a listener on it
336: #
337: sub new_slope_coordinate {
338: my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
339: #
340: # $variable: name of the slope point
341: # $x, $y: coordinates of the slope point
342: # $pointname: name of the associated point point
343: # $xp $yp: coordinates of the point point
344: #
345: if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
346: $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
347: }
348: if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
349: $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
350: }
351: if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
352: $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
353: }
354: if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
355: $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
356: }
357:
358: &generate_input_field($id,$variable,$x,$y);
359: my $xrel=$x-$xp;
360: my $yrel=$y-$yp;
361: return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed).&update_register($id,$variable);
362: }
363:
364: #
365: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
366: # It then starts the right headers
367: #
368: sub start_init_script {
369: my ($id)=@_;
370: # Add id to the list of ggbInit_$id functions that need to be called
371: push(@Apache::functionplotresponse::callscripts,$id);
372: # ... and open this function
373: return (<<ENDSTARTINIT);
374: <script type="text/javascript">
375: // <![CDATA[
376: // variable that will eventually be passed back to the server
377: var coordinateMap_$id = [];
378: // flag for not loaded yet
379: var loaded_$id=false;
380: // Init-function for applet
381: function ggbInit_$id() {
382: ENDSTARTINIT
383: }
384:
385: #
386: # This sets the axes inside ggbInit_$id
387: #
388:
389: sub axes_script {
390: my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
391: my $appid=&appid($id);
392: return (<<ENDAXESSCRIPT);
393: // changes (xmin, xmax, ymin, ymax)
394: document.ggbApplet$appid.setCoordSystem($xmin,$xmax,$ymin,$ymax);
395:
396: // makes the (x,y) axis (in)visible
397: document.ggbApplet$appid.setAxesVisible($xvisible,$yvisible);
398: // makes the grid (in)visible
399: document.ggbApplet$appid.setGridVisible($gvisible);
400: ENDAXESSCRIPT
401: }
402:
403: sub axes_label {
404: my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
405: my $appid=&appid($id);
406: unless ($xlabel || $ylabel) { return ''; }
407: my $return='document.ggbApplet'.$appid.'.evalCommand("topRight=Corner[3]");';
408: if ($xlabel) {
409: if (($ymin<0) && ($ymax>0)) {
410: $return.=(<<ENDXAXISLABELSCRIPT);
411: document.ggbApplet$appid.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
412: document.ggbApplet$appid.setVisible("Xlabel",false);
413: document.ggbApplet$appid.evalCommand("Text[\\"$xlabel\\", Xlabel]");
414: ENDXAXISLABELSCRIPT
415: } else {
416: $return.=(<<ENDXOFFAXISLABEL);
417: document.ggbApplet$appid.evalCommand("LowerRight=Corner[2]");
418: document.ggbApplet$appid.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
419: ENDXOFFAXISLABEL
420: }
421: }
422: if ($ylabel) {
423: if (($xmin<0) && ($xmax>0)) {
424: $return.=(<<ENDYAXISLABELSCRIPT);
425: document.ggbApplet$appid.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
426: document.ggbApplet$appid.setVisible("Ylabel",false);
427: document.ggbApplet$appid.evalCommand("Text[\\"$ylabel\\", Ylabel]");
428: ENDYAXISLABELSCRIPT
429: } else {
430: $return.=(<<ENDYOFFAXISLABEL);
431: document.ggbApplet$appid.evalCommand("UpperLeft=Corner[4]");
432: document.ggbApplet$appid.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
433: ENDYOFFAXISLABEL
434: }
435: }
436: return $return;
437: }
438:
439: #
440: # Subroutine to produce background and answer plots
441: #
442:
443: sub plot_script {
444: my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
445: my $appid=&appid($id);
446: $label=~s/\W//g;
447: if (($label) && ($label!~/^[A-Za-z]/)) {
448: $label='C'.$label;
449: }
450: my $visible=0;
451: if ($label) {
452: $visible="1";
453: } else {
454: $Apache::functionplotresponse::counter++;
455: $label='C'.$Apache::functionplotresponse::counter;
456: }
457: my $rc=0;
458: my $gc=0;
459: my $bc=0;
460: if ($color) {
461: my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
462: $rc=hex($rh);
463: $gc=hex($gh);
464: $bc=hex($bh);
465: }
466: if ($fixed) {
467: return "document.ggbApplet$appid.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
468: ($visible?'':"document.ggbApplet$appid.setLabelVisible('$label', false);\n").
469: ($color?"document.ggbApplet$appid.setColor('$label',$rc,$gc,$bc);\n":'').
470: ($thickness?"document.ggbApplet$appid.setLineThickness('$label',$thickness);\n":'');
471: } else {
472: return "document.ggbApplet$appid.evalCommand('y=$function');\n";
473: }
474: }
475:
476: #
477: # Subroutine to produce objects
478: #
479:
480: sub plotobject_script {
481: my ($id,$label,$x,$y)=@_;
482: my $appid=&appid($id);
483: unless ($label) {
484: $Apache::functionplotresponse::counter++;
485: $label='O'.$Apache::functionplotresponse::counter;
486: }
487: &generate_input_field($id,$label,$x,$y);
488: return "document.ggbApplet$appid.evalCommand('a=1');\n".
489: "document.ggbApplet$appid.setVisible('a', false);\n".
490: "document.ggbApplet$appid.setLabelVisible('a', false);\n".
491: "document.ggbApplet$appid.evalCommand('$label=a*($x,$y)');\n".
492: "document.ggbApplet$appid.setVisible('$label', true);\n".
493: "document.ggbApplet$appid.setLabelVisible('$label', true);\n";
494: }
495:
496: #
497: # Subroutine to produce vectors
498: #
499:
500: sub plotvector_script {
501: my ($id,$label,$xs,$ys,$xe,$ye,$xmin,$xmax,$fixed)=@_;
502: my $appid=&appid($id);
503: unless ($label) {
504: $Apache::functionplotresponse::counter++;
505: $label='V'.$Apache::functionplotresponse::counter;
506: }
507: my $startlabel=$label.'Start';
508: my $endlabel=$label.'End';
509: my $pointlabel=$label.'Point';
510: my $pointx=2.*($xmax-$xmin)+$xmax;
511: my $anglelabel=$label.'Angle';
512: return
513: &new_point_coordinate($id,$startlabel,$xs,$ys,$fixed).
514: &new_point_coordinate($id,$endlabel,$xe,$ye,$fixed).
515: (<<ENDVECTOR);
516: document.ggbApplet$appid.evalCommand("$label=Vector[$startlabel,$endlabel]");
517: document.ggbApplet$appid.setLabelVisible("$label",true);
518: document.ggbApplet$appid.setLineThickness("$label",8);
519: document.ggbApplet$appid.evalCommand("$pointlabel=($pointx,y($startlabel))");
520: document.ggbApplet$appid.evalCommand("$anglelabel=Angle[$pointlabel,$startlabel,$endlabel]");
521: document.ggbApplet$appid.setLabelVisible("$anglelabel",true);
522: document.ggbApplet$appid.setLabelStyle("$anglelabel",VALUE=2);
523: ENDVECTOR
524: }
525:
526: #
527: # Answer spline display
528: #
529: # points: x,y,slope_x,slope_y
530:
531: sub answer_spline_script {
532: my ($id,@points)=@_;
533: my $appid=&appid($id);
534: my $order=int(($#points+1)/4);
535: if ($order<2) { $order=2; }
536: if ($order>8) { $order=8; }
537: $Apache::functionplotresponse::counter++;
538: my $label='CSpline'.$Apache::functionplotresponse::counter;
539: my $output='document.ggbApplet'.$appid.'.evalCommand("'.$label.'=Spline'.$order.'[';
540: for (my $i=0;$i<=$#points;$i+=4) {
541: $output.="($points[$i],$points[$i+1]),($points[$i+2],$points[$i+3]),";
542: }
543: $output=~s/\,$//;
544: $output.=']");'."\n";
545: for (my $i=2; $i<2*$order; $i+=2) {
546: $output.='document.ggbApplet'.$appid.'.setColor("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",0,170,0);'."\n";
547: }
548: for (my $i=1; $i<2*$order; $i+=2) {
549: $output.='document.ggbApplet'.$appid.'.setVisible("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",false);'."\n";
550: }
551:
552: return $output;
553: }
554:
555: #
556: # Subroutine that generates code for spline $label based on stored information
557: #
558:
559: sub generate_spline {
560: my ($id,$label,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
561: my $appid=&appid($id);
562: my $result='';
563: my $order=$Apache::functionplotresponse::splineorder{$label};
564: my $x=$Apache::functionplotresponse::splineinitx{$label};
565: my $y=$Apache::functionplotresponse::splineinity{$label};
566: my $sx=$Apache::functionplotresponse::splinescalex{$label};
567: my $sy=$Apache::functionplotresponse::splinescaley{$label};
568: my @coords=();
569: foreach my $i (1..$order) {
570: $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y,$fixed);
571: my $xp=$x;
572: $x+=$sx/(2.*($order-1));
573: push(@coords,$label.'P'.$i);
574: $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax,$fixed);
575: $x+=$sx/(2.*($order-1));
576: push(@coords,$label.'S'.$i);
577: }
578: $result.='document.ggbApplet'.$appid.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
579: return $result;
580: }
581:
582: #
583: # Object
584: #
585:
586: sub start_plotobject {
587: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
588: my $result='';
589: my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
590: my $x=&Apache::lonxml::get_param('x',$parstack,$safeeval);
591: my $y=&Apache::lonxml::get_param('y',$parstack,$safeeval);
592: my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
593: $label=~s/\W//gs;
594: $label=ucfirst($label);
595: unless ($label) { $label="NewObject"; }
596: if ($target eq 'web') {
597: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
598: unless (defined($x)) { $x=$xmin; }
599: unless (defined($y)) { $y=$ymin; }
600: $result.=&plotobject_script($internalid,$label,$x,$y);
601: } elsif ($target eq 'edit') {
602: $result=&Apache::edit::tag_start($target,$token,'Plot Object').
603: &Apache::edit::text_arg('Label on Plot:','label',
604: $token,'16').
605: &Apache::edit::text_arg('x:','x',
606: $token,'8').
607: &Apache::edit::text_arg('y:','y',
608: $token,'8').
609: &Apache::edit::end_row();
610: } elsif ($target eq 'modified') {
611: $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
612: my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','x','y');
613: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
614: }
615: return $result;
616: }
617:
618: sub end_plotobject {
619: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
620: my $result='';
621: if ($target eq 'edit') {
622: $result=&Apache::edit::end_table();
623: }
624: return $result;
625: }
626:
627: #
628: # Vector
629: #
630:
631: sub start_plotvector {
632: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
633: my $result='';
634: my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
635: my $tailx=&Apache::lonxml::get_param('tailx',$parstack,$safeeval);
636: my $taily=&Apache::lonxml::get_param('taily',$parstack,$safeeval);
637: my $tipx=&Apache::lonxml::get_param('tipx',$parstack,$safeeval);
638: my $tipy=&Apache::lonxml::get_param('tipy',$parstack,$safeeval);
639:
640: my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
641: $label=~s/\W//gs;
642: $label=ucfirst($label);
643: unless ($label) { $label="NewVector"; }
644: if ($Apache::functionplotresponse::vectorlabels{$label}) {
645: &Apache::lonxml::warning(&mt('Vector labels must be unique: [_1]',$label));
646: }
647: $Apache::functionplotresponse::vectorlabels{$label}=1;
648: if ($target eq 'web') {
649: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
650: unless (defined($tailx)) { $tailx=$xmin; }
651: unless (defined($taily)) { $taily=$ymin; }
652: unless (defined($tipx)) { $tipx=$xmin; }
653: unless (defined($tipy)) { $tipy=$ymin; }
654: my $fixed=0;
655: if ((&Apache::response::show_answer()) || (&Apache::response::check_status()>=2)) { $fixed=1; }
656: $result.=&plotvector_script($internalid,$label,$tailx,$taily,$tipx,$tipy,$xmin,$xmax,$fixed);
657: } elsif ($target eq 'edit') {
658: $result=&Apache::edit::tag_start($target,$token,'Plot Vector').
659: &Apache::edit::text_arg('Label on Plot:','label',
660: $token,'16').
661: &Apache::edit::text_arg('Tail x:','tailx',
662: $token,'8').
663: &Apache::edit::text_arg('Tail y:','taily',
664: $token,'8').
665: &Apache::edit::text_arg('Tip x:','tipx',
666: $token,'8').
667: &Apache::edit::text_arg('Tip y:','tipy',
668: $token,'8').
669:
670: &Apache::edit::end_row();
671: } elsif ($target eq 'modified') {
672: $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
673: my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','tailx','taily','tipx','tipy');
674: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
675: }
676: return $result;
677: }
678:
679: sub end_plotvector {
680: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
681: my $result='';
682: if ($target eq 'edit') {
683: $result=&Apache::edit::end_table();
684: }
685: return $result;
686: }
687:
688:
689: #
690: # Vector sum - have GeoGebra draw a sum of specified vectors to help students draw
691: #
692:
693: sub start_drawvectorsum {
694: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
695: my $result='';
696: my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
697: my $internalappid=&appid($internalid);
698: my $tailx=&Apache::lonxml::get_param('tailx',$parstack,$safeeval);
699: my $taily=&Apache::lonxml::get_param('taily',$parstack,$safeeval);
700: my $showvalue=&Apache::lonxml::get_param('showvalue',$parstack,$safeeval);
701: my $vectorlist=&Apache::lonxml::get_param('vectorlist',$parstack,$safeeval);
702: my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
703: $label=~s/\W//gs;
704: $label=ucfirst($label);
705: unless ($label) { $label="NewVector"; }
706: if ($target eq 'web') {
707: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
708: unless (defined($tailx)) { $tailx=$xmin; }
709: unless (defined($taily)) { $taily=$ymin; }
710: unless (defined($vectorlist)) { $vectorlist=''; }
711: my @vectors=split(/\,/,$vectorlist);
712: if ($#vectors>0) {
713: my @sumx=();
714: my @sumy=();
715: foreach my $thisvector (@vectors) {
716: $thisvector=~s/\W//gs;
717: $thisvector=ucfirst($thisvector);
718: unless ($thisvector) { next; }
719: unless ($Apache::functionplotresponse::vectorlabels{$thisvector}) {
720: &Apache::lonxml::warning(&mt('Vectors must be defined before using them for drawing vector sums: [_1]',$thisvector));
721: next;
722: }
723: my $vectorx=$thisvector.'X';
724: my $vectory=$thisvector.'Y';
725: $result.=(<<ENDADDVEC);
726: document.ggbApplet$internalappid.evalCommand("$vectorx=x($thisvector)");
727: document.ggbApplet$internalappid.evalCommand("$vectory=y($thisvector)");
728: document.ggbApplet$internalappid.evalCommand("Include$thisvector$label=Checkbox[]");
729: ENDADDVEC
730: push(@sumx,"If[Include$thisvector$label,$vectorx,0]");
731: push(@sumy,"If[Include$thisvector$label,$vectory,0]");
732: }
733: $result.="document.ggbApplet$internalappid.evalCommand(".'"'."xTot$label=".join('+',@sumx).'");'."\n";
734: $result.="document.ggbApplet$internalappid.evalCommand(".'"'."yTot$label=".join('+',@sumy).'");'."\n";
735: my $show=0;
736: if ($showvalue=~/yes/i) {
737: $show=1;
738: }
739: $result.=(<<ENDMAKEVECTOR);
740: document.ggbApplet$internalappid.evalCommand("$label=Vector[($tailx,$taily),($tailx+xTot$label,$taily+yTot$label)]");
741: document.ggbApplet$internalappid.setLabelVisible("$label",true);
742: document.ggbApplet$internalappid.setLineThickness("$label",8);
743: document.ggbApplet$internalappid.setColor("$label",255,0,0);
744: document.ggbApplet$internalappid.setLabelStyle("$label",VALUE=$show);
745: ENDMAKEVECTOR
746: }
747: } elsif ($target eq 'edit') {
748: $result=&Apache::edit::tag_start($target,$token,'Draw Vector Sum').
749: &Apache::edit::text_arg('Label on Plot:','label',
750: $token,'16').
751: &Apache::edit::text_arg('Tail x:','tailx',
752: $token,'8').
753: &Apache::edit::text_arg('Tail y:','taily',
754: $token,'8').
755: &Apache::edit::select_arg('Show Value:','showvalue',
756: ['yes','no'],$token).'<br />'.
757: &Apache::edit::text_arg('Vector List:','vectorlist',
758: $token,'40').
759: &Apache::edit::end_row();
760: } elsif ($target eq 'modified') {
761: $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
762: my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','tailx','taily','showvalue','vectorlist');
763: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
764: }
765: return $result;
766: }
767:
768:
769: sub end_drawvectorsum {
770: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
771: my $result='';
772: if ($target eq 'edit') {
773: $result=&Apache::edit::end_table();
774: }
775: return $result;
776: }
777:
778:
779:
780: #
781: # <backgroundplot function="..." fixed="yes/no" />
782: #
783: sub start_backgroundplot {
784: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
785: my $result='';
786: my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
787: my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
788: my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
789: my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
790: my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
791: my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
792: $color=~s/[^a-fA-F0-9]//gs;
793: unless (length($color)==6) { $color=''; }
794: my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
795:
796: unless ($function) { $function="0"; }
797: if ($target eq 'web') {
798: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
799: unless (defined($xinitial)) { $xinitial=$xmin; }
800: unless (defined($xfinal)) { $xfinal=$xmax; }
801: $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
802: } elsif ($target eq 'edit') {
803: $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
804: &Apache::edit::text_arg('Function:','function',
805: $token,'16').
806: &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
807: $token,'8').
808: &Apache::edit::text_arg('Final x-value (optional):','xfinal',
809: $token,'8').
810: &Apache::edit::text_arg('Label on Plot:','label',
811: $token,'8').
812: &Apache::edit::text_arg('Color (hex code):','color',
813: $token,'8').
814: &Apache::edit::select_arg('Fixed location:','fixed',
815: ['yes','no'],$token).
816: &Apache::edit::end_row();
817: } elsif ($target eq 'modified') {
818: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
819: $safeeval,'function','label','xinitial','xfinal','color','fixed');
820: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
821: }
822: return $result;
823: }
824:
825: sub end_backgroundplot {
826: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
827: my $result='';
828: if ($target eq 'edit') {
829: $result=&Apache::edit::end_table();
830: }
831: return $result;
832: }
833:
834: #
835: # <functionplotrule ... />
836: #
837: sub start_functionplotrule {
838: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
839: my $result='';
840: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
841: $Apache::functionplotresponse::counter++;
842: if ($label=~/\W/) {
843: &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
844: }
845: $label=~s/\W//gs;
846: unless ($label) {
847: $label='R'.$Apache::functionplotresponse::counter;
848: } else {
849: $label='R'.$label;
850: }
851:
852: if ($target eq 'grade') {
853: # Simply remember - in order - for later
854: my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
855: my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
856: if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
857: &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
858: }
859: $beginninglabel=~s/\W//gs;
860: $endinglabel=~s/\W//gs;
861: my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
862: $relationship=~s/\W//gs;
863: $relationship=lc($relationship);
864: unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
865: &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
866: $relationship='eq';
867: }
868: my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
869: unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
870: &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
871: $derivative=0;
872: }
873: push(@Apache::functionplotresponse::functionplotrules,join(':',(
874: $label,
875: $derivative,
876: &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
877: $beginninglabel,
878: &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
879: $endinglabel,
880: &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
881: &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
882: $relationship,
883: &Apache::lonxml::get_param('value',$parstack,$safeeval),
884: &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
885: )));
886: } elsif ($target eq 'edit') {
887: $result=&Apache::edit::tag_start($target,$token,'Function Plot Graph Rule').
888: &Apache::edit::text_arg('Index/Name:','index',
889: $token,'10').' '.
890: &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
891: [['0','Function itself'],
892: ['1','First derivative'],
893: ['2','Second derivative'],
894: ['-1','Integral']],$token).'<br />'.
895: &Apache::edit::text_arg('Initial x-value:','xinitial',
896: $token,'8').
897: &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
898: [['start','Start of Plot'],
899: ['end','End of Plot']],$token,'8').'<br />'.
900:
901: &Apache::edit::text_arg('Final x-value (optional):','xfinal',
902: $token,'8').
903: &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
904: [['end','End of Plot']],$token,'8').'<br />'.
905: &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
906: $token,'8').
907: &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
908: $token,'8').'<br />'.
909: &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
910: [['eq','equal'],
911: ['ne','not equal'],
912: ['ge','greater than or equal'],
913: ['gt','greater than'],
914: ['lt','less than'],
915: ['le','less than or equal']],$token).
916: $result.= &Apache::edit::select_or_text_arg('Value:','value',
917: [['undef','not defined']],$token,'30').
918: &Apache::edit::text_arg('Percent error:','percenterror',
919: $token,'8').
920: &Apache::edit::end_row();
921: } elsif ($target eq 'modified') {
922: if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
923: $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
924: }
925: if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
926: $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
927: }
928: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
929: $safeeval,'index','derivativeorder',
930: 'xinitial','xinitiallabel','xfinal','xfinallabel',
931: 'minimumlength','maximumlength',
932: 'relationship','value','percenterror');
933: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
934: }
935: return $result;
936: }
937:
938: sub end_functionplotrule {
939: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
940: my $result='';
941: if ($target eq 'edit') {
942: $result=&Apache::edit::end_table();
943: }
944: return $result;
945: }
946:
947:
948: #
949: # <functionplotvectorrule ... />
950: #
951: sub start_functionplotvectorrule {
952: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
953: my $result='';
954: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
955: $Apache::functionplotresponse::counter++;
956: if ($label=~/\W/) {
957: &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
958: }
959: $label=~s/\W//gs;
960: unless ($label) {
961: $label='R'.$Apache::functionplotresponse::counter;
962: } else {
963: $label='R'.$label;
964: }
965:
966: if ($target eq 'grade') {
967: # Simply remember - in order - for later
968:
969: my $id=$Apache::inputtags::response[-1];
970: my $partid=$Apache::inputtags::part;
971: my $internalid = $partid.'_'.$id;
972:
973: my $vector=&Apache::lonxml::get_param('vector',$parstack,$safeeval);
974: $vector=~s/\W//gs;
975: $vector=ucfirst($vector);
976:
977: push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
978: $label,
979: 'vector',
980: $internalid,
981: $vector,
982: &Apache::lonxml::get_param('attachpoint',$parstack,$safeeval),
983: &Apache::lonxml::get_param('notattachpoint',$parstack,$safeeval),
984: &Apache::lonxml::get_param('tailpoint',$parstack,$safeeval),
985: &Apache::lonxml::get_param('tippoint',$parstack,$safeeval),
986: &Apache::lonxml::get_param('nottailpoint',$parstack,$safeeval),
987: &Apache::lonxml::get_param('nottippoint',$parstack,$safeeval),
988: &Apache::lonxml::get_param('length',$parstack,$safeeval),
989: &Apache::lonxml::get_param('angle',$parstack,$safeeval),
990: &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
991: &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
992: )));
993: } elsif ($target eq 'edit') {
994: $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Rule').
995: &Apache::edit::text_arg('Index/Name:','index',
996: $token,'10').' '.
997: &Apache::edit::text_arg('Vector:','vector',
998: $token,'16').'<br />'.
999: &Apache::edit::text_arg('Attached to object:','attachpoint',
1000: $token,'16').
1001: &Apache::edit::text_arg('Not attached to object:','notattachpoint',
1002: $token,'16').'<br />'.
1003: &Apache::edit::text_arg('Tail attached to object:','tailpoint',
1004: $token,'16').
1005: &Apache::edit::text_arg('Tip attached to object:','tippoint',
1006: $token,'16').
1007: &Apache::edit::text_arg('Tail not attached to object:','nottailpoint',
1008: $token,'16').
1009: &Apache::edit::text_arg('Tip not attached to object:','nottippoint',
1010: $token,'16').'<br />'.
1011: &Apache::edit::text_arg('Length:','length',
1012: $token,'30').
1013: &Apache::edit::text_arg('Absolute error length:','lengtherror',
1014: $token,'8').'<br />'.
1015: &Apache::edit::text_arg('Angle:','angle',
1016: $token,'30').
1017: &Apache::edit::text_arg('Absolute error angle:','angleerror',
1018: $token,'8').
1019: &Apache::edit::end_row();
1020: } elsif ($target eq 'modified') {
1021: $env{'form.'.&Apache::edit::html_element_name('vector')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('vector')});
1022: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1023: $safeeval,'index','vector','attachpoint','notattachpoint',
1024: 'tailpoint','tippoint','nottailpoint','nottipoint',
1025: 'length','angle',
1026: 'lengtherror','angleerror');
1027: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1028: }
1029: return $result;
1030: }
1031:
1032: sub end_functionplotvectorrule {
1033: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1034: my $result='';
1035: if ($target eq 'edit') {
1036: $result=&Apache::edit::end_table();
1037: }
1038: return $result;
1039: }
1040:
1041: #
1042: # <functionplotvectorsumrule ... />
1043: #
1044: sub start_functionplotvectorsumrule {
1045: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1046: my $result='';
1047: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1048: $Apache::functionplotresponse::counter++;
1049: if ($label=~/\W/) {
1050: &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1051: }
1052: $label=~s/\W//gs;
1053: unless ($label) {
1054: $label='R'.$Apache::functionplotresponse::counter;
1055: } else {
1056: $label='R'.$label;
1057: }
1058: if ($target eq 'grade') {
1059: # Simply remember - in order - for later
1060: my $id=$Apache::inputtags::response[-1];
1061: my $partid=$Apache::inputtags::part;
1062: my $internalid = $partid.'_'.$id;
1063: my $vectors=&Apache::lonxml::get_param('vectors',$parstack,$safeeval);
1064: push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
1065: $label,
1066: 'sum',
1067: $internalid,
1068: $vectors,
1069: &Apache::lonxml::get_param('length',$parstack,$safeeval),
1070: &Apache::lonxml::get_param('angle',$parstack,$safeeval),
1071: &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
1072: &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
1073: )));
1074: } elsif ($target eq 'edit') {
1075: $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Sum Rule').
1076: &Apache::edit::text_arg('Index/Name:','index',
1077: $token,'10').' '.
1078: &Apache::edit::text_arg('Comma-separated list of vectors:','vectors',
1079: $token,'30').'<br />'.
1080: &Apache::edit::text_arg('Sum vector length:','length',
1081: $token,'30').
1082: &Apache::edit::text_arg('Absolute error length:','lengtherror',
1083: $token,'8').'<br />'.
1084: &Apache::edit::text_arg('Sum vector angle:','angle',
1085: $token,'30').
1086: &Apache::edit::text_arg('Absolute error angle:','angleerror',
1087: $token,'8').
1088: &Apache::edit::end_row();
1089: } elsif ($target eq 'modified') {
1090: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1091: $safeeval,'index','vectors',
1092: 'length','angle',
1093: 'lengtherror','angleerror');
1094: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1095: }
1096: return $result;
1097: }
1098:
1099: sub end_functionplotvectorsumrule {
1100: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1101: my $result='';
1102: if ($target eq 'edit') {
1103: $result=&Apache::edit::end_table();
1104: }
1105: return $result;
1106: }
1107:
1108: #
1109: # <functionplotcustom ... />
1110: #
1111: sub start_functionplotcustomrule {
1112: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1113: my $result='';
1114: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1115: $Apache::functionplotresponse::counter++;
1116: if ($label=~/\W/) {
1117: &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1118: }
1119: $label=~s/\W//gs;
1120: unless ($label) {
1121: $label='R'.$Apache::functionplotresponse::counter;
1122: } else {
1123: $label='R'.$label;
1124: }
1125: &Apache::lonxml::register('Apache::response',('answer'));
1126: if ($target eq 'edit') {
1127: $result=&Apache::edit::tag_start($target,$token,'Function Plot Custom Rule').
1128: &Apache::edit::text_arg('Index/Name:','index',$token,'10').
1129: &Apache::edit::end_row();
1130: } elsif ($target eq 'modified') {
1131: my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'index');
1132: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1133: }
1134: return $result;
1135: }
1136:
1137: sub end_functionplotcustomrule {
1138: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1139: my $result='';
1140: if ($target eq 'edit') {
1141: $result=&Apache::edit::end_table();
1142: } elsif ($target eq 'grade') {
1143: # Simply remember - in order - for later
1144: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1145: $Apache::functionplotresponse::counter++;
1146: if ($label=~/\W/) {
1147: &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1148: }
1149: $label=~s/\W//gs;
1150: unless ($label) {
1151: $label='R'.$Apache::functionplotresponse::counter;
1152: } else {
1153: $label='R'.$label;
1154: }
1155: push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
1156: $label,
1157: 'custom',
1158: &escape($Apache::response::custom_answer[-1])
1159: )));
1160: }
1161: &Apache::lonxml::deregister('Apache::response',('answer'));
1162: return $result;
1163: }
1164:
1165:
1166:
1167: #
1168: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1169: #
1170: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
1171: #
1172: sub start_spline {
1173: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1174: my $result='';
1175: if ($target eq 'web') {
1176: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1177: $Apache::functionplotresponse::counter++;
1178: if ($label=~/\W/) {
1179: &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1180: }
1181: $label=~s/\W//gs;
1182: unless ($label) {
1183: $label='S'.$Apache::functionplotresponse::counter;
1184: } else {
1185: $label='S'.$label;
1186: }
1187: if ($Apache::functionplotresponse::splineorder{$label}) {
1188: &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1189: }
1190:
1191: my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
1192: if ($order<2) { $order=2; }
1193: if ($order>8) { $order=8; }
1194: $Apache::functionplotresponse::splineorder{$label}=$order;
1195:
1196: my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
1197: unless ($x) { $x=0; }
1198: $Apache::functionplotresponse::splineinitx{$label}=$x;
1199:
1200: my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
1201: unless ($y) { $y=0; }
1202: $Apache::functionplotresponse::splineinity{$label}=$y;
1203:
1204: my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
1205: unless ($sx) { $sx=$order; }
1206: $Apache::functionplotresponse::splinescalex{$label}=$sx;
1207:
1208: my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
1209: unless ($sy) { $sy=2; }
1210: $Apache::functionplotresponse::splinescaley{$label}=$sy;
1211: } elsif ($target eq 'edit') {
1212: $result=&Apache::edit::tag_start($target,$token,'Spline').
1213: &Apache::edit::text_arg('Index:','index',
1214: $token,'4').' '.
1215: &Apache::edit::select_arg('Order:','order',
1216: ['2','3','4','5','6','7','8'],$token).' '.
1217: &Apache::edit::text_arg('Initial x-value:','initx',
1218: $token,'4').' '.
1219: &Apache::edit::text_arg('Initial y-value:','inity',
1220: $token,'4').' '.
1221: &Apache::edit::text_arg('Scale x:','scalex',
1222: $token,'4').' '.
1223: &Apache::edit::text_arg('Scale y:','scaley',
1224: $token,'4').
1225: &Apache::edit::end_row();
1226: } elsif ($target eq 'modified') {
1227: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1228: $safeeval,'index','order','initx','inity',
1229: 'scalex','scaley');
1230: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1231: }
1232: return $result;
1233: }
1234:
1235: sub end_spline {
1236: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1237: my $result='';
1238: if ($target eq 'edit') {
1239: $result=&Apache::edit::end_table();
1240: }
1241: return $result;
1242: }
1243:
1244: sub end_init_script {
1245: return (<<ENDENDINIT);
1246: }
1247: // ]]>
1248: </script>
1249: ENDENDINIT
1250: }
1251:
1252: #
1253: # Storing and restoring spline coordinates from part answers
1254: #
1255: sub decode_previous_answer {
1256: my ($answer)=@_;
1257: foreach my $coordinate (split(/\,/,$answer)) {
1258: my ($key,$value)=split(/\=/,$coordinate);
1259: $Apache::functionplotresponse::previous{$key}=$value;
1260: }
1261: }
1262:
1263: sub get_answer_from_form_fields {
1264: my ($id)=@_;
1265: my $answer='';
1266: my %coords=();
1267: foreach my $field (keys(%env)) {
1268: if ($field=~/^form\.HWVAL\_$id/) {
1269: $field=~/^form\.(.*)$/;
1270: $coords{$1}=$env{$field};
1271: }
1272: }
1273: $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
1274: return ($answer,%coords);
1275: }
1276:
1277: #
1278: # The following functions calculate the cubic-hermite splines server-side
1279: #
1280:
1281: sub cubic_hermite {
1282: my ($t,$p1,$s1,$p2,$s2)=@_;
1283: return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
1284: (-2.*$t*$t*$t+3.*$t*$t) *$p2 + 3.*($t*$t*$t-$t*$t) *($s2-$p2);
1285: }
1286:
1287: #
1288: # d/dt(...)
1289: #
1290:
1291: sub ddt_cubic_hermite {
1292: my ($t,$p1,$s1,$p2,$s2)=@_;
1293: return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
1294: (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t) *($s2-$p2);
1295: }
1296:
1297: #
1298: # d^2/dt^2(...)
1299: #
1300:
1301: sub d2dt2_cubic_hermite {
1302: my ($t,$p1,$s1,$p2,$s2)=@_;
1303: return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
1304: (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
1305: }
1306:
1307: #
1308: # Array index calculation
1309: #
1310: sub array_index {
1311: my ($xmin,$xmax,$x)=@_;
1312: if ($x ne '') {
1313: return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
1314: } else {
1315: return undef;
1316: }
1317: }
1318:
1319: #
1320: # Populate the arrays
1321: #
1322:
1323: sub populate_arrays {
1324: my ($id,$xmin,$xmax,$ymin,$ymax)=@_;
1325: for (my $i=0; $i<=400; $i++) {
1326: $Apache::functionplotresponse::actualxval[$i]=undef;
1327: $Apache::functionplotresponse::func[$i]=undef;
1328: $Apache::functionplotresponse::dfuncdx[$i]=undef;
1329: $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1330: }
1331: unless ($xmax>$xmin) { return 'no_func'; }
1332: # Run over all splines in response
1333: foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1334: my $xiold=-1;
1335: # Run over all points in spline
1336: for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1337: my $ni=$i+1;
1338: my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
1339: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
1340: $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
1341: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
1342: my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
1343: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
1344: $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
1345: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
1346: # Run in small steps over spline parameter
1347: for (my $t=0; $t<=1; $t+=0.0001) {
1348: my $xreal=&cubic_hermite($t,@xparms);
1349: my $xi=&array_index($xmin,$xmax,$xreal);
1350: if ($xi<$xiold) { return 'no_func'; }
1351: if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1352: $xiold=$xi;
1353: $Apache::functionplotresponse::actualxval[$xi]=$xreal;
1354: # Function value
1355: my $funcval=&cubic_hermite($t,@yparms);
1356:
1357: # Do we already have a value for this point, and is it different from the new one?
1358: if ((defined($Apache::functionplotresponse::func[$xi])) &&
1359: (abs($Apache::functionplotresponse::func[$xi]-$funcval)>($ymax-$ymin)/100.)) {
1360: return 'no_func';
1361: }
1362: # Okay, remember the new point
1363: $Apache::functionplotresponse::func[$xi]=$funcval;
1364:
1365: if (defined($funcval)) {
1366: if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
1367: $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
1368: }
1369: if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
1370: $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
1371: }
1372: }
1373: # Chain rule
1374: # dy/dx=dy/dt/(dx/dt)
1375: my $dxdt=&ddt_cubic_hermite($t,@xparms);
1376: if ($dxdt) {
1377: $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
1378: # Second derivative
1379: $Apache::functionplotresponse::d2funcdx2[$xi]=
1380: ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
1381: ($dxdt*$dxdt*$dxdt);
1382: }
1383: }
1384: }
1385: }
1386: }
1387: }
1388:
1389: #
1390: # Implementation of <functionplotresponse>
1391: #
1392:
1393: sub start_functionplotresponse {
1394: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1395: my $result='';
1396: # To remember the splines - somehow, they need to come last
1397: undef %Apache::functionplotresponse::splineorder;
1398: undef %Apache::functionplotresponse::splineinitx;
1399: undef %Apache::functionplotresponse::splineinity;
1400: undef %Apache::functionplotresponse::splinescalex;
1401: undef %Apache::functionplotresponse::splinescaley;
1402: # Remember input fields, etc
1403: undef %Apache::functionplotresponse::previous;
1404: $Apache::functionplotresponse::inputfields='';
1405: $Apache::functionplotresponse::counter=0;
1406: # Remember vectors
1407: undef %Apache::functionplotresponse::vectorlabels;
1408: # Remember rules
1409: undef @Apache::functionplotresponse::functionplotrules;
1410: undef @Apache::functionplotresponse::functionplotvectorrules;
1411: # Remember failed rules
1412: if ($target eq 'grade') {
1413: undef @Apache::functionplotresponse::failedrules;
1414: }
1415: # Delete previous awards
1416: undef $Apache::functionplotresponse::awarddetail;
1417: # Part and ID
1418: my $partid=$Apache::inputtags::part;
1419: my $id=&Apache::response::start_response($parstack,$safeeval);
1420: # Internal ID to mark the applet and its coordinates
1421: my $internalid = $partid.'_'.$id;
1422: # Previous answer
1423: &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
1424:
1425: # Parameters of <functionplotresponse>
1426: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
1427: my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1428: my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1429: my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1430: my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
1431: my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1432: if ($target eq 'edit') {
1433: $result.=&Apache::edit::start_table($token)
1434: .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
1435: .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
1436: .&Apache::edit::deletelist($target,$token).' '
1437: .&Apache::edit::insertlist($target,$token).' '
1438: .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
1439: .'</span></td>'
1440: ."<td> "
1441: .&Apache::edit::end_row()
1442: .&Apache::edit::start_spanning_row()
1443: ."\n";
1444: $result.=&Apache::edit::text_arg('Width (pixels):','width',
1445: $token,'6').' '.
1446: &Apache::edit::text_arg('Height (pixels):','height',
1447: $token,'6').'<br />'.
1448: &Apache::edit::text_arg('Label x-axis:','xlabel',
1449: $token,'6').' '.
1450: &Apache::edit::text_arg('Minimum x-value:','xmin',
1451: $token,'4').' '.
1452: &Apache::edit::text_arg('Maximum x-value:','xmax',
1453: $token,'4').' '.
1454: &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1455: ['yes','no'],$token).'<br />'.
1456: &Apache::edit::text_arg('Label y-axis:','ylabel',
1457: $token,'6').' '.
1458: &Apache::edit::text_arg('Minimum y-value:','ymin',
1459: $token,'4').' '.
1460: &Apache::edit::text_arg('Maximum y-value:','ymax',
1461: $token,'4').' '.
1462: &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1463: ['yes','no'],$token).'<br />'.
1464: &Apache::edit::select_arg('Grid visible:','gridvisible',
1465: ['yes','no'],$token).'<br />'.
1466: &Apache::edit::text_arg('Background plot(s) for answer (function(x):xmin:xmax,function(x):xmin:xmax,x1:y1:sx1:sy1:x2:y2:sx2:sy2,...):',
1467: 'answerdisplay',$token,'50').
1468: &Apache::edit::end_row().&Apache::edit::start_spanning_row();
1469: } elsif ($target eq 'modified') {
1470: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1471: $safeeval,'width','height','xlabel','xmin','xmax','ylabel','ymin','ymax',
1472: 'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1473: if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1474:
1475: } elsif ($target eq 'meta') {
1476: $result=&Apache::response::meta_package_write('functionplotresponse');
1477: } elsif (($target eq 'answer') &&
1478: ($env{'form.answer_output_mode'} ne 'tex') &&
1479: ($Apache::lonhomework::viewgrades == 'F')) {
1480: my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
1481: $uname =~s/\W//g;
1482: $udom =~s/\W//g;
1483: my $function_name =
1484: join('_','LONCAPA_scriptvars',$uname,$udom,
1485: $env{'form.counter'},$Apache::lonxml::curdepth);
1486: &Apache::lonxml::add_script_result(
1487: &Apache::loncommon::modal_adhoc_window($function_name,700,500,
1488: '<pre>'.$Apache::functionplotresponse::ruleslog.'</pre>',
1489: &mt('Rules Log'))."<br />");
1490: }
1491: return $result;
1492: }
1493:
1494: sub compare_rel {
1495: my ($relationship,$value,$realval,$tol)=@_;
1496: # is the real value undefined?
1497: unless (defined($realval)) {
1498: # the real value is not defined
1499: if ($relationship eq 'eq') {
1500: if ($value eq 'undef') {
1501: return 1;
1502: } else {
1503: return 0;
1504: }
1505: } elsif ($relationship eq 'ne') {
1506: if ($value eq 'undef') {
1507: return 0;
1508: } else {
1509: return 1;
1510: }
1511: } else {
1512: return 0;
1513: }
1514: }
1515:
1516: # is the expected value undefined?
1517: if ($value eq 'undef') {
1518: # but by now we know that the real value is defined
1519: return 0;
1520: }
1521:
1522: # both are defined.
1523: if ($relationship eq 'gt') {
1524: return ($realval>$value);
1525: } elsif ($relationship eq 'ge') {
1526: return ($realval>$value-$tol);
1527: } elsif ($relationship eq 'lt') {
1528: return ($realval<$value);
1529: } elsif ($relationship eq 'le') {
1530: return ($realval<$value+$tol);
1531: } elsif ($relationship eq 'ne') {
1532: return (abs($value-$realval)>$tol);
1533: } else {
1534: return (abs($value-$realval)<$tol);
1535: }
1536: return 0;
1537: }
1538:
1539: sub addlog {
1540: my ($text)=@_;
1541: $text=~s/\'/\\\'/g;
1542: $Apache::functionplotresponse::ruleslog.=$text.'<br />';
1543: }
1544:
1545: sub actualval {
1546: my ($i,$xmin,$xmax)=@_;
1547: return $xmin+$i/400.*($xmax-$xmin);
1548: }
1549:
1550: sub fpr_val {
1551: my ($arg)=@_;
1552: return &actualval($Apache::functionplotresponse::functionplotrulelabels{$arg},
1553: $Apache::functionplotresponse::fpr_xmin,
1554: $Apache::functionplotresponse::fpr_xmax);
1555: }
1556:
1557: sub fpr_f {
1558: my ($arg)=@_;
1559: return $Apache::functionplotresponse::func[&array_index($Apache::functionplotresponse::fpr_xmin,
1560: $Apache::functionplotresponse::fpr_xmax,
1561: $arg)];
1562: }
1563:
1564: sub fpr_dfdx {
1565: my ($arg)=@_;
1566: return $Apache::functionplotresponse::dfuncdx[&array_index($Apache::functionplotresponse::fpr_xmin,
1567: $Apache::functionplotresponse::fpr_xmax,
1568: $arg)];
1569: }
1570:
1571: sub fpr_d2fdx2 {
1572: my ($arg)=@_;
1573: return $Apache::functionplotresponse::d2funcdx2[&array_index($Apache::functionplotresponse::fpr_xmin,
1574: $Apache::functionplotresponse::fpr_xmax,
1575: $arg)];
1576: }
1577:
1578: sub fpr_vectorcoords {
1579: my ($arg)=@_;
1580: $arg=~s/\W//gs;
1581: $arg=ucfirst($arg);
1582: my $id=$Apache::inputtags::response[-1];
1583: my $partid=$Apache::inputtags::part;
1584: my $internalid = $partid.'_'.$id;
1585: return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_x'},
1586: $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_x'},
1587: $env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_y'},
1588: $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_y'});
1589: }
1590:
1591: sub fpr_objectcoords {
1592: my ($arg)=@_;
1593: $arg=~s/\W//gs;
1594: $arg=ucfirst($arg);
1595: my $id=$Apache::inputtags::response[-1];
1596: my $partid=$Apache::inputtags::part;
1597: my $internalid = $partid.'_'.$id;
1598: return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'_x'},
1599: $env{'form.HWVAL_'.$internalid.'_'.$arg.'_y'});
1600: }
1601:
1602: sub fpr_vectorlength {
1603: my ($arg)=@_;
1604: my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
1605: return sqrt(($xe-$xs)*($xe-$xs)+($ye-$ys)*($ye-$ys));
1606: }
1607:
1608: sub fpr_vectorangle {
1609: my ($arg)=@_;
1610: my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
1611: my $angle=57.2957795*atan2(($ye-$ys),($xe-$xs));
1612: if ($angle<0) { $angle=360+$angle; }
1613: return $angle;
1614: }
1615:
1616: sub vectorcoords {
1617: my ($id,$label)=@_;
1618: return ($env{'form.HWVAL_'.$id.'_'.$label.'Start_x'},
1619: $env{'form.HWVAL_'.$id.'_'.$label.'End_x'},
1620: $env{'form.HWVAL_'.$id.'_'.$label.'Start_y'},
1621: $env{'form.HWVAL_'.$id.'_'.$label.'End_y'});
1622: }
1623:
1624: sub objectcoords {
1625: my ($id,$label)=@_;
1626: return ($env{'form.HWVAL_'.$id.'_'.$label.'_x'},
1627: $env{'form.HWVAL_'.$id.'_'.$label.'_y'});
1628: }
1629:
1630: sub attached {
1631: my ($id,$vector,$objects,$xmin,$xmax,$ymin,$ymax)=@_;
1632: my ($xs,$xe,$ys,$ye)=&vectorcoords($id,$vector);
1633: my $tolx=($xmax-$xmin)/100.;
1634: my $toly=($ymax-$ymin)/100.;
1635: my $tail=0;
1636: my $tip=0;
1637: foreach my $obj (split(/\s*\,\s*/,$objects)) {
1638: $obj=~s/\W//g;
1639: unless ($obj) { next; }
1640: $obj=ucfirst($obj);
1641: my ($xo,$yo)=&objectcoords($id,$obj);
1642: &addlog("Proximity $vector ($xs,$ys)-($xe,$ye) to $obj ($xo,$yo)");
1643: if ((abs($xs-$xo)<$tolx) && (abs($ys-$yo)<$toly)) {
1644: $tail=1;
1645: &addlog("Attached tail: $obj");
1646: }
1647: if ((abs($xe-$xo)<$tolx) && (abs($ye-$yo)<$toly)) {
1648: $tip=1;
1649: &addlog("Attached tip: $obj");
1650: }
1651: }
1652: &addlog("Result tail:$tail tip:$tip");
1653: return($tail,$tip);
1654: }
1655:
1656:
1657: sub vectorangle {
1658: my ($x,$y)=@_;
1659: my $angle=57.2957795*atan2($y,$x);
1660: if ($angle<0) { $angle=360+$angle; }
1661: return $angle;
1662: }
1663:
1664: sub vectorlength {
1665: my ($x,$y)=@_;
1666: return sqrt($x*$x+$y*$y);
1667: }
1668:
1669: sub relvector {
1670: my ($xs,$xe,$ys,$ye)=@_;
1671: return ($xe-$xs,$ye-$ys);
1672: }
1673:
1674: sub plotvectorlength {
1675: return &vectorlength(&relvector(&vectorcoords(@_)));
1676: }
1677:
1678: sub plotvectorangle {
1679: return &vectorangle(&relvector(&vectorcoords(@_)));
1680: }
1681:
1682:
1683: #
1684: # Evaluate a functionplotvectorrule
1685: #
1686:
1687: sub functionplotvectorrulecheck {
1688: my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1689: &addlog("=================");
1690: my ($label,$type)=split(/\:/,$rule);
1691: if ($type eq 'vector') {
1692: return &vectorcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
1693: } elsif ($type eq 'sum') {
1694: return &sumcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
1695: } elsif ($type eq 'custom') {
1696: return &customcheck($rule,$safeeval);
1697: }
1698: }
1699:
1700: sub vectorcheck {
1701: my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1702: my ($label,$type,$id,$vector,
1703: $attachpoint,$notattachpoint,
1704: $tailpoint,$tippoint,$nottailpoint,$nottippoint,
1705: $length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
1706: &addlog("Vector Rule $label for vector ".$vector);
1707: if ($length ne '') {
1708: &addlog("Checking for length $length with error $lengtherror");
1709: $length=&Apache::run::run($length,$safeeval);
1710: &addlog("Length evaluated to $length");
1711: my $thislength=&plotvectorlength($id,$vector);
1712: &addlog("Found length $thislength");
1713: if (abs($thislength-$length)>$lengtherror) {
1714: &setfailed($label);
1715: return 0;
1716: }
1717: }
1718: if ($angle ne '') {
1719: &addlog("Checking for angle $angle with error $angleerror");
1720: $angle=&Apache::run::run($angle,$safeeval);
1721: &addlog("Angle evaluated to $angle");
1722: my $thisangle=&plotvectorangle($id,$vector);
1723: &addlog("Found angle $thisangle");
1724: my $anglediff=abs($thisangle-$angle);
1725: &addlog("Angle difference: $anglediff");
1726: if ($anglediff>360.-$anglediff) {
1727: $anglediff=360.-$anglediff;
1728: }
1729: &addlog("Smallest angle difference: $anglediff");
1730: if ($anglediff>$angleerror) {
1731: &setfailed($label);
1732: return 0;
1733: }
1734: }
1735: if ($attachpoint ne '') {
1736: &addlog("Checking attached: ".$attachpoint);
1737: my ($tail,$tip)=&attached($id,$vector,$attachpoint,$xmin,$xmax,$ymin,$ymax);
1738: unless ($tail || $tip) {
1739: &setfailed($label);
1740: return 0;
1741: }
1742: }
1743: if ($notattachpoint ne '') {
1744: &addlog("Checking not attached: ".$notattachpoint);
1745: my ($tail,$tip)=&attached($id,$vector,$notattachpoint,$xmin,$xmax,$ymin,$ymax);
1746: if ($tail || $tip) {
1747: &setfailed($label);
1748: return 0;
1749: }
1750: }
1751: if ($tailpoint ne '') {
1752: &addlog("Checking tail: ".$tailpoint);
1753: my ($tail,$tip)=&attached($id,$vector,$tailpoint,$xmin,$xmax,$ymin,$ymax);
1754: unless ($tail) {
1755: &setfailed($label);
1756: return 0;
1757: }
1758: }
1759: if ($nottailpoint ne '') {
1760: &addlog("Checking not tail: ".$nottailpoint);
1761: my ($tail,$tip)=&attached($id,$vector,$nottailpoint,$xmin,$xmax,$ymin,$ymax);
1762: if ($tail) {
1763: &setfailed($label);
1764: return 0;
1765: }
1766: }
1767: if ($tippoint ne '') {
1768: &addlog("Checking tip: ".$tippoint);
1769: my ($tail,$tip)=&attached($id,$vector,$tippoint,$xmin,$xmax,$ymin,$ymax);
1770: unless ($tip) {
1771: &setfailed($label);
1772: return 0;
1773: }
1774: }
1775: if ($nottippoint ne '') {
1776: &addlog("Checking not tip: ".$nottippoint);
1777: my ($tail,$tip)=&attached($id,$vector,$nottippoint,$xmin,$xmax,$ymin,$ymax);
1778: if ($tip) {
1779: &setfailed($label);
1780: return 0;
1781: }
1782: }
1783:
1784: &addlog("Rule $label passed.");
1785: return 1;
1786: }
1787:
1788: sub sumcheck {
1789: my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1790: my ($label,$type,$id,$vectors,$length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
1791: &addlog("Vector Sum Rule $label for vectors ".$vectors);
1792: my $sumx=0;
1793: my $sumy=0;
1794: foreach my $sv (split(/\s*\,\s*/,$vectors)) {
1795: my ($rx,$ry)=&relvector(&vectorcoords($id,$sv));
1796: $sumx+=$rx;
1797: $sumy+=$ry;
1798: }
1799: &addlog("Sum vector ($sumx,$sumy)");
1800: if ($length ne '') {
1801: &addlog("Checking length $length with error $lengtherror");
1802: $length=&Apache::run::run($length,$safeeval);
1803: &addlog("Evaluated to $length");
1804: my $thislength=&vectorlength($sumx,$sumy);
1805: &addlog("Actual length $thislength");
1806: if (abs($length-$thislength)>$lengtherror) {
1807: &setfailed($label);
1808: return 0;
1809: }
1810: }
1811: if ($angle ne '') {
1812: &addlog("Checking angle $angle with error $angleerror");
1813: $angle=&Apache::run::run($angle,$safeeval);
1814: &addlog("Evaluated to $angle");
1815: my $thisangle=&vectorangle($sumx,$sumy);
1816: &addlog("Actual angle $thisangle");
1817: my $anglediff=abs($thisangle-$angle);
1818: &addlog("Angle difference: $anglediff");
1819: if ($anglediff>360.-$anglediff) {
1820: $anglediff=360.-$anglediff;
1821: }
1822: &addlog("Smallest angle difference: $anglediff");
1823: if ($anglediff>$angleerror) {
1824: &setfailed($label);
1825: return 0;
1826: }
1827: }
1828: &addlog("Rule $label passed.");
1829: return 1;
1830: }
1831:
1832: sub customcheck {
1833: my ($rule,$safeeval)=@_;
1834: my ($label,$type,$prg)=split(/\:/,$rule);
1835: &addlog("Custom Rule ".$label);
1836: my $result=&Apache::run::run(&unescape($prg),$safeeval);
1837: &addlog("Algorithm returned $result");
1838: unless ($result) {
1839: &setfailed($label);
1840: return 0;
1841: }
1842: &addlog("Rule $label passed.");
1843: return 1;
1844: }
1845:
1846: #
1847: # Evaluate a functionplotrule
1848: #
1849:
1850: sub functionplotrulecheck {
1851: my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1852:
1853: my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1854: =split(/\:/,$rule);
1855: $percent=($percent>0?$percent:5);
1856: &addlog("=================");
1857: &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1858: #
1859: # Evaluate the value
1860: #
1861: if (($value=~/\D/) && ($value ne 'undef')) {
1862: $Apache::functionplotresponse::fpr_xmin=$xmin;
1863: $Apache::functionplotresponse::fpr_xmax=$xmax;
1864: $value=&Apache::run::run($value,$safeeval);
1865: &addlog("Value evaluated to $value");
1866: }
1867:
1868: #
1869: # Minimum and maximum lengths of the interval
1870: #
1871: if ((defined($minimumlength)) || (defined($maximumlength))) {
1872: &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
1873: }
1874: my $li=0;
1875: my $lh=400;
1876:
1877: # Special case: the upper boundary was not defined
1878: # and needs to be set to the value where
1879: # the condition is not true anymore => set flag
1880:
1881: my $findupper=0;
1882: if (($xfinal eq '')
1883: && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
1884: && ($xfinallabel)) {
1885: $findupper=1;
1886: }
1887:
1888: # if a hard value is set for the boundaries, it overrides the label
1889: if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
1890: $li=&array_index($xmin,$xmax,$xinitial);
1891: $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
1892: }
1893: if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
1894: $lh=&array_index($xmin,$xmax,$xfinal);
1895: $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1896: }
1897: # if the label is defined, use it
1898: if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1899: &addlog("Using lower label $xinitiallabel");
1900: $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
1901: } else {
1902: $li=&array_index($xmin,$xmax,$xinitial);
1903: }
1904: unless ($findupper) {
1905: if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1906: &addlog("Using upper label $xfinallabel");
1907: $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1908: } else {
1909: $lh=&array_index($xmin,$xmax,$xfinal);
1910: }
1911: }
1912: # Basic sanity checks
1913: if ($li<0) { $li=0; }
1914: if ($lh>400) { $lh=400; }
1915: if (($li>$lh) || (!defined($lh))) {
1916: $lh=$li;
1917: }
1918:
1919: &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
1920: &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
1921: if ($findupper) {
1922: &addlog("Looking for label $xfinallabel");
1923: }
1924: my $tol=$percent*($ymax-$ymin)/100;
1925: if ($xmax>$xmin) {
1926: if ($derivative==2) {
1927: $tol=4.*$tol/($xmax-$xmin);
1928: } elsif ($derivative==1) {
1929: $tol=2.*$tol/($xmax-$xmin);
1930: } elsif ($derivative==-1) {
1931: $tol=$tol*($xmax-$xmin)/2.;
1932: }
1933: }
1934: my $integral=0;
1935: my $binwidth=($xmax-$xmin)/400.;
1936: if (($derivative<0) && (!$findupper)) {
1937: # definite integral, calculate over whole length
1938: &addlog("Calculating definite integral");
1939: for (my $i=$li; $i<=$lh; $i++) {
1940: $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
1941: }
1942: unless (&compare_rel($relationship,$value,$integral,$tol)) {
1943: &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
1944: &addlog("Rule $label failed.");
1945: &setfailed($label);
1946: return 0;
1947: }
1948: } else {
1949: for (my $i=$li; $i<=$lh; $i++) {
1950: my $val;
1951: if ($derivative==2) {
1952: $val=$Apache::functionplotresponse::d2funcdx2[$i];
1953: } elsif ($derivative==1) {
1954: $val=$Apache::functionplotresponse::dfuncdx[$i];
1955: } elsif ($derivative==-1) {
1956: $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
1957: $val=$integral;
1958: } else {
1959: $val=$Apache::functionplotresponse::func[$i];
1960: }
1961: unless (&compare_rel($relationship,$value,$val,$tol)) {
1962: &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1963: &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1964: if (($findupper) && ($i>$li)) {
1965: # Check lengths
1966: unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1967: # Successfully found a new label, set it
1968: $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1969: &addlog("Rule $label passed, setting label $xfinallabel");
1970: return 1;
1971: } else {
1972: &addlog("Rule $label failed.");
1973: &setfailed($label);
1974: return 0;
1975: }
1976: }
1977: }
1978: }
1979: # Corner case where this makes sense: using start or stop as defined labels
1980: unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1981: &addlog("Rule $label passed.");
1982: return 1;
1983: }
1984:
1985: #
1986: # check for minimum and maximum lengths
1987: #
1988:
1989: sub checklength {
1990: my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
1991: unless (($minimumlength) || ($maximumlength)) { return 1; }
1992: my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
1993: if ($minimumlength) {
1994: if ($length<$minimumlength) {
1995: &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
1996: &setfailed($label);
1997: return 0;
1998: }
1999: }
2000: if ($maximumlength) {
2001: if ($length>$maximumlength) {
2002: &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
2003: &setfailed($label);
2004: return 0;
2005: }
2006: }
2007: return 1;
2008: }
2009:
2010: sub setfailed {
2011: my ($hintlabel)=@_;
2012: $hintlabel=~s/^R//;
2013: push(@Apache::functionplotresponse::failedrules,$hintlabel);
2014: &addlog("Set hint condition $hintlabel");
2015: }
2016:
2017: sub start_functionplotruleset {
2018: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2019: if ($target eq 'edit') {
2020: return &Apache::edit::start_table($token).
2021: '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
2022: .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
2023: .&Apache::edit::deletelist($target,$token).' '.
2024: &Apache::edit::insertlist($target,$token).' '
2025: .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
2026: .'</span></td>'
2027: ."<td> "
2028: .&Apache::edit::end_row()
2029: .&Apache::edit::start_spanning_row()
2030: ."\n";
2031: }
2032: }
2033:
2034: sub end_functionplotruleset {
2035: my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
2036: my $id=$Apache::inputtags::response[-1];
2037: my $partid=$Apache::inputtags::part;
2038: my $internalid = $partid.'_'.$id;
2039:
2040: if ($target eq 'edit' ) {
2041: return &Apache::edit::end_table();
2042: } elsif ($target eq 'grade'
2043: && &Apache::response::submitted()
2044: && $Apache::lonhomework::type ne 'exam') {
2045: #
2046: # Actually grade
2047: #
2048: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
2049:
2050: my $ad='';
2051: undef %Apache::functionplotresponse::functionplotrulelabels;
2052: $Apache::functionplotresponse::ruleslog='';
2053: $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
2054: $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
2055: if (&populate_arrays($internalid,$xmin,$xmax,$ymin,$ymax) eq 'no_func') {
2056: $ad='NOT_FUNCTION';
2057: } else {
2058: &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
2059: $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
2060: &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
2061: $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
2062:
2063: # We have a function that we can actually grade, go through the spline rules.
2064: foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
2065: unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
2066: $ad='INCORRECT';
2067: last;
2068: }
2069: }
2070: # And now go through the vector rules
2071: foreach my $rule (@Apache::functionplotresponse::functionplotvectorrules) {
2072: unless (&functionplotvectorrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
2073: $ad='INCORRECT';
2074: last;
2075: }
2076: }
2077: # If it's not wrong, it's correct
2078: unless ($ad) { $ad='EXACT_ANS' };
2079: }
2080: &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
2081: &addlog("Assigned award detail: $ad");
2082: # Store for later to be assigned at end_functionplotresponse
2083: $Apache::functionplotresponse::awarddetail=$ad;
2084: }
2085: }
2086:
2087:
2088: sub end_functionplotresponse {
2089: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2090: &Apache::response::end_response;
2091:
2092: my $result;
2093: my $id=$Apache::inputtags::response[-1];
2094: my $partid=$Apache::inputtags::part;
2095: my $internalid = $partid.'_'.$id;
2096:
2097: if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
2098: if ($target eq 'grade'
2099: && &Apache::response::submitted()
2100: && $Apache::lonhomework::type eq 'exam') {
2101:
2102: &Apache::response::scored_response($partid,$id);
2103:
2104: } elsif ($target eq 'grade'
2105: && &Apache::response::submitted()
2106: && $Apache::lonhomework::type ne 'exam') {
2107: my ($response,%coords)=&get_answer_from_form_fields($internalid);
2108: $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
2109: my %previous=&Apache::response::check_for_previous($response,$partid,$id);
2110: #
2111: # Assign grade
2112: #
2113: my $ad=$Apache::functionplotresponse::awarddetail;
2114: #
2115: # Store grading info
2116: #
2117: $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
2118: &Apache::response::handle_previous(\%previous,$ad);
2119: } elsif ($target eq 'web') {
2120: undef @Apache::functionplotresponse::failedrules;
2121: }
2122: return $result;
2123: }
2124:
2125: sub end_functionplotelements {
2126: my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
2127: my $result='';
2128: my $id=$Apache::inputtags::response[-1];
2129: my $partid=$Apache::inputtags::part;
2130: my $internalid = $partid.'_'.$id;
2131: if ($target eq 'edit' ) {
2132: $result=&Apache::edit::end_table();
2133: } elsif ($target eq 'web') {
2134: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
2135:
2136: # Are we in show answer mode?
2137: my $showanswer=&Apache::response::show_answer();
2138: if ($showanswer) {
2139: # Render answerdisplay
2140: my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
2141: if ($answerdisplay=~/\S/s) {
2142: foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
2143: my @components=split(/\s*\:\s*/,$plot);
2144: if ($#components<3) {
2145: # Just a simple plot
2146: my ($func,$xl,$xh)=@components;
2147: if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
2148: if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
2149: $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
2150: } else {
2151: # This is a spline
2152: $result.=&answer_spline_script($internalid,@components);
2153: }
2154: }
2155: }
2156: }
2157: my $fixed=0;
2158: if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
2159: # Now is the time to render all of the stored splines
2160: foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
2161: $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
2162: }
2163: # close the init script
2164: $result.=&end_init_script();
2165: # register all splines in this response
2166: $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
2167: join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
2168: foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
2169: $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
2170: $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
2171: }
2172: # generate the input fields
2173: $result.=$Apache::functionplotresponse::inputfields;
2174: # actually start the <applet>-tag
2175: $result.=&geogebra_startcode($internalid,
2176: &Apache::lonxml::get_param('width',$parstack,$safeeval,-2),
2177: &Apache::lonxml::get_param('height',$parstack,$safeeval,-2));
2178: # set default parameters
2179: $result.=&geogebra_default_parameters($internalid);
2180: # close the <applet>-tag
2181: $result.=&geogebra_endcode();
2182: }
2183: return $result;
2184: }
2185:
2186: sub boundaries {
2187: my ($parstack,$safeeval,$level)=@_;
2188: my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
2189: $xmin=(defined($xmin)?$xmin:-10);
2190: my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
2191: $xmax=(defined($xmax)?$xmax:10);
2192: my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
2193: $ymin=(defined($ymin)?$ymin:-10);
2194: my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
2195: $ymax=(defined($ymax)?$ymax:10);
2196: if ($xmax<=$xmin) {
2197: $xmax=$xmin+20;
2198: }
2199: if ($ymax<=$ymin) {
2200: $ymax=$ymin+20;
2201: }
2202: return ($xmin,$xmax,$ymin,$ymax);
2203: }
2204:
2205: sub start_functionplotelements {
2206: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2207: my $result='';
2208: my $id=$Apache::inputtags::response[-1];
2209: my $partid=$Apache::inputtags::part;
2210: my $internalid = $partid.'_'.$id;
2211:
2212: if ($target eq 'edit') {
2213: return &Apache::edit::start_table($token).
2214: '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
2215: .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
2216: .&Apache::edit::deletelist($target,$token).' '.
2217: &Apache::edit::insertlist($target,$token).' '
2218: .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
2219: .'</span></td>'
2220: ."<td> "
2221: .&Apache::edit::end_row()
2222: .&Apache::edit::start_spanning_row()
2223: ."\n";
2224: } elsif ($target eq 'web') {
2225: my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
2226: my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
2227: my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
2228: my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
2229: my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
2230: my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
2231:
2232:
2233: # paste in the update routine to receive stuff back from the applet
2234: $result.=&update_script($internalid);
2235: # start the initscript for this applet
2236: $result.=&start_init_script($internalid);
2237: # put the axis commands inside
2238: $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
2239: $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
2240: # init script is left open
2241: }
2242: return $result;
2243: }
2244:
2245: 1;
2246:
2247: __END__
2248:
2249: =head1 NAME
2250:
2251: Apache::functionplotresponse.pm;
2252:
2253: =head1 SYNOPSIS
2254:
2255: Handles tags associated with accepting function plots.
2256:
2257: This is part of the LearningOnline Network with CAPA project
2258: described at http://www.lon-capa.org.
2259:
2260: =head1 HANDLER SUBROUTINE
2261:
2262: start_functionplotresponse()
2263:
2264: =head1 OTHER SUBROUTINES
2265:
2266: =over
2267:
2268: =item end_functionplotresponse()
2269:
2270: =back
2271:
2272: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>