We are about to switch to a new forum software. Until then we have removed the registration on this forum.
(In Processing) Can I convert a string to a code? For example: The user write on a text box "rect(100,100,20,50)". And the computer convert it to a line of code and on the screen the rect will be drawn. How can I do that?
Answers
maybe when you use p5 ....
https://forum.processing.org/two/discussions/tagged/p1?Tag=eval()
https://forum.Processing.org/two/discussion/13311/using-a-string-as-an-if-evaluation#Item_4
https://forum.Processing.org/two/discussion/7147/some-simple-pulse-equations-using-trig-#Item_8
GoToLoop Thank you! But I dont need boolean statement, I need a line of code! And methods :)
as I discussed with gotoloop in the other thread: gotoloop thinks put can do rectangles too
and he's right - see below
I posted an example based on the QScript example QSCriptIDE by @quark
the whole java / put is by @gotoloop
I killed most of the functionality of the QScript
but you can press "start" to get an rectangle or whatever
you can edit the sketch
you can write e.g.
OR with 2 lines
OR
and hit "start"
Lines
the important lines are 90 to 100
279 to 282
342 to 355
and I added line 334
remark
I am not sure though how to make a separate window where the rectangles are actually drawn
I would be happier if I could pass a String array (my array
code) to@Chrisir, don't you think your code was a lil' too big for @Raz? :-\"
Anyways, here's my own attempt w/ lotsa tricks I've learnt today about Nashorn JS + P5: :-bd
Now's a more advanced version which includes CompiledScript for better script performance: ;;)
http://docs.Oracle.com/javase/8/docs/api/javax/script/Compilable.html
http://docs.Oracle.com/javase/8/docs/api/javax/script/CompiledScript.html
/** * Processing Nashorn JS Integration (v4.0) * GoToLoop (2016-Feb-28) * * Forum.Processing.org/two/discussion/15151/how-to-convert-string-to-a-line-of-code * Forum.Processing.org/two/discussion/7147/some-simple-pulse-equations-using-trig */ final ScriptEngine js = new ScriptEngineManager().getEngineByName("Nashorn"); final CompiledScript compiledJS = compileJS(js, // compiles P5's canvas API calls. "background(~~random(0x1000000))", "text(SENTENCES[idx = (idx+1) % SENTENCES.length], w>>1, h>>1)", "surf.setTitle('Idx: ' + idx + ' Frame: ' + frameCount)"); static final String[] SENTENCES = { "Nashorn JS is cool!", "We can draw on the canvas inside JS too!", "Let's program is JS now!!!" }; void setup() { size(400, 150); smooth(4); frameRate(.5); initJSProcessingEnv(js, this); js.put("SENTENCES", SENTENCES); // puts String[] SENTENCES. js.put("idx", 0); // creates global variable idx into JS. evalJS(js, "surf = surface || frame"); // assigns either surface or frame. println(evalJS(js, // calls P5's canvas API from JS. "textFont(createFont('DejaVu Sans', 18))", "textAlign(CENTER, BASELINE)", "fill(~~0xffFFFF00), stroke(0), strokeWeight(1.5)")); } void draw() { runJS(compiledJS); } import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.Invocable; import javax.script.Compilable; import javax.script.CompiledScript; static final void initJSProcessingEnv (final ScriptEngine js, final PApplet pa) { js.put("p", pa); // injects sketch's PApplet as p into JS. js.put("w", pa.width); // injects width's current value as w into JS. js.put("h", pa.height); // injects height's current value as h into JS. evalJS(js, // imports Processing's packages. "var processing = {", " core: JavaImporter(Packages.processing.core),", " data: JavaImporter(Packages.processing.data),", " event: JavaImporter(Packages.processing.event),", " awt: JavaImporter(Packages.processing.awt),", " javafx: JavaImporter(Packages.processing.javafx),", " opengl: JavaImporter(Packages.processing.opengl)", "}"); evalJS(js, // imports Processing's core classes. "var PApplet = Java.type('processing.core.PApplet'),", " PConstants = Java.type('processing.core.PConstants'),", " PFont = Packages.processing.core.PFont,", " PGraphics = Packages.processing.core.PGraphics,", " PImage = Packages.processing.core.PImage,", " PMatrix = Packages.processing.core.PMatrix,", " PMatrix2D = Packages.processing.core.PMatrix2D,", " PMatrix3D = Packages.processing.core.PMatrix3D,", " PShape = Packages.processing.core.PShape,", " PShapeOBJ = Packages.processing.core.PShapeOBJ,", " PShapeSVG = Packages.processing.core.PShapeSVG,", " PStyle = Packages.processing.core.PStyle,", " PSurface = Packages.processing.core.PSurface,", " PSurfaceNone = Packages.processing.core.PSurfaceNone,", " PVector = Packages.processing.core.PVector,", " ThinkDifferent = Packages.processing.core.ThinkDifferent"); evalJS(js, // imports Processing's data classes. "var FloatDict = Packages.processing.data.FloatDict,", " FloatList = Packages.processing.data.FloatList,", " IntDict = Packages.processing.data.IntDict,", " IntList = Packages.processing.data.IntList,", " JSONArray = Packages.processing.data.JSONArray,", " JSONObject = Packages.processing.data.JSONObject,", " JSONTokener = Packages.processing.data.JSONTokener,", " Sort = Packages.processing.data.Sort,", " StringDict = Packages.processing.data.StringDict,", " StringList = Packages.processing.data.StringList,", " Table = Packages.processing.data.Table,", " TableRow = Packages.processing.data.TableRow,", " XML = Packages.processing.data.XML"); evalJS(js, // imports Processing's event classes. "var Event = Packages.processing.event.Event,", " KeyEvent = Packages.processing.event.KeyEvent,", " MouseEvent = Packages.processing.event.MouseEvent,", " TouchEvent = Packages.processing.event.TouchEvent"); evalJS(js, // imports Processing's awt classes. "var PGraphicsJava2D = Packages.processing.awt.PGraphicsJava2D,", " PShapeJava2D = Packages.processing.awt.PShapeJava2D,", " PSurfaceAWT = Packages.processing.awt.PSurfaceAWT"); evalJS(js, // imports Processing's javafx classes. "var PGraphicsFX2D = Packages.processing.javafx.PGraphicsFX2D,", " PSurfaceFX = Packages.processing.javafx.PSurfaceFX"); evalJS(js, // imports Processing's opengl classes. "var FontTexture = Packages.processing.opengl.FontTexture,", " FrameBuffer = Packages.processing.opengl.FrameBuffer,", " LinePath = Packages.processing.opengl.LinePath,", " LineStroker = Packages.processing.opengl.LineStroker,", " PGL = Packages.processing.opengl.PGL,", " PGraphics2D = Packages.processing.opengl.PGraphics2D,", " PGraphics3D = Packages.processing.opengl.PGraphics3D,", " PGraphicsOpenGL = Packages.processing.opengl.PGraphicsOpenGL,", " PJOGL = Packages.processing.opengl.PJOGL,", " PShader = Packages.processing.opengl.PShader,", " PShapeOpenGL = Packages.processing.opengl.PShapeOpenGL,", " PSurfaceJOGL = Packages.processing.opengl.PSurfaceJOGL,", " Texture = Packages.processing.opengl.Texture,", " VertexBuffer = Packages.processing.opengl.VertexBuffer"); evalJS(js, // imports some useful Java classes. "var ArrayList = java.util.ArrayList,", " LinkedList = java.util.LinkedList,", " ArrayDeque = java.util.ArrayDeque,", " HashMap = java.util.HashMap,", " WeakHashMap = java.util.WeakHashMap,", " HashSet = java.util.HashSet,", " LinkedHashSet = java.util.LinkedHashSet,", " TreeSet = java.util.TreeSet,", " Collections = java.util.Collections,", " Arrays = java.util.Arrays,", " Objects = java.util.Objects,", " Optional = java.util.Optional,", " Comparator = java.util.Comparator,", " Timer = java.util.Timer", " TimerTask = java.util.TimerTask", " Scanner = java.util.Scanner", " File = java.io.File,", " FileFilter = java.io.FileFilter,", " FilenameFilter = java.io.FilenameFilter,", " BufferedReader = java.io.BufferedReader,", " FileReader = java.io.FileReader,", " PrintWriter = java.io.PrintWriter,", " InputStream = java.io.InputStream,", " OutputStream = java.io.OutputStream,", " IOException = java.io.IOException,", " StringBuilder = java.lang.StringBuilder,", " System = java.lang.System,", " Cloneable = java.lang.Cloneable", " Comparable = java.lang.Comparable", " Iterable = java.lang.Iterable", " Runnable = java.lang.Runnable", " Thread = java.lang.Thread", " ThreadGroup = java.lang.ThreadGroup", " ThreadLocal = java.lang.ThreadLocal", " Character = java.lang.Character", " Byte = java.lang.Byte", " Short = java.lang.Short", " Integer = java.lang.Integer", " Long = java.lang.Long", " Float = java.lang.Float", " Double = java.lang.Double", " Random = java.lang.Random", " StrictMath = java.lang.StrictMath"); evalJS(js, // transfers all PConstants' to JS global scope. "void function () {", " for each (var f in PConstants.class.getFields()) {", " var name = f.getName(), field = PConstants[name]", " if (!this[name]) this[name] = field", " }", "} ()"); evalJS(js, // transfers all PApplet's static fields to JS global scope. "void function () {", " for each (var f in PApplet.class.getFields()) {", " var name = f.getName(), field = PApplet[name]", " if (field && !this[name]) this[name] = field", " }", "} ()"); evalJS(js, // transfers all PApplet's static methods to JS global scope. "void function () {", " for each (var m in PApplet.class.getDeclaredMethods()) {", " var name = m.getName(), method = PApplet[name]", " if (method && !this[name]) this[name] = method", " }", "} ()"); // Injects PApplet's non-static members to JS global scope: evalJS(js, "Object.bindProperties(this, p)"); evalJS(js, // transfers JS' Math static properties to global scope. "void function () {", " for each (var prop in Object.getOwnPropertyNames(Math))", " if (!this[prop]) this[prop] = Math[prop]", "} ()"); } @SafeVarargs static final String evalJS (final ScriptEngine js, final String... statements) { if (statements == null) return ""; final String expression = PApplet.join(statements, PConstants.ENTER); try { js.eval(expression); } catch (final ScriptException cause) { PApplet.println(cause); System.err.println(expression); throw new RuntimeException(cause); } return expression; } @SafeVarargs static final CompiledScript compileJS (final ScriptEngine js, final String... statements) { final String expression = statements != null? PApplet.join(statements, PConstants.ENTER) : ""; try { return ((Compilable) js).compile(expression); } catch (final ScriptException cause) { PApplet.println(cause); System.err.println(expression); throw new RuntimeException(cause); } } static final Object runJS (final CompiledScript compiled) { try { return compiled.eval(); } catch (final ScriptException cause) { PApplet.println(cause); throw new RuntimeException(cause); } } @SafeVarargs static final Object invokeJS (final ScriptEngine js, final String funct, final Object... args) { try { return ((Invocable) js).invokeFunction(funct, args); } catch (final Exception cause) { PApplet.println(cause); System.err.println(funct); PApplet.printArray(args); throw new RuntimeException(cause); } }