Annotation of loncom/homework/functionplotresponse.pm, revision 1.58

1.1       www         1: # LearningOnline Network with CAPA
                      2: # option list style responses
                      3: #
1.58    ! www         4: # $Id: functionplotresponse.pm,v 1.57 2011/03/31 16:10:07 www Exp $
1.1       www         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;
1.36      www        34:  
1.1       www        35: BEGIN {
1.37      www        36:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
                     37:                                                             'functionplotrule','functionplotruleset',
                     38:                                                             'functionplotelements'));
1.1       www        39: }
                     40: 
1.5       www        41: #
                     42: # There can be a number of applets on a page, each called ggbApplet_$id, 
                     43: # where $id is the "_"-concatenated part and responseid
                     44: #
                     45: 
1.1       www        46: sub geogebra_startcode {
1.3       www        47:     my ($id)=@_;
1.1       www        48:     return (<<ENDSTARTCODE);
1.3       www        49: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
1.40      www        50:          codebase="/adm/geogebra/"  width="722" height="447" MAYSCRIPT>
1.1       www        51:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
                     52: ENDSTARTCODE
                     53: }
                     54: 
                     55: sub geogebra_endcode {
1.2       www        56:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
                     57: }
                     58: 
1.5       www        59: #
                     60: # This is the internal GeoGebra bytecode which defines the spline functions
                     61: #
1.2       www        62: sub geogebra_spline_program {
                     63:     return (<<ENDSPLINEPROGRAM);
1.57      www        64: <param name="ggbBase64" value="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/CWYPcead93Tf9Y174Y2Hm2bPb1PmxZtPL2R9f39OV52fkl799PeL7wbPeicDj9goGnxOE6O7z3HT2HEtoZezPbQnv7En/pBrMVkRvfMwnEQ69rEe/An7Ew+ffvNPTtrLXz4jz+I03PO/v/oTeY+O9439/T/RjgJI40OT1kc8d8P/Lc3mT15dIuyy7tOPOJH2os3Yf9N99DhPodDf22vF4ynnHVtHvszNsANhXDm+0N6U+npCdPxZ3RAfmu9OZ1BGEbDubZIDquR9Ob6M7kdeRd+qV/Hf6YHbb3dG5PJ23O5b6Qo7cCrfwJ4NQ+IF73F/2/Amre3qkDWOcQtdhqQtfcN2WIW+XMmOBkO3sO/F1R3FrNk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WJxHaVh77ERB/q/21WD+3qOWHyLjkykoxPp2EQ6PpFOTKSLJtLFE+mSiXSLqX6eHJCpESFTQ0KmxoRMDQqZGhUyNSxkalzI1MCQqZGhUyNDJ5+VqZGhUyNDp0aGfiEysrR3O10BbNdZo8vSVYf9aJw5AW7YuPdNX6zTo8Zrpatv349uSxZ/49lf2bfAefbDF2dfodBWNj/jm7Q8P7pwwRv+BvchLxjeoXw3Cad6Wpb6sMZLqkrL73Jl9PkJ4pbe40vivapPtRXk7x0O3iFQjcwvSv3Ic71lALm8T7vS9OpcZX5SiZcPssEd+MZfYb/udNf62/FIeo427hD1C33bS21L/gU7iJ/NZdHIofGU7guFb4pu9eJy8dn0cj4YsWyzRtX21oA9qiq6tMBmVHVliQ0XX2UPF5u2Bre4NZ8HRhnbuda17cbwFp9//ZcYdGZntta3P9qPK3CX4oI5BpCnBhkCq38syb0I+k8st38AUEsHCA04kj02BQAA1BEAAFBLAQIUABQACAAIAKNNfz4bb+CNfwoAAFdEAQASAAAAAAAAAAAAAAAAAAAAAABnZW9nZWJyYV9tYWNyby54bWxQSwECFAAUAAgACACkTX8+RczeXRoAAAAYAAAAFgAAAAAAAAAAAAAAAAC/CgAAZ2VvZ2VicmFfamF2YXNjcmlwdC5qc1BLAQIUABQACAAIAKRNfz4NOJI9NgUAANQRAAAMAAAAAAAAAAAAAAAAAB0LAABnZW9nZWJyYS54bWxQSwUGAAAAAAMAAwC+AAAAjRAAAAAA"/>
1.2       www        65: ENDSPLINEPROGRAM
                     66: }
                     67: 
1.5       www        68: #
                     69: # The standard set of parameters inside <applet>
                     70: #
1.2       www        71: sub geogebra_default_parameters {
1.3       www        72:    my ($id)=@_;
1.2       www        73:    return(<<ENDDEFAULTPARAMETERS);
                     74:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
                     75:         <param name="boxborder" value="false"  />
                     76:         <param name="centerimage" value="true"  />
1.39      www        77: 	<param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_algos.jar, geogebra_export.jar, geogebra_javascript.jar, jlatexmath.jar, jlm_greek.jar, jlm_cyrillic.jar, geogebra_properties.jar" />
1.56      www        78: 	<param name="cache_version" value="3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0, 3.9.214.0" />
1.2       www        79:         <param name="framePossible" value="false" />
                     80: 
                     81:         <param name="showResetIcon" value="false" />
                     82:         <param name="showAnimationButton" value="false" />
                     83:         <param name="enableRightClick" value="false" />
                     84:         <param name="errorDialogsActive" value="true" />
                     85:         <param name="enableLabelDrags" value="false" />
                     86:         <param name="showMenuBar" value="false" />
                     87:         <param name="showToolBar" value="false" />
                     88:         <param name="showToolBarHelp" value="false" />
                     89:         <param name="showAlgebraInput" value="false" />
                     90:         <param name="enableShiftDragZoom" value="false" />
                     91:         <param name="allowRescaling" value="false" />
                     92:         <param name="enableLabelDrags" value="false" />
1.3       www        93:         <param name="ggbOnInitParam" value="applet_$id" />
1.2       www        94: ENDDEFAULTPARAMETERS
1.1       www        95: }
                     96: 
1.5       www        97: #
                     98: # This subroutine is called by LON-CAPA at </problem>
                     99: # Each applet on the page will call function ggbOnInit when it is done loading
                    100: # This function in turn will call the respective function registered by start_init_script
                    101: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
                    102: #
                    103: 
1.3       www       104: sub init_script {
1.16      www       105:    if ($#Apache::functionplotresponse::callscripts>=0) {
                    106:       my $script='';
                    107:       foreach my $id (@Apache::functionplotresponse::callscripts) {
                    108:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
                    109:       }
                    110:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
1.52      www       111:                ") { setTimeout('ggbInitAll()',200) }";
1.16      www       112:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
1.3       www       113:       return (<<ENDGGBINIT);
                    114: <script type="text/javascript">
                    115: // <![CDATA[
1.16      www       116: // Function that each applet will call when loaded
                    117: // It will pass "its" parameter
                    118: // Set flags for when an applet is loaded, wait till all are loaded, and then some
1.3       www       119: function ggbOnInit(param) {
1.16      www       120: $script
                    121: }
                    122: function ggbInitAll() {
1.17      www       123: $calls
1.3       www       124: }
                    125: // ]]>
                    126: </script>
                    127: ENDGGBINIT
                    128:    }
                    129: }
                    130: 
1.5       www       131: #
                    132: # Each Geogebra applet is supposed to call this when parameters change
1.10      www       133: # Changes the hidden fields on the web page
1.5       www       134: #
                    135: sub update_script {
                    136:     my ($id)=@_;
                    137:     return (<<ENDUPDATESCRIPT);
                    138: <script type="text/javascript">
                    139: // <![CDATA[
                    140: function updatePointCoordinates_$id(coordinateName) {
                    141:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
                    142:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
1.9       www       143:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
                    144:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
1.5       www       145:         }
                    146: // ]]>
                    147: </script>
                    148: ENDUPDATESCRIPT
                    149: }
                    150: 
                    151: #
                    152: # Register the above update-handler for a variable
                    153: #
                    154: 
                    155: sub update_register {
                    156:    my ($id,$variable)=@_;
1.6       www       157:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
                    158: }
                    159: 
                    160: #
1.40      www       161: # Set a point coordinate variable
1.6       www       162: #
1.40      www       163: sub set_point_coordinate {
1.48      www       164:    my ($id,$variable,$x,$y,$fixed)=@_;
                    165:    my $mult=($fixed?'a*':'');
1.6       www       166:    return (<<ENDSETVARIABLE);
1.48      www       167: document.ggbApplet_$id.evalCommand("a=1");
                    168: document.ggbApplet_$id.evalCommand("$variable=$mult($x,$y)");
1.40      www       169: document.ggbApplet_$id.setLabelVisible("$variable",false);
1.6       www       170: ENDSETVARIABLE
                    171: }
                    172: 
                    173: #
1.40      www       174: # Set a slope coordinate variable
                    175: #
                    176: sub set_slope_coordinate {
1.48      www       177:    my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed)=@_;
1.40      www       178:    my $xvariable=$variable.'x';
                    179:    my $yvariable=$variable.'y';
                    180:    my $domain=$xmax-$xmin;
                    181:    my $range=$ymax-$ymin;
                    182:    my $xinterval=$domain/100.;
                    183:    my $yinterval=$range/200.;
1.48      www       184:    my $mult=($fixed?'a*':'');
1.40      www       185:    return (<<ENDSETSVARIABLE);
1.48      www       186: document.ggbApplet_$id.evalCommand("a=1");
1.51      www       187: document.ggbApplet_$id.evalCommand("$xvariable=Slider[$xinterval,$domain,$xinterval]");
1.40      www       188: document.ggbApplet_$id.setVisible("$xvariable", false);
                    189: document.ggbApplet_$id.evalCommand("$xvariable=$xrel");
                    190: document.ggbApplet_$id.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
                    191: document.ggbApplet_$id.setVisible("$yvariable", false);
                    192: document.ggbApplet_$id.evalCommand("$yvariable=$yrel");
1.48      www       193: document.ggbApplet_$id.evalCommand("$variable=$mult($xvariable+x($pointname),$yvariable+y($pointname))");
1.40      www       194: document.ggbApplet_$id.setLabelVisible("$variable", false);
                    195: ENDSETSVARIABLE
                    196: }
                    197: 
                    198: #
1.9       www       199: # Input field name for a coordinate variable
                    200: #
                    201: 
                    202: sub field_name {
                    203:     my ($id,$variable,$name)=@_;
                    204:     return "HWVAL_$id\_$variable\_$name";
                    205: }
                    206: 
                    207: #
                    208: # Generate an input field for a coordinate variable
                    209: #
                    210: 
                    211: sub generate_input_field {
                    212:     my ($id,$variable,$x,$y)=@_;
                    213:     $Apache::functionplotresponse::inputfields.=
                    214:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
                    215:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
                    216: }
                    217: 
                    218: #
1.40      www       219: # Initialize a new point coordinate variable at set a listener on it
1.6       www       220: #
1.40      www       221: sub new_point_coordinate {
1.48      www       222:     my ($id,$variable,$x,$y,$fixed)=@_;
1.11      www       223:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
1.10      www       224:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    225:     }
1.11      www       226:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
1.10      www       227:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    228:     }
1.9       www       229:     &generate_input_field($id,$variable,$x,$y);
1.48      www       230:     return &set_point_coordinate($id,$variable,$x,$y,$fixed).&update_register($id,$variable);
1.40      www       231: }
                    232: 
                    233: #
                    234: # Initialize a new slope coordinate variable at set a listener on it
                    235: #
                    236: sub new_slope_coordinate {
1.48      www       237:     my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
1.40      www       238: #
                    239: # $variable: name of the slope point
                    240: # $x, $y: coordinates of the slope point
                    241: # $pointname: name of the associated point point
                    242: # $xp $yp: coordinates of the point point
                    243: #
                    244:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
                    245:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    246:     }
                    247:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
                    248:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    249:     }
                    250:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
                    251:        $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
                    252:     }
                    253:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
                    254:        $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
                    255:     }
                    256: 
                    257:     &generate_input_field($id,$variable,$x,$y);
                    258:     my $xrel=$x-$xp;
                    259:     my $yrel=$y-$yp;
1.48      www       260:     return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed).&update_register($id,$variable);
1.5       www       261: }
                    262: 
                    263: #
                    264: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
                    265: # It then starts the right headers
                    266: #
1.3       www       267: sub start_init_script {
                    268:     my ($id)=@_;
1.16      www       269: # Add id to the list of ggbInit_$id functions that need to be called
                    270:     push(@Apache::functionplotresponse::callscripts,$id);
1.5       www       271: # ... and open this function
1.3       www       272:     return (<<ENDSTARTINIT);
                    273: <script type="text/javascript">
                    274: // <![CDATA[
1.5       www       275: // variable that will eventually be passed back to the server
                    276: var coordinateMap_$id = [];
1.16      www       277: // flag for not loaded yet
                    278: var loaded_$id=false;
1.5       www       279: // Init-function for applet
1.3       www       280: function ggbInit_$id() {
                    281: ENDSTARTINIT
                    282: }
                    283: 
1.5       www       284: #
                    285: # This sets the axes inside ggbInit_$id
                    286: #
                    287: 
1.4       www       288: sub axes_script {
                    289:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
                    290:     return (<<ENDAXESSCRIPT);
                    291:             // changes (xmin, xmax, ymin, ymax)
                    292:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
                    293: 
                    294:             // makes the (x,y) axis (in)visible
                    295:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
                    296:             // makes the grid (in)visible
                    297:             document.ggbApplet_$id.setGridVisible($gvisible);
                    298: ENDAXESSCRIPT
                    299: }
                    300: 
1.14      www       301: sub axes_label {
1.45      www       302:     my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
1.14      www       303:     unless ($xlabel || $ylabel) { return ''; }
                    304:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
                    305:     if ($xlabel) {
1.45      www       306:       if (($ymin<0) && ($ymax>0)) {
1.14      www       307:        $return.=(<<ENDXAXISLABELSCRIPT);
                    308: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
                    309: document.ggbApplet_$id.setVisible("Xlabel",false);
                    310: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
                    311: ENDXAXISLABELSCRIPT
1.45      www       312:       } else {
                    313:        $return.=(<<ENDXOFFAXISLABEL);
                    314: document.ggbApplet_$id.evalCommand("LowerRight=Corner[2]");
                    315: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
                    316: ENDXOFFAXISLABEL
                    317:       }
1.14      www       318:     }
                    319:     if ($ylabel) {
1.45      www       320:       if (($xmin<0) && ($xmax>0)) {
1.14      www       321:        $return.=(<<ENDYAXISLABELSCRIPT);
                    322: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
                    323: document.ggbApplet_$id.setVisible("Ylabel",false);
                    324: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
                    325: ENDYAXISLABELSCRIPT
1.45      www       326:       } else {
                    327:        $return.=(<<ENDYOFFAXISLABEL);
                    328: document.ggbApplet_$id.evalCommand("UpperLeft=Corner[4]");
                    329: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
                    330: ENDYOFFAXISLABEL
                    331:       }
1.14      www       332:     }
                    333:     return $return;
                    334: }
                    335: 
1.58    ! www       336: #
        !           337: # Subroutine to produce background and answer plots
        !           338: #
        !           339: 
1.4       www       340: sub plot_script {
1.47      www       341:    my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
1.41      www       342:    $label=~s/\W//g;
                    343:    if (($label) && ($label!~/^[A-Za-z]/)) {
                    344:       $label='C'.$label;
                    345:    }
                    346:    my $visible=0;
                    347:    if ($label) {
                    348:       $visible="1";
                    349:    } else {
                    350:       $Apache::functionplotresponse::counter++;
                    351:       $label='C'.$Apache::functionplotresponse::counter;
                    352:    }
1.46      www       353:    my $rc=0;
                    354:    my $gc=0;
                    355:    my $bc=0;
                    356:    if ($color) {
                    357:       my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
                    358:       $rc=hex($rh);
                    359:       $gc=hex($gh);
                    360:       $bc=hex($bh);
                    361:    }
1.6       www       362:    if ($fixed) {
1.43      www       363:       return "document.ggbApplet_$id.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
1.46      www       364:              ($visible?'':"document.ggbApplet_$id.setLabelVisible('$label', false);\n").
1.47      www       365:              ($color?"document.ggbApplet_$id.setColor('$label',$rc,$gc,$bc);\n":'').
                    366:              ($thickness?"document.ggbApplet_$id.setLineThickness('$label',$thickness);\n":'');
1.6       www       367:    } else {
1.46      www       368:        return "document.ggbApplet_$id.evalCommand('y=$function');\n";
1.6       www       369:    }
1.4       www       370: }
                    371: 
1.5       www       372: #
1.58    ! www       373: # Answer spline display
        !           374: # 
        !           375: # points: x,y,slope_x,slope_y
        !           376: 
        !           377: sub answer_spline_script {
        !           378:    my ($id,@points)=@_;
        !           379:    my $order=int(($#points+1)/4);
        !           380:    if ($order<2) { $order=2; }
        !           381:    if ($order>8) { $order=8; }
        !           382:    $Apache::functionplotresponse::counter++;
        !           383:    my $label='C'.$Apache::functionplotresponse::counter;
        !           384: }
        !           385: 
        !           386: #
1.7       www       387: # Subroutine that generates code for spline $label based on stored information
1.6       www       388: #
                    389: 
                    390: sub generate_spline {
1.48      www       391:    my ($id,$label,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
1.6       www       392:    my $result='';
1.7       www       393:    my $order=$Apache::functionplotresponse::splineorder{$label};
                    394:    my $x=$Apache::functionplotresponse::splineinitx{$label};
                    395:    my $y=$Apache::functionplotresponse::splineinity{$label};
                    396:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
                    397:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
                    398:    my @coords=();
                    399:    foreach my $i (1..$order) {
1.48      www       400:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y,$fixed);
1.40      www       401:        my $xp=$x;
1.8       www       402:        $x+=$sx/(2.*($order-1));
1.7       www       403:        push(@coords,$label.'P'.$i);
1.48      www       404:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax,$fixed);
1.8       www       405:        $x+=$sx/(2.*($order-1));
1.7       www       406:        push(@coords,$label.'S'.$i);
                    407:    }
                    408:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
1.6       www       409:    return $result;
                    410: }
                    411: #
                    412: # <backgroundplot function="..." fixed="yes/no" />
1.5       www       413: #
1.4       www       414: sub start_backgroundplot {
                    415:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    416:    my $result='';
                    417:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    418:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
1.47      www       419:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
                    420:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
1.41      www       421:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
1.46      www       422:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
                    423:    $color=~s/[^a-fA-F0-9]//gs;
                    424:    unless (length($color)==6) { $color=''; }
1.6       www       425:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
                    426:  
1.4       www       427:    unless ($function) { $function="0"; }
                    428:    if ($target eq 'web') {
1.41      www       429:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
1.47      www       430:       unless (defined($xinitial)) { $xinitial=$xmin; }
                    431:       unless (defined($xfinal)) { $xfinal=$xmax; }
                    432:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
1.13      www       433:    } elsif ($target eq 'edit') {
                    434:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
                    435:              &Apache::edit::text_arg('Function:','function',
                    436:                                      $token,'16').
1.47      www       437:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
                    438:                                      $token,'8').
                    439:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
                    440:                                      $token,'8').
1.41      www       441:              &Apache::edit::text_arg('Label on Plot:','label',
                    442:                                      $token,'8').
1.46      www       443:              &Apache::edit::text_arg('Color (hex code):','color',
                    444:                                      $token,'8').
1.13      www       445:              &Apache::edit::select_arg('Fixed location:','fixed',
                    446:                                   ['yes','no'],$token).
                    447:              &Apache::edit::end_row();
                    448:   } elsif ($target eq 'modified') {
                    449:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.47      www       450:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
1.13      www       451:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    452:   }
                    453:   return $result;
1.4       www       454: }
                    455: 
                    456: sub end_backgroundplot {
1.13      www       457:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    458:    my $result='';
                    459:    if ($target eq 'edit') {
                    460:        $result=&Apache::edit::end_table();
                    461:    }
                    462:    return $result;
1.6       www       463: }
                    464: 
                    465: #
1.25      www       466: # <functionplotrule ... />
1.12      www       467: #
1.25      www       468: sub start_functionplotrule {
1.12      www       469:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    470:    my $result='';
1.24      www       471:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    472:    $Apache::functionplotresponse::counter++;
                    473:    if ($label=~/\W/) {
1.25      www       474:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1.24      www       475:    }
                    476:    $label=~s/\W//gs;
                    477:    unless ($label) {
                    478:       $label='R'.$Apache::functionplotresponse::counter;
                    479:    } else {
                    480:       $label='R'.$label;
                    481:    }
                    482:    if ($Apache::functionplotresponse::splineorder{$label}) {
1.25      www       483:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
1.24      www       484:    }
                    485: 
                    486: 
                    487:    if ($target eq 'grade') {
                    488: # Simply remember - in order - for later
1.25      www       489:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
                    490:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
1.24      www       491:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
1.25      www       492:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
1.24      www       493:       }
                    494:       $beginninglabel=~s/\W//gs;
                    495:       $endinglabel=~s/\W//gs;
                    496:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
                    497:       $relationship=~s/\W//gs;
                    498:       $relationship=lc($relationship);
                    499:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
1.25      www       500:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
1.24      www       501:           $relationship='eq';
                    502:       }
1.35      www       503:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
1.42      www       504:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
1.25      www       505:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
1.24      www       506:          $derivative=0;
                    507:       }
1.25      www       508:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
1.24      www       509:            $label,
                    510:            $derivative,
1.25      www       511:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
1.24      www       512:            $beginninglabel,
1.25      www       513:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
1.24      www       514:            $endinglabel,
1.35      www       515:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
                    516:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
1.24      www       517:            $relationship,
1.33      www       518:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
                    519:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
1.24      www       520:           )));
                    521:    } elsif ($target eq 'edit') {
1.29      www       522:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Evaluation Rule').
1.36      www       523:              &Apache::edit::text_arg('Index/Name:','index',
                    524:                                      $token,'10').'&nbsp;'.
1.35      www       525:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
1.29      www       526:                                   [['0','Function itself'],
                    527:                                    ['1','First derivative'],
1.42      www       528:                                    ['2','Second derivative'],
                    529:                                    ['-1','Integral']],$token).'<br />'.
1.44      www       530:              &Apache::edit::text_arg('Initial x-value:','xinitial',
1.35      www       531:                                       $token,'8').
1.44      www       532:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
                    533:                                                [['start','Start of Plot'],
                    534:                                                 ['end','End of Plot']],$token,'8').'<br />'.
1.30      www       535: 
1.44      www       536:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
1.35      www       537:                                       $token,'8').
1.44      www       538:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
1.32      www       539:                                                [['end','End of Plot']],$token,'8').'<br />'.
1.44      www       540:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
1.35      www       541:                                      $token,'8').
1.44      www       542:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
1.35      www       543:                                      $token,'8').'<br />'.
1.38      www       544:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
1.29      www       545:                                   [['eq','equal'],
                    546:                                    ['ne','not equal'],
                    547:                                    ['ge','greater than or equal'],
                    548:                                    ['gt','greater than'],
                    549:                                    ['lt','less than'],
                    550:                                    ['le','less than or equal']],$token).
                    551:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
1.35      www       552:                                                [['undef','not defined']],$token,'8').
1.29      www       553:              &Apache::edit::text_arg('Percent error:','percenterror',
1.35      www       554:                                      $token,'8').
1.29      www       555:              &Apache::edit::end_row();
                    556:   } elsif ($target eq 'modified') {
1.54      www       557:     if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
1.53      www       558:        $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
                    559:     }
1.54      www       560:     if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
1.53      www       561:        $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
                    562:     }
1.29      www       563:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.35      www       564:                                                  $safeeval,'index','derivativeorder',
                    565:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
                    566:                                                            'minimumlength','maximumlength',
                    567:                                                            'relationship','value','percenterror');
1.29      www       568:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.13      www       569:    }
1.12      www       570:    return $result;
                    571: }
                    572: 
1.25      www       573: sub end_functionplotrule {
1.13      www       574:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    575:    my $result='';
                    576:    if ($target eq 'edit') {
                    577:        $result=&Apache::edit::end_table();
                    578:    }
                    579:    return $result;
1.12      www       580: }
                    581: 
                    582: 
                    583: #
1.23      www       584: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1.6       www       585: #
                    586: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
                    587: #
                    588: sub start_spline {
                    589:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.13      www       590:    my $result='';
                    591:    if ($target eq 'web') {
1.23      www       592:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1.13      www       593:       $Apache::functionplotresponse::counter++;
                    594:       if ($label=~/\W/) {
1.23      www       595:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1.13      www       596:       }
                    597:       $label=~s/\W//gs;
1.23      www       598:       unless ($label) { 
                    599:          $label='S'.$Apache::functionplotresponse::counter; 
                    600:       } else {
                    601:          $label='S'.$label;
                    602:       }
1.13      www       603:       if ($Apache::functionplotresponse::splineorder{$label}) {
1.23      www       604:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1.13      www       605:       }
                    606: 
                    607:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
                    608:       if ($order<2) { $order=2; }
                    609:       if ($order>8) { $order=8; }
                    610:       $Apache::functionplotresponse::splineorder{$label}=$order;
                    611: 
                    612:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
                    613:       unless ($x) { $x=0; }
                    614:       $Apache::functionplotresponse::splineinitx{$label}=$x;
                    615: 
                    616:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
                    617:       unless ($y) { $y=0; }
                    618:       $Apache::functionplotresponse::splineinity{$label}=$y;
                    619: 
                    620:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
                    621:       unless ($sx) { $sx=$order; }
                    622:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
                    623: 
                    624:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
                    625:       unless ($sy) { $sy=2; }
                    626:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
                    627:    } elsif ($target eq 'edit') {
                    628:         $result=&Apache::edit::tag_start($target,$token,'Spline').
1.23      www       629:              &Apache::edit::text_arg('Index:','index',
1.14      www       630:                                      $token,'4').'&nbsp;'.
1.13      www       631:              &Apache::edit::select_arg('Order:','order',
1.44      www       632:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
1.13      www       633:              &Apache::edit::text_arg('Initial x-value:','initx',
1.14      www       634:                                      $token,'4').'&nbsp;'.
1.13      www       635:              &Apache::edit::text_arg('Initial y-value:','inity',
1.14      www       636:                                      $token,'4').'&nbsp;'.
1.13      www       637:              &Apache::edit::text_arg('Scale x:','scalex',
1.14      www       638:                                      $token,'4').'&nbsp;'.
1.13      www       639:              &Apache::edit::text_arg('Scale y:','scaley',
                    640:                                      $token,'4').
                    641:              &Apache::edit::end_row();
                    642:   } elsif ($target eq 'modified') {
                    643:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.23      www       644:                                                  $safeeval,'index','order','initx','inity',
1.13      www       645:                                                            'scalex','scaley');
                    646:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    647:   }
                    648:   return $result;
1.6       www       649: }
                    650: 
                    651: sub end_spline {
1.13      www       652:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    653:    my $result='';
                    654:    if ($target eq 'edit') {
                    655:        $result=&Apache::edit::end_table();
                    656:    }
                    657:    return $result;
1.4       www       658: }
                    659:  
1.3       www       660: sub end_init_script {
                    661:     return (<<ENDENDINIT);
                    662: }
                    663: // ]]>
                    664: </script>
                    665: ENDENDINIT
                    666: }
                    667: 
1.10      www       668: #
                    669: # Storing and restoring spline coordinates from part answers
                    670: #
                    671: sub decode_previous_answer {
                    672:    my ($answer)=@_;
                    673:    foreach my $coordinate (split(/\,/,$answer)) {
                    674:       my ($key,$value)=split(/\=/,$coordinate);
                    675:       $Apache::functionplotresponse::previous{$key}=$value;
                    676:    }
                    677: }
                    678: 
                    679: sub get_answer_from_form_fields {
                    680:    my ($id)=@_;
                    681:    my $answer='';
                    682:    my %coords=();
                    683:    foreach my $field (keys(%env)) {
                    684:       if ($field=~/^form\.HWVAL\_$id/) {
                    685:          $field=~/^form\.(.*)$/;
                    686:          $coords{$1}=$env{$field};
                    687:       }
                    688:    }
                    689:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
                    690:    return ($answer,%coords);
                    691: }
                    692: 
1.15      www       693: #
                    694: # The following functions calculate the cubic-hermite splines server-side
                    695: #
                    696: 
                    697: sub cubic_hermite {
                    698:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       699:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
                    700:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
1.15      www       701: }
                    702: 
                    703: #
                    704: # d/dt(...)
                    705: # 
                    706: 
                    707: sub ddt_cubic_hermite {
                    708:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       709:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
                    710:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
1.15      www       711: }
                    712: 
                    713: #
                    714: # d^2/dt^2(...)
                    715: #
                    716: 
                    717: sub d2dt2_cubic_hermite {
                    718:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       719:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
                    720:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
1.15      www       721: }
                    722: 
                    723: #
1.18      www       724: # Array index calculation
                    725: #
                    726: sub array_index {
                    727:    my ($xmin,$xmax,$x)=@_;
1.38      www       728:    if ($x ne '') {
                    729:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
                    730:    } else {
                    731:       return undef;
                    732:    }
1.20      www       733: }
                    734: 
                    735: #
1.18      www       736: # Populate the arrays
                    737: #
                    738: 
                    739: sub populate_arrays {
                    740:     my ($id,$xmin,$xmax)=@_;
1.26      www       741:     for (my $i=0; $i<=400; $i++) {
1.35      www       742:        $Apache::functionplotresponse::actualxval[$i]=undef;
1.19      www       743:        $Apache::functionplotresponse::func[$i]=undef;
1.22      www       744:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
1.19      www       745:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1.18      www       746:     }
1.19      www       747:     unless ($xmax>$xmin) { return 'no_func'; }
1.18      www       748: # Run over all splines in response
                    749:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1.19      www       750:         my $xiold=-1;
1.18      www       751: # Run over all points in spline
1.19      www       752:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1.18      www       753:             my $ni=$i+1;
                    754:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
                    755:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
                    756:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
                    757:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
                    758:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
                    759:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
                    760:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
                    761:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
                    762: # Run in small steps over spline parameter
1.26      www       763:             for (my $t=0; $t<=1; $t+=0.0001) {
1.35      www       764:                 my $xreal=&cubic_hermite($t,@xparms);
                    765:                 my $xi=&array_index($xmin,$xmax,$xreal);
1.19      www       766:                 if ($xi<$xiold) { return 'no_func'; }
1.26      www       767:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1.19      www       768:                    if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
1.18      www       769:                    $xiold=$xi;
1.35      www       770:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
1.22      www       771: # Function value
1.30      www       772:                    my $funcval=&cubic_hermite($t,@yparms);
                    773:                    $Apache::functionplotresponse::func[$xi]=$funcval;
                    774:                    if (defined($funcval)) {
                    775:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
                    776:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
                    777:                       }
                    778:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
                    779:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
                    780:                       }
                    781:                    }
1.28      www       782: # Chain rule
1.22      www       783: # dy/dx=dy/dt/(dx/dt)
                    784:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
                    785:                    if ($dxdt) {
                    786:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
1.34      www       787: # Second derivative
1.28      www       788:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
1.34      www       789:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
                    790:                          ($dxdt*$dxdt*$dxdt);
1.22      www       791:                    }
1.18      www       792:                 }
                    793:             }
                    794:         }
                    795:     }
                    796: }
                    797: 
                    798: #
1.37      www       799: # Implementation of <functionplotresponse>
1.15      www       800: #
                    801: 
1.1       www       802: sub start_functionplotresponse {
                    803:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    804:   my $result='';
1.6       www       805: # To remember the splines - somehow, they need to come last
                    806:   undef %Apache::functionplotresponse::splineorder;
                    807:   undef %Apache::functionplotresponse::splineinitx;
                    808:   undef %Apache::functionplotresponse::splineinity;
                    809:   undef %Apache::functionplotresponse::splinescalex;
                    810:   undef %Apache::functionplotresponse::splinescaley;
1.10      www       811: # Remember input fields, etc
                    812:   undef %Apache::functionplotresponse::previous;
1.9       www       813:   $Apache::functionplotresponse::inputfields='';
1.6       www       814:   $Apache::functionplotresponse::counter=0;
1.24      www       815: # Remember rules
1.25      www       816:   undef @Apache::functionplotresponse::functionplotrules;
1.37      www       817: # Remember failed rules
                    818:   if ($target eq 'grade') {
                    819:      undef @Apache::functionplotresponse::failedrules;
                    820:   }
                    821: # Delete previous awards
                    822:   undef $Apache::functionplotresponse::awarddetail;
1.10      www       823: # Part and ID
                    824:   my $partid=$Apache::inputtags::part;
                    825:   my $id=&Apache::response::start_response($parstack,$safeeval);
1.6       www       826: # Internal ID to mark the applet and its coordinates
1.10      www       827:   my $internalid = $partid.'_'.$id;
                    828: # Previous answer
                    829:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
                    830: 
1.6       www       831: # Parameters of <functionplotresponse>
1.41      www       832:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
1.6       www       833:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    834:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    835:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1.14      www       836:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
                    837:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1.12      www       838:   if ($target eq 'edit') {
                    839:     $result.=&Apache::edit::start_table($token)
                    840:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
                    841:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
1.37      www       842:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
1.50      www       843:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                    844:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
1.12      www       845:        .'</span></td>'
                    846:        ."<td>&nbsp;"
                    847:        .&Apache::edit::end_row()
                    848:        .&Apache::edit::start_spanning_row()
                    849:        ."\n";
1.14      www       850:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
                    851:                                      $token,'6').'&nbsp;'.
                    852:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                    853:                                      $token,'4').'&nbsp;'.
1.12      www       854:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www       855:                                      $token,'4').'&nbsp;'.
1.12      www       856:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www       857:                                   ['yes','no'],$token).'<br />'.
1.14      www       858:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                    859:                                      $token,'6').'&nbsp;'.
1.12      www       860:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www       861:                                      $token,'4').'&nbsp;'.
1.12      www       862:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www       863:                                      $token,'4').'&nbsp;'.
1.12      www       864:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www       865:                                   ['yes','no'],$token).'<br />'.
1.12      www       866:              &Apache::edit::select_arg('Grid visible:','gridvisible',
1.47      www       867:                                   ['yes','no'],$token).'<br />'.
1.58    ! www       868:              &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,...):',
1.47      www       869:                                          'answerdisplay',$token,'50');
                    870: 
1.12      www       871:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    872:   } elsif ($target eq 'modified') {
                    873:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.14      www       874:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
1.47      www       875:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1.12      www       876:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www       877: 
1.12      www       878:   } elsif ($target eq 'meta') {
1.10      www       879:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.35      www       880:   } elsif (($target eq 'answer') &&
                    881:             ($env{'form.answer_output_mode'} ne 'tex') &&
                    882:             ($Apache::lonhomework::viewgrades == 'F')) {
                    883:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
                    884:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
                    885:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
                    886:                                                {'only_body' => 1,
                    887:                                                 'bgcolor'   => '#FFFFFF',
                    888:                                                 'js_ready'  => 1,});
                    889:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
                    890:       $uname =~s/\W//g;
                    891:       $udom  =~s/\W//g;
                    892:       my $function_name =
                    893:                 join('_','LONCAPA_scriptvars',$uname,$udom,
                    894:                      $env{'form.counter'},$Apache::lonxml::curdepth);
                    895:       my $rules_var ="<script type=\"text/javascript\">
                    896: // <![CDATA[
                    897:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
                    898:     $Apache::functionplotresponse::ruleslog.
                    899:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
                    900: // ]]>
                    901: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
                    902:             &Apache::lonxml::add_script_result($rules_var);
                    903:         }
                    904: 
1.1       www       905:   return $result;
                    906: }
                    907: 
1.25      www       908: sub compare_rel {
1.26      www       909:    my ($relationship,$value,$realval,$tol)=@_;
1.36      www       910: # is the real value undefined?
1.26      www       911:    unless (defined($realval)) {
1.36      www       912: # the real value is not defined
1.26      www       913:       if ($relationship eq 'eq') {
                    914:          if ($value eq 'undef') {
                    915:             return 1;
                    916:          } else {
                    917:             return 0;
                    918:          }
                    919:       } elsif ($relationship eq 'ne') {
                    920:          if ($value eq 'undef') {
                    921:             return 0;
                    922:          } else {
                    923:             return 1;
                    924:          }
                    925:       } else {
                    926:          return 0;
                    927:       }
                    928:    }
                    929: 
1.36      www       930: # is the expected value undefined?
                    931:    if ($value eq 'undef') {
                    932: # but by now we know that the real value is defined
                    933:       return 0;
                    934:    }
                    935: 
                    936: # both are defined.
1.26      www       937:    if ($relationship eq 'gt') {
                    938:       return ($realval>$value);
                    939:    } elsif ($relationship eq 'ge') {
                    940:       return ($realval>$value-$tol);
                    941:    } elsif ($relationship eq 'lt') {
                    942:       return ($realval<$value);
                    943:    } elsif ($relationship eq 'le') {
                    944:       return ($realval<$value+$tol);
                    945:    } elsif ($relationship eq 'ne') {
                    946:       return (abs($value-$realval)>$tol);
                    947:    } else {
                    948:       return (abs($value-$realval)<$tol);
                    949:    }
1.25      www       950:    return 0;
                    951: }
                    952: 
1.35      www       953: sub addlog {
                    954:    my ($text)=@_;
                    955:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
                    956: }
                    957: 
                    958: sub actualval {
                    959:    my ($i,$xmin,$xmax)=@_;
                    960:    return $xmin+$i/400.*($xmax-$xmin);
                    961: }
                    962:  
1.25      www       963: sub functionplotrulecheck {
1.33      www       964:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
                    965: 
1.35      www       966:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1.25      www       967:       =split(/\:/,$rule);
1.33      www       968:    $percent=($percent>0?$percent:5);
1.35      www       969:    &addlog("=================");
1.42      www       970:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1.49      www       971:    if ((defined($minimumlength)) || (defined($maximumlength))) {
                    972:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
                    973:    }
1.30      www       974:    my $li=0;
                    975:    my $lh=400;
                    976: 
1.31      www       977: # Special case: the upper boundary was not defined
                    978: # and needs to be set to the value where
                    979: # the condition is not true anymore => set flag
                    980: 
                    981:    my $findupper=0;
                    982:    if (($xfinal eq '')
                    983:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                    984:     && ($xfinallabel)) {
                    985:        $findupper=1;
                    986:    }
                    987: 
1.25      www       988: # if a hard value is set for the boundaries, it overrides the label
1.30      www       989:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                    990:       $li=&array_index($xmin,$xmax,$xinitial);
                    991:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                    992:    }
                    993:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                    994:       $lh=&array_index($xmin,$xmax,$xfinal);
                    995:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www       996:    }
1.31      www       997: # if the label is defined, use it
1.25      www       998:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www       999:       &addlog("Using lower label $xinitiallabel");
1.30      www      1000:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                   1001:    } else {
                   1002:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www      1003:    }
1.31      www      1004:    unless ($findupper) {
                   1005:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www      1006:          &addlog("Using upper label $xfinallabel");
1.33      www      1007:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www      1008:       } else {
                   1009:          $lh=&array_index($xmin,$xmax,$xfinal);
                   1010:       }
1.25      www      1011:    }
                   1012: # Basic sanity checks
1.30      www      1013:    if ($li<0) { $li=0; }
                   1014:    if ($lh>400) { $lh=400; }
1.38      www      1015:    if (($li>$lh) || (!defined($lh))) {
1.30      www      1016:        $lh=$li;
1.25      www      1017:    }
1.31      www      1018: 
1.35      www      1019:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                   1020:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                   1021:    if ($findupper) {
                   1022:       &addlog("Looking for label $xfinallabel");
                   1023:    }
1.33      www      1024:    my $tol=$percent*($ymax-$ymin)/100;
                   1025:    if ($xmax>$xmin) {
                   1026:       if ($derivative==2) {
                   1027:          $tol=4.*$tol/($xmax-$xmin);
                   1028:       } elsif ($derivative==1) {
                   1029:          $tol=2.*$tol/($xmax-$xmin);
1.42      www      1030:       } elsif ($derivative==-1) {
                   1031:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1032:       }
1.27      www      1033:    }
1.42      www      1034:    my $integral=0;
                   1035:    my $binwidth=($xmax-$xmin)/400.;
                   1036:    if (($derivative<0) && (!$findupper)) {
                   1037: # definite integral, calculate over whole length
                   1038:      &addlog("Calculating definite integral");
                   1039:      for (my $i=$li; $i<=$lh; $i++) {
                   1040:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1041:      }
                   1042:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1043:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1044:         &addlog("Rule $label failed.");
                   1045:         my $hintlabel=$label;
                   1046:         $hintlabel=~s/^R//;
                   1047:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1048:         &addlog("Set hint condition $hintlabel");
                   1049:         return 0;
                   1050:      } 
                   1051:    } else {
                   1052:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1053:         my $val;
                   1054:         if ($derivative==2) {
1.27      www      1055:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1056:         } elsif ($derivative==1) {
1.27      www      1057:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1058:         } elsif ($derivative==-1) {
                   1059:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1060:            $val=$integral;      
1.25      www      1061:         } else {
1.27      www      1062:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1063:         }
1.31      www      1064:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1065:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1066:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1067:            if (($findupper) && ($i>$li)) {
1.49      www      1068: # Check lengths
                   1069:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
                   1070: # Successfully found a new label, set it
1.31      www      1071:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1072:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1073:               return 1;
                   1074:            } else {
1.35      www      1075:               &addlog("Rule $label failed.");
1.49      www      1076:               &setfailed($label);
1.31      www      1077:               return 0; 
                   1078:            }
                   1079:         }
1.42      www      1080:      }
1.25      www      1081:    }
1.49      www      1082: # Corner case where this makes sense: using start or stop as defined labels
                   1083:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1.35      www      1084:    &addlog("Rule $label passed.");
1.27      www      1085:    return 1;
1.24      www      1086: }
                   1087: 
1.49      www      1088: #
                   1089: # check for minimum and maximum lengths
                   1090: #
                   1091: 
                   1092: sub checklength {
                   1093:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
                   1094:     unless (($minimumlength) || ($maximumlength)) { return 1; }
                   1095:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
                   1096:     if ($minimumlength) {
                   1097:        if ($length<$minimumlength) {
                   1098:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
                   1099:           &setfailed($label);
                   1100:           return 0;
                   1101:        }
                   1102:     }
                   1103:     if ($maximumlength) {
                   1104:        if ($length>$maximumlength) {
                   1105:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
                   1106:           &setfailed($label);
                   1107:           return 0;
                   1108:        }
                   1109:     }
                   1110:     return 1;
                   1111: }
                   1112: 
                   1113: sub setfailed {
                   1114:    my ($label)=@_;
                   1115:    my $hintlabel=$label;
                   1116:    $hintlabel=~s/^R//;
                   1117:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1118:    &addlog("Set hint condition $hintlabel");
                   1119: }
                   1120: 
1.37      www      1121: sub start_functionplotruleset {
                   1122:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1123:    if ($target eq 'edit') {
                   1124:       return &Apache::edit::start_table($token).
                   1125:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1126:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1127:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1128:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1129:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
1.37      www      1130:        .'</span></td>'
                   1131:        ."<td>&nbsp;"
                   1132:        .&Apache::edit::end_row()
                   1133:        .&Apache::edit::start_spanning_row()
                   1134:        ."\n";
                   1135:    }
                   1136: }
1.3       www      1137: 
1.37      www      1138: sub end_functionplotruleset {
                   1139:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1140:     my $id=$Apache::inputtags::response[-1];
                   1141:     my $partid=$Apache::inputtags::part;
                   1142:     my $internalid = $partid.'_'.$id;
                   1143: 
                   1144:     if ($target eq 'edit' ) {
                   1145:         return &Apache::edit::end_table();
                   1146:     }  elsif ($target eq 'grade'
1.10      www      1147:          && &Apache::response::submitted()
                   1148:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1149: #
                   1150: # Actually grade
                   1151: #
1.41      www      1152:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1153: 
1.24      www      1154:         my $ad='';
1.30      www      1155:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1156:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1157:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1158:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.18      www      1159:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
1.21      www      1160:            $ad='NOT_FUNCTION';
1.18      www      1161:         } else {
1.35      www      1162:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1163:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1164:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1165:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1166: 
1.24      www      1167: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1168:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.33      www      1169:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
1.24      www      1170:                  $ad='INCORRECT';
                   1171:                  last;
                   1172:               }
                   1173:            }
                   1174: # If it's not wrong, it's correct 
                   1175:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1176:         }
1.37      www      1177:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1178:         &addlog("Assigned award detail: $ad");
                   1179: # Store for later to be assigned at end_functionplotresponse
                   1180:         $Apache::functionplotresponse::awarddetail=$ad;
                   1181:      }
                   1182: }
                   1183: 
                   1184: 
                   1185: sub end_functionplotresponse {
                   1186:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1187:   &Apache::response::end_response;
                   1188: 
                   1189:   my $result;
                   1190:   my $id=$Apache::inputtags::response[-1];
                   1191:   my $partid=$Apache::inputtags::part;
                   1192:   my $internalid = $partid.'_'.$id;
1.20      www      1193: 
1.37      www      1194:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1195:     if ($target eq 'grade'
                   1196:          && &Apache::response::submitted()
                   1197:          && $Apache::lonhomework::type eq 'exam') {
                   1198: 
                   1199:         &Apache::response::scored_response($partid,$id);
                   1200: 
                   1201:     } elsif ($target eq 'grade'
                   1202:          && &Apache::response::submitted()
                   1203:          && $Apache::lonhomework::type ne 'exam') {
                   1204:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1205:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1206:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1207: #
                   1208: # Assign grade
                   1209: #
                   1210:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1211: #
                   1212: # Store grading info
                   1213: #
                   1214:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1215:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1216:    } elsif ($target eq 'web') {
1.37      www      1217:         undef @Apache::functionplotresponse::failedrules;
                   1218:    }
                   1219:    return $result;
                   1220: }
                   1221: 
                   1222: sub end_functionplotelements {
                   1223:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1224:   my $result='';
                   1225:   my $id=$Apache::inputtags::response[-1];
                   1226:   my $partid=$Apache::inputtags::part;
                   1227:   my $internalid = $partid.'_'.$id;
                   1228:   if ($target eq 'edit' ) {
                   1229:      $result=&Apache::edit::end_table();
                   1230:   } elsif ($target eq 'web') {
1.47      www      1231:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
                   1232: 
                   1233: # Are we in show answer mode?
                   1234:      my $showanswer=&Apache::response::show_answer();
                   1235:      if ($showanswer) {
                   1236: # Render answerdisplay
                   1237:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
                   1238:         if ($answerdisplay=~/\S/s) {
                   1239:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
1.58    ! www      1240:               my @components=split(/\s*\:\s*/,$plot);
        !          1241:               if ($#components<3) {
        !          1242: # Just a simple plot
        !          1243:                  my ($func,$xl,$xh)=@components;
        !          1244:                  if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
        !          1245:                  if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
        !          1246:                  $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
        !          1247:               } else {
        !          1248: # This is a spline
        !          1249:                  $result.=&answer_spline_script(@components);
        !          1250:               }
1.47      www      1251:            }
                   1252:         }
                   1253:      }
1.48      www      1254:      my $fixed=0;
                   1255:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
1.6       www      1256: # Now is the time to render all of the stored splines
                   1257:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.48      www      1258:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
1.6       www      1259:      }
1.5       www      1260: # close the init script
1.3       www      1261:      $result.=&end_init_script();
1.17      www      1262: # register all splines in this response 
                   1263:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1264:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1265:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1266:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1267:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1268:      }
1.9       www      1269: # generate the input fields
                   1270:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1271: # actually start the <applet>-tag
1.3       www      1272:      $result.=&geogebra_startcode($internalid);
1.5       www      1273: # load the spline bytecode
1.3       www      1274:      $result.=&geogebra_spline_program();
1.5       www      1275: # set default parameters
1.3       www      1276:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1277: # close the <applet>-tag
1.1       www      1278:      $result.=&geogebra_endcode();
                   1279:   }
                   1280:   return $result;
                   1281: }
                   1282: 
1.41      www      1283: sub boundaries {
                   1284:    my ($parstack,$safeeval,$level)=@_;
                   1285:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   1286:    $xmin=(defined($xmin)?$xmin:-10);
                   1287:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   1288:    $xmax=(defined($xmax)?$xmax:10);
                   1289:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   1290:    $ymin=(defined($ymin)?$ymin:-10);
                   1291:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   1292:    $ymax=(defined($ymax)?$ymax:10);
                   1293:    if ($xmax<=$xmin) {
                   1294:       $xmax=$xmin+20;
                   1295:    }
                   1296:    if ($ymax<=$ymin) {
                   1297:       $ymax=$ymin+20;
                   1298:    }
                   1299:    return ($xmin,$xmax,$ymin,$ymax);
                   1300: }
                   1301: 
1.37      www      1302: sub start_functionplotelements {
                   1303:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1304:    my $result='';
                   1305:    my $id=$Apache::inputtags::response[-1];
                   1306:    my $partid=$Apache::inputtags::part;
                   1307:    my $internalid = $partid.'_'.$id;
                   1308: 
                   1309:    if ($target eq 'edit') {
                   1310:       return &Apache::edit::start_table($token).
                   1311:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   1312:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1313:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1314:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1315:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
1.37      www      1316:        .'</span></td>'
                   1317:        ."<td>&nbsp;"
                   1318:        .&Apache::edit::end_row()
                   1319:        .&Apache::edit::start_spanning_row()
                   1320:        ."\n";
                   1321:    } elsif ($target eq 'web') {
1.41      www      1322:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      1323:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1324:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1325:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1326:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   1327:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   1328: 
                   1329: 
                   1330: # paste in the update routine to receive stuff back from the applet
                   1331:      $result.=&update_script($internalid);
                   1332: # start the initscript for this applet
                   1333:      $result.=&start_init_script($internalid);
                   1334: # put the axis commands inside
                   1335:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      1336:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      1337: # init script is left open
                   1338:   }
                   1339:   return $result;
                   1340: }
                   1341: 
1.1       www      1342: 1;
                   1343: 
                   1344: __END__
                   1345:  
                   1346: =head1 NAME
                   1347: 
                   1348: Apache::functionplotresponse.pm;
                   1349: 
                   1350: =head1 SYNOPSIS
                   1351: 
                   1352: Handles tags associated with accepting function plots.
                   1353: 
                   1354: This is part of the LearningOnline Network with CAPA project
                   1355: described at http://www.lon-capa.org.
                   1356: 
                   1357: =head1 HANDLER SUBROUTINE
                   1358: 
                   1359: start_functionplotresponse()
                   1360: 
                   1361: =head1 OTHER SUBROUTINES
                   1362: 
                   1363: =over
                   1364: 
                   1365: =item end_functionplotresponse()
                   1366: 
                   1367: =back
                   1368: 
                   1369: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>