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