Converting Vector Processing syntax to p5 sketch - javascript

I am learning coding and am a novice. I am currently trying to convert a Processing(java) sketch to a p5(javascript) sketch to put on my first website.
I'm having trouble translating the Vector and Array syntax from the Processing sketch.
This is the Vector from the processing Sketch (working):
for (int i = pts.size()-1; i >= 0; i --){
PVector pt = (PVector)pts.get(i);
......
PVector pt2 = (PVector)pts.get(j);
if (pt.dist(pt2) < 20){
......
Here is how I've been trying to translate it in p5 (not working)
for (var i = pts.size()-1; i >= 0; i --){
pt = p5.Vector.pts.get(i);
...........
var pt2 = (PVector)pts.get(j);
if (pt.dist(pt2) < 20){
line(pt.x, pt.y, pt2.x, pt2.y);
}
}

You shouldn't try to translate code by going line-by-line and translating the syntax. Instead, you need to take a step back and convert the program into English first. Then you take that English and try to implement it in the targed language. That might sound dumb, but that English is called an algorithm.
So, you should have a description of your program like this:
"Show 10 circles bouncing around the screen. If a circle touches the edge of the screen, it should bounce off by..."
That's just an example, but you get the idea. Then you'd take that and implement it in P5.js.
So instead of saying "how do I convert this array syntax to P5.js", you should be asking yourself "how do arrays work in JavaScript" or even "how do variables work in JavaScript". From there you can read tutorials to figure out how to implement your algorithm in P5.js.
Then if you get stuck on a specific syntax error, please look in the JavaScript console for any errors you're getting. We can't really help if all you tell us is that it's not working. What error are you getting? Where is your MCVE?
All of that being said, I'll try to help with your specific question. Let's take the original line:
PVector pt = (PVector)pts.get(i);
This line is declaring a variable named pt and is pointing it at whatever is returned from pts.get(i), which it casts to a PVector because Java is statically typed so everything needs a type.
Compare that to what you're trying to do in P5.js:
pt = p5.Vector.pts.get(i);
First off, where did you declare the pt variable? Secondly what is p5.Vector.pts? This syntax doesn't make any sense. You need to read up on how variables and arrays work in JavaScript.
Similarly, let's look at this line in your P5.js code:
var pt2 = (PVector)pts.get(j);
Again, where is pts declared? And you never have to cast anything in JavaScript, because it's dynamically typed. Again, you need to go back and read up on how variables in JavaScript work.
Shameless self-promotion: I've written a series of tutorials geared towards Processing developers trying to learn JavaScript, available here.

Related

Javascript Runtime Error Involving Value Not Written in Code

I am using App Lab on Code.org, which utilizes JavaScript commands; however, they have their own UI controls. Therefore, the code will contain commands such as onEvent() and setText(), etc. etc. These are all acceptable.
I am attempting to make a code for the Spherical Law of Cosines that calculates the distance between four different locations, but I am getting a runtime error message stating this: "Line: 171: Oops, we can’t figure out what -0.9208185005422157 is - perhaps you meant the string “-0.9208185005422157” with quotes? If this is meant to be a variable, make sure you declared a variable: var -0.9208185005422157."
The line in reference is as follows:
N = Math.acos((((((Math.abs(Math.cos(a)))*(Math.PI/180))*(Math.abs((Math.cos(b)(Math.PI/180))))+(((Math.abs(Math.sin(a)*(Math.PI/180)))+((Math.abs(Math.sin(b)*(Math.PI/180)))))*(((Math.abs(Math.cos(n))*(Math.PI/180)))))))));
Basically, I'm trying to find the value of the angle between two locations using the Spherical Law of Cosines, so I converted all of my values to degrees.
What would cause the error to log a random value in that line that I did not write?
It seems that you are missing a *
Math.cos(b)(Math.PI/180)
should be
Math.cos(b)*(Math.PI/180)

Non-linear regression with errors in variables in JavaScript

I need a robust curve-fitting algorithm that would work in a browser. Namely I need it to be able to fit polynomial and trigonometric (and ideally all custom) functions, and it also has to account for errors in both variables.
I would like to use an existing library or rewrite an implementation written in a different but understandable language (pseudocode, Python, C#, C without much memory magic, etc.). Alternatively I could use a transpliter to JavaScript if it were possible. However I've searched for hours and haven't found any suitable JavaScript library, nor a straightforward implementation that I could crib.
I have found two pieces of software that can do what I want.
The first one is Gnuplot which is a utility written in C. It's open-source, but I found the code somewhat convoluted and the curve-fitting part was quite inter-dependent with other parts of the program, so I didn't manage to port it to JavaScript.
The second one is SciPy, a math library for Python. That would be an easy victory if the relevant part were actually written in Python. Which, sadly, is not the case, as instead it's a piece of old Fortran code modified, so that it can communicate with Python. The code was too difficult and archaic for me and Fortran-to-Javascript transpliters didn't work because of the Python-specific stuff in the code.
Do you know any project I could use? I know it's not going to be a “solve-all answer” but I will appreciate anything that will get me closer to the finish.
gnuplot can be transcoded via Emscripten to run as javascript in a browser. See live demonstration site gnuplot + emscripten.
The resulting javascript variant is not currently supported by the gnuplot project but the proof-of-principle demonstration is impressive.
Alglib.js will allow you to fit data data to an arbitrary function.
Go here for a complete example https://pterodactylus.github.io/Alglib.js/curve_fitting.html
<script type="module">
import {Alglib} from 'https://cdn.jsdelivr.net/gh/Pterodactylus/Alglib.js#master/Alglib-v1.1.0.js'
//import {Alglib} from '../Alglib-v1.1.0.js'
var f = function(a_n, x){
return a_n[3]*Math.pow(x, 3)+a_n[2]*Math.pow(x, 2)+a_n[1]*Math.pow(x, 1)+a_n[0];
}
let data = [[-3, 8], [1,3], [5,3], [9,8], [10,16]]
var fn1 = function(a){
let sum = 0
for (let i = 0; i < data.length; ++i) {
sum = sum + Math.pow(data[i][1] - f(a, data[i][0]), 2)
}
let sse = Math.sqrt(sum)
return sse
}
let solver = new Alglib()
solver.add_function(fn1) //Add the first equation to the solver.
solver.promise.then(function(result) {
var x_guess = [1,1,1,1] //Guess the initial values of the solution.
var s = solver.solve("min", x_guess) //Solve the equation
let x = solver.get_report()
solver.remove() //required to free the memory in C++
})
</script>

JavaScript: How do i use a string as a piece of code

I am making a simple-ish graph maker to visualise equations. I need to be able to have the user input a string in a textbox and then interpret that as a piece of code I can execute to produce the graph. The way I am displaying the graph is by going through x in small increments and using an equation to then calculate the y position and then drawing a line between the points. At the moment I am just manually making a function in the code for example:
function(val) { return (val * val) + 5; }
but I need to be able to create a similar function from a string so the user could just input something like "(x*x)+(2*x)". is there any way to do this?
Canonically, this is done with eval(), although it comes with many caveats and should probably be avoided.
There are several questions on SO that discuss eval alternatives, but in your case, I would suggest a very bare-bones parser -- especially if all you're handling are mathematical equations.

Can somebody please help me with a geometric transformation problem?

I need to draw a circular arc between two given points. I also have the arc's radius. I understand that this can be done using standard canvas APIs but I need to handle the case of elliptical arcs too. This code is a generalized solution. The only problem right now is that it doesn't work!
The mathematical concept behind this code is at https://math.stackexchange.com/questions/53093/how-to-find-the-center-of-an-ellipse.
My JS code is implementation of that. My JS code can be found at http://jsfiddle.net/BkEnz/2/. Ideally both the circles there should pass through the two little pink dots.
I hope somebody can point me towards the right direction. I have been trying to solve this for past few days now!
Fixed this issue. The corrected working code is at http://jsfiddle.net/ZxRBT.
Notice the line
var t = translate(-R1R2x, -R1R2y, IDENTITY_TRANSFORM());
In my previous version of the code this line was
var t = translate(-R1R2x, -R1R2y, sr);
So when I was calculating the value of C1 and C2, using the following code
C1 = compose(vut, [[R1x],[R1y],[1]]);
C2 = compose(vut, [[R2x],[R2y],[1]]);
I was also applying the sr composition over R1x,R1y and R2x,R2y, but these points were already in sr coordinate.
This was a grave mistake which I overlooked for really a long time.

Javascript+Canvas implementation of Game of Life not working

I'm having problems with my javascript+canvas implementation of Conways Game of Life.
The cells are being created just fine and the canvas boxed representing the cells are also being rendered fine. But somewhere along the way all cells seems to be set alive & aren't toggling.
For the life of me I can't understand what's wrong.
The javascript code is here and my implementation is here.
Can someone please tell me where I went wrong.
************************EDIT************************
I think I've figured out whats wrong. I'm passing an element of the 2d array to the reallyToggle() function, like so -
var reallyToggle = function(a) {
//code
}
reallyToggle(cell[i][j]);
I think the problem lies in this part of the code. Can anyone tell me how can I pass an element of an array to a function?
So your code is pretty obscure and overly-complicated to be honest. Creating a grid of custom Javascript function objects is way over-engineering: all you need is a 2D boolean array.
Problems like this are often easiest to solve if thought of as two separate problems: the problem space and the world space. The problem space is the area in which you solve the actual problem. The world space is the problem space mapped to a visual outcome. To separate it out for your problem, think of the problem space as the two dimensional array of booleans and then the world space is your canvas.
If you would like to clean up your simulation a bit, here is an approach that may help:
//Have some parameters that you can change around
var cellSize = 10;
var cellsWide = 100;
var cellsHigh = 100;
//Instantiate and initialize a 2d array to false
var theGrid = new Array();
for (var i=0; i<cellsWide; i++) {
theGrid.push(new Array());
for (var j=0; j<cellsHeight; j++) {
theGrid[i].push(false);
}
}
//Attach a click event to your canvas (assuming canvas has already been dropped on page
//at the assigned width/height
$('#simCanvas').click(function(e) {
var i = Math.floor((e.pageX - this.offsetLeft)/cellSize);
var j = Math.floor((e.pageY - this.offsetTop)/cellSize);
theGrid[i][j] = !theGrid[i][j];
});
This would be a much more succinct way for you to handle the problem space. The mapping of problem space to world space is a bit more straight-forward, but if you need help with that just let me know.
Cheers
This line is rather suspect :)
if (!run) run == true;
First of all, check MoarCodePlz answer. And about Your code:
Uncaught exception: ReferenceError: Undefined variable: gameLoop when pressing start.
All Your functions that are defined in initialize are not in global scope, so they are not reachable in global scope.
Please, use Firebug; Chrome Developer Tools, Opera Dragonfly or something to find out such errors. These tools really help while developing JS.

Categories

Resources