Why Brython is important

845 views
Skip to first unread message

Bruce Sherwood

unread,
Feb 6, 2014, 5:27:14 PM2/6/14
to bry...@googlegroups.com
Here is an interesting talk on the future of Python:


I was surprised that this talk didn't touch on what may be really crucial, which is the importance of being able to use Python in client-side browser programming. Running in a browser is of rapidly increasing importance and Python could easily get left behind. There exist multiple projects whose goal is to be able to compile Python to JavaScript to address this issue. It looks to me like Brython may be the best bet, in that it seems to be an active development with a small but growing community of interested parties. I'd like to comment on why Brython is interesting to me.

I'm one of the major developers of VPython (vpython.org) which makes it easy even for novices to write Python programs that generate navigable real-time 3D animations as a side effect of computations. In the last six months there were nearly 50,000 downloads of VPython, and VPythnon is featured in four (soon to be five) computational physics textbooks. Many of these downloads were by university engineering and science students taking an intro physics course that uses a textbook by Ruth Chabay and me that includes a serious introduction to computational modeling (matterandinteractions.org, www.coursera.org/course/phys1). The vast majority of these students have never written a program before, so the ease of learning and using Python has been crucial to the successful introduction of computational modeling into an already crowded physics course.

Inspired by VPython, with a big initial push from David Scherer, the originator of VPython, I'm developing GlowScript (glowscript.org) where you can write VPython-like 3D animations using WebGL, writing in JavaScript or CoffeeScript. A minimal program is the single-line program

box()

This program places a WebGL canvas in the window, displays a cube in the window, creates lights to illuminate the scene, places the camera so that the cube fills the window, and enables mouse interactions to zoom and rotate. You can of course control all of these elements, but there are lots of good defaults to get going easily. Needless to say writing WebGL programs with other tools is vastly more difficult.

It's already the case that it's very nice to be able to send a URL in an email and have the recipient click that link to see a 3D animation rather than asking them to install Python and VPython. Here's a simple example that will run in WebGL-enabled browsers:


Many more demo programs are available at glowscript.org.

However: I don't like the syntax of JavaScript, especially for novice programmers, and even though CoffeeScript is more Pythonesque its syntax and use of white space is kind of quirky and, I judge, not good for novices. I would love to enable Python as one of the languages (indeed the major language) for novices and experts to write GlowScript programs. I hope very much that Brython can make this feasible, and I'll try using it in the near future (I'm tied up at the moment working on a new edition of our physics textbook).

I was disappointed that when I raised the issue of Python in the browser in a Python forum Guido said, "I think this is a lost cause. Many very smart people have broken their heads against this particular wall." I realize that it would be difficult to import the entire Python ecology into the browser since there are many modules not written in pure Python; maybe it was this issue that led to Guido's pessimism. For my purposes it would be sufficient to have the basic Python syntax; the kinds of things done with VPython and GlowScript don't depend on having access to all Python modules. Moreover, the higher speed of JavaScript compared to Python should reduce the need for something like numpy.

I'll be watching Brython development with interest.

Kiko

unread,
Feb 6, 2014, 5:46:34 PM2/6/14
to bry...@googlegroups.com



2014-02-06 Bruce Sherwood <bruce.s...@gmail.com>:

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/brython/44097b88-2388-4e1a-8d0e-7b9326c1c721%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Hi Bruce,

Very interesting work and inspiring words.

Let's make our dreams a reality!!!

P.D.: I used VPython in the past and I wrote a post about it in our scientific python blog (in spanish): https://pybonacci.wordpress.com/2012/10/02/lanzando-proyectiles-con-ayuda-de-vpython/
I remember it was annoying to have to record the animation, upload the video to youtube, link the video,... It would be easier with brython and glowscript!!!!!!!!!

Bruce Sherwood

unread,
Feb 6, 2014, 6:32:30 PM2/6/14
to bry...@googlegroups.com
¡Gracias por su interesante uso de VPython! Quiero mencionar que un grupo internacional en Chile, Colombia, Puerto Rico, y México está traduciendo nuestro libro al español.

Billy Earney

unread,
Feb 6, 2014, 6:47:44 PM2/6/14
to bry...@googlegroups.com
Should we add a VPython like library to the GSOC Idea List?  We could use glowscript as a module of how to produce this in 100% python, or we could wrap the glowscript libraries.

What do others think?

Billy


Bruce Sherwood

unread,
Feb 6, 2014, 8:24:23 PM2/6/14
to bry...@googlegroups.com
I'm not sure exactly what you have in mind, so let me briefly summarize the current status of GlowScript.

It consists of libraries written in JavaScript that can be imported to permit easy construction of 3D scenes and animations, using WebGL. The graphics primitives include box, sphere, cylinder, arrow, etc. You can add textures and bumpmaps to these objects. You can create a set of "vertex" objects that have position, color, and normal, and then create triangles and quads that change when you modify the vertex objects they use. You can create distant and local lights. You can write infinite loops that nevertheless perform repeated renderings and recognize mouse interactions, as well as event-driven programs (some of the Example programs at glowscript.org are provided in both versions). You can add and subtract vectors in the form A+B and A-B despite the fact that JavaScript doesn't support operator overloading. True pixel-level transparency is supported using a depth-peeling algorithm in the GPUs.

I would think that there are two different ways of linking the GlowScript capabilities to Python. One way is to do what has been done with CoffeeScript. At glowscript.org if you choose CoffeeScript, when you execute your program it is passed through the CoffeeScript compiler to make JavaScript, which then runs. A different approach would be to just use the GlowScript libraries outside the glowscript.org environment, but currently this isn't ideal because at glowscipt.org there is also a pre-execution pass using the Streamline library to make the vector operator overloading work. Currently one can export a preprocessed GlowScript program to your own web site, but without going through the glowscript.org preprocessing there are restrictions on writing your program from scratch. For example, to add two vectors you have to write A.add(B) instead of A+B. These details are discussed in the Help available at glowscript.org. See the links on the first page of the Help.

Billy Earney

unread,
Feb 6, 2014, 8:54:10 PM2/6/14
to bry...@googlegroups.com
What you are saying about glowscript, doesn't seem to be ideal. 

Billy


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Pierre Quentel

unread,
Feb 7, 2014, 11:11:16 AM2/7/14
to bry...@googlegroups.com

Bonan tagon Bruce,

I couldn't agree more to your introduction on why it's important to be able to run Python in the browser. I also agree that Brython is the best solution for that, but I might be slightly biaised...

I am not surprised by Guido's answer. In his keynote at PyCon 2012 he said that convincing browser vendors to natively include Python would be very difficult (and he was working for Google at the time), which leads me to think that he regrets it. In a recent interview for slashdot he even asked not to try to translate Python to Javascript, because the semantics are too different and the result would be too slow. His answer to your message is less definitive, he is just saying that very smart people tried and did not succeed. That's good news : dummies like us might make it ;-)

I downloaded the glowscript package with Google Apps engine and tried to imagine how Brython could be introduced to allow writing 3D scripts in Python. I am certain it's possible, but it will require some work of someone who dives into both projects. I like Billy's suggestion to add this topic in the ideas list for Google Summer of Code ; Bruce, do you agree ? if so, can you think of students in your university who could apply for this topic if Brython is selected ?

- Pierre

Billy Earney

unread,
Feb 7, 2014, 11:38:41 AM2/7/14
to bry...@googlegroups.com
What I see happening in the browser dealing with python client side programming is that, it will start with python being developed in javascript (projects like Brython), and then eventually when it gains popularity is for browsers to support python natively, so that people get the speeds they demand.  I guess it could be seen as a browser plugin.  If the python plugin is installed it uses the plugin for speed, if not, fallback to a python implemented in javascript would occur.

This evolution won't happen overnight, but projects like Brython could be a catalyst, and could help mold how python is used in client side development.

Billy


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 7, 2014, 4:17:12 PM2/7/14
to bry...@googlegroups.com
Pierre, estas surprizo, ke vi salutas min Esperante....

I'm formally retired (though professionally active), and I don't have access to students at my most recent university (North Carolina State University) who could contribute (I now live in Santa Fe, New Mexico). I do agree that making it possible to call GlowScript functions from Brython would be an interesting and useful project. It obviously requires someone to get familiar with both components. I hope that in less than a year I can make a stab at this myself, by learning to use Brython. 

For completeness I should address a question no one asked, which is "what about accessing VPython capabilities from Brython?" The answer is that the guts of VPython are written in C++ in order to get the necessary speed, so it's not pure Python. Also, it currently uses OpenGL, almost entirely from the CPU side, with shaders used only for textures, whereas GlowScript uses WebGL and necessarily does almost all graphics with GPUs. (I hope eventually to redo the VPython graphics to use GPUs, building on the GlowScript shaders.)

I assume that the fact that the GlowScript library is all in JavaScript isn't a barrier to being called from Brython, yes? Please excuse my ignorance.

I don't understand the speed issue. If one compiles Python to JavaScript I would expect a speedup. Or is it Guido's concern that lots of extra code would have to be generated to deal with the differences?

Here in Santa Fe Ruth and I benefit from regular conversations with people who are very powerful with computers. A recent conversation brought into relief that our main concern is Python syntax, not so much Python ecology. By this I mean that for the non-expert programmers who are a majority of the users of VPython and GlowScript, what matters is the cleanliness of Python syntax, not access to the huge set of Python modules. Since many significant Python modules are not written in pure Python, I assume that Brython does not and cannot have as a major goal making all Python modules available to Brython, right?

Bruce

Billy Earney

unread,
Feb 7, 2014, 7:49:53 PM2/7/14
to bry...@googlegroups.com
Bruce,

I think migrating the vpython code is the way to go.   We can use glowscript as a source if we get stuck migrating parts of the code. :)

See

Would you be interested in being a co-mentor (with myself) for the VPython Google Summer of Code Idea?

Billy



--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Francois Dion

unread,
Feb 7, 2014, 8:26:55 PM2/7/14
to bry...@googlegroups.com

Bruce,

I'm in Winston Salem, and the local Python user group meets at WFU. We had a presentation on vpython back in July 2013:

http://www.pyptug.org/2013/07/pyptug-meeting-july-22nd.html

Dr Aaron Titus teaches physics at High Point uni. He is aware of Brython through PYPTUG. perhaps he could help in finding students.

I've also introduced Gary Bishop of UNC chapel hill to Brython, and to some folks at NCSU.

I'll also be presenting at tripython (Raleigh Durham area python user group) in march,many members from UNC and ncsu.

Between all these avenues, it would be a shame if we can't find some teacher/students interested in helping.

Francois

Bruce Sherwood

unread,
Feb 8, 2014, 1:16:45 AM2/8/14
to bry...@googlegroups.com
I'm confused, doubtless because I don't know anything about Brython other than I want to use it. I would think the VPython code is useless, since it is mostly written in C++ and uses CPU-based OpenGL for graphics, not GPU-based WebGL. Presumably Brython can call libraries written in JavaScript? And surely Brython can't call libraries written in C++? What am I missing?

In principle yes, I would be interested in being a co-mentor. A few years ago I mentored a student in Brazil in the GSOC.

Bruce

Bruce Sherwood

unread,
Feb 8, 2014, 1:22:26 AM2/8/14
to bry...@googlegroups.com, Aaron Titus
I'm delighted to hear of your connection to my friend and colleague Aaron Titus, a physicist who was one of the very first adopters of our Matter & Interactions textbook, including computational modeling based on VPython. Aaron once said, "VPython is a gateway drug to the Matter & Interactions curriculum." I wish you luck in scaring up additional human resources. Whom have you spoken with at NCSU, where I was in the physics department until I retired in 2008?

Bruce

Billy Earney

unread,
Feb 8, 2014, 8:25:02 AM2/8/14
to bry...@googlegroups.com
Bruce,

I noticed you are a contributor to the vpython source code, so you know the code much better than I do.   The approach we would have to take is to convert the C code to python and/or javascript, and calls made to OpenGL libraries would need to be converted to WebGL.

I am not an expert in Vpython, OpenGL or WebGL.  So this might be an overwhelming task.  What do you think?

Billy


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Kiko

unread,
Feb 8, 2014, 9:52:11 AM2/8/14
to bry...@googlegroups.com



2014-02-08 14:25 GMT+01:00 Billy Earney <billy....@gmail.com>:
Bruce,

I noticed you are a contributor to the vpython source code, so you know the code much better than I do.   The approach we would have to take is to convert the C code to python and/or javascript, and calls made to OpenGL libraries would need to be converted to WebGL.

I am not an expert in Vpython, OpenGL or WebGL.  So this might be an overwhelming task.  What do you think?

Billy


On Sat, Feb 8, 2014 at 12:16 AM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
I'm confused, doubtless because I don't know anything about Brython other than I want to use it. I would think the VPython code is useless, since it is mostly written in C++ and uses CPU-based OpenGL for graphics, not GPU-based WebGL. Presumably Brython can call libraries written in JavaScript? And surely Brython can't call libraries written in C++? What am I missing?

In principle yes, I would be interested in being a co-mentor. A few years ago I mentored a student in Brazil in the GSOC.

Bruce


On Friday, February 7, 2014 5:49:53 PM UTC-7, Billy Earney wrote:
Bruce,

I think migrating the vpython code is the way to go.   We can use glowscript as a source if we get stuck migrating parts of the code. :)

See

Would you be interested in being a co-mentor (with myself) for the VPython Google Summer of Code Idea?

Billy



Maybe a brython wrapper around three.js would be a good start: http://threejs.org/
There is an example in the brython gallery made by Dirk Krause: http://brython.info/gallery/three.html

Billy Earney

unread,
Feb 8, 2014, 10:14:06 AM2/8/14
to bry...@googlegroups.com
Sure, especially if we can emulate vpython's api with three.js.  Doing this could be less effort than converting the C libraries.

Billy


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 8, 2014, 12:33:09 PM2/8/14
to bry...@googlegroups.com
I continue to be deeply puzzled by why VPython would seem a better starting point than GlowScript. One way to think about GlowScipt is that it is a re-implementation of VPython. The syntax and semantics of GlowScript were inspired by and heavily dependent on the syntax and semantics of VPython. There are also significant differences, for two reasons. One is that many years of experience in the development and use of VPython (for which I am indeed one of the main developers) suggested improvements, and the other is that going from CPU-based OpenGL to GPU-based WebGL was a Big Deal. One could say that the work of converting VPython to JavaScript has already been done by creating GlowScript. (There remains work to convert VPython's CPU-based use of OpenGL to GPU-based use of OpenGL, and this work will benefit from the existence in GlowScript of rather sophisticated GPU vertex and fragment programs, including handling pixel-level transparency correctly.)

By giving too many details about the architecture of GlowScript, did I unintentionally give the impression that there are insuperable problems with just calling the GlowScript libraries from Brython? Surely it is possible to call JavaScript libraries from Brython?

The JavaScript library threejs is probably the most widely used wrapper of the very low-level WebGL, but the goal of threejs is to server the expert programmer. Last year I went through a Udacity course on computer graphics in which the problems were coded using threejs. One of them was a "drinking bird" animation. As a test, I also coded it in GlowScript, which you can see here (as long as you have a WebGL-enabled browser):


The threejs program was 320 lines long, with pretty arcane coding. The GlowScript version is 60 lines long, and if you click "Edit this program" you'll see that the code is quite simple.

The architecture of threejs requires that much of the graphics manipulation must be done on the CPU side, whereas in GlowScript all the heavy lifting is done by the GPUs, which should provide significantly higher performance.

By all means make it possible to use threejs with Brython, as it serves its users very well and has emerged out of a crowded field of such libraries as the one that is most widely used. But GlowScript has a different purpose and a different intended audience.

Bruce

Bruce Sherwood

unread,
Feb 8, 2014, 12:36:57 PM2/8/14
to bry...@googlegroups.com
And a minor correction: As I said earlier, the core of VPython is not written in C, it's written in C++. I don't know whether that makes a difference as far as the Brython environment is concerned.

Bruce

Cyrille Rossant

unread,
Feb 8, 2014, 1:18:42 PM2/8/14
to bry...@googlegroups.com, vi...@googlegroups.com
(cross-posting on Brython and Vispy mailing lists)

Dear Brython developers,

I'm following this discussion with great interest. I'm a core
developer of Vispy (http://vispy.org), a new visualization library in
Python based on OpenGL (2D/3D). Vispy gives high-level and Pythonic
access to modern OpenGL & GLSL (shaders) for various purposes,
including interactive data visualization. Our main goals are
performance (using the GPU for as many things as possible) and ease of
use.

The project is still in its infancy. For now, we have an
object-oriented layer wrapping OpenGL (called "gloo"). We're now
working on intermediate-level layers that aim at giving non OpenGL
experts access to the powerful visualization capabilities of OpenGL.

Although Vispy is currently pure Python, we would like to create a web
backend in the long run (WebGL). The idea would be to write high-level
code in Python, and generate automatically a pure HTML/Javascript
document with the implemented visualization. I'm currently looking at
the various possibilities for this challenging task, and Brython is
one of the potential solutions I want to investigate.

It seems we have converging goals and we would love to collaborate
with people from your side! In particular, we'd be very interested in
benefiting from your expertise in Python->Javascript translation.

All the best,
Cyrille
> --
> You received this message because you are subscribed to the Google Groups
> "brython" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to brython+u...@googlegroups.com.
> To post to this group, send email to bry...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/brython/610eef88-131b-4891-9cae-92eaff5eb891%40googlegroups.com.

Christophe Gragnic

unread,
Feb 8, 2014, 2:19:31 PM2/8/14
to bry...@googlegroups.com
On Sat, Feb 8, 2014 at 6:33 PM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
> just calling the GlowScript libraries from Brython? Surely it is possible to
> call JavaScript libraries from Brython?

Yes. Please click on «Using Javascript objects and libraries» at:
http://brython.info/doc/en/

> The JavaScript library threejs is probably the most widely used wrapper of
> the very low-level WebGL, but the goal of threejs is to server the expert
> programmer...

See this demo: http://brython.info/gallery/three.html


chri

--

http://profgra.org/lycee/ (site pro)
http://delicious.com/profgraorg (liens, favoris)
https://twitter.com/profgraorg

Billy Earney

unread,
Feb 8, 2014, 4:57:23 PM2/8/14
to bry...@googlegroups.com
Bruce,

This is a great conversation.  You obviously have more experience with VPython and GlowScript than I do (I have none). Going with glowscript maybe the best solution.  Creating a wrapper around glowscript that emulates VPython maybe the path of least resistance.

You can easily access any javascript object using the JSObject function which is defined in Brython's custom Javascript module. (http://brython.info/doc/en/)

I shied away from glowscript because of the "extra processing that needed to be done", but looking at the code, it looks like it is just handling a few special cases (such as operator overloading), that could be handled in brython.

Bruce, to be clear, (and maybe I've gotten off topic), you are interested in emulating VPython in a web environment, and maybe use glowscript as a helper library to emulate the VPython libraries?  

Billy



On Sat, Feb 8, 2014 at 11:36 AM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
And a minor correction: As I said earlier, the core of VPython is not written in C, it's written in C++. I don't know whether that makes a difference as far as the Brython environment is concerned.

Bruce

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Billy Earney

unread,
Feb 8, 2014, 5:10:31 PM2/8/14
to bry...@googlegroups.com, vi...@googlegroups.com
Cyrille,

Welcome to the group!   We definitely would be interested in playing a part in vispy's future.  Since vispy is 100% python, this should work quite well.  We really don't know how we are going to handle WebGL (as you can see from this post), but the group is trying to create a python 3 interpreter that will compile most if not all of python 3 syntax.  We've come along way, but we still have a ways to go.   I'd like to see brython compile all of python 3's standard library, and any other code that python 3 can handle.  Of course there will not be a 100% conversion rate, since some things don't make sense to run on the web that runs on an OS and vice versa.  FileIO is tricky, but we can get it work in some/most cases., etc.

Billy

Cyrille Rossant

unread,
Feb 8, 2014, 6:10:42 PM2/8/14
to bry...@googlegroups.com, vi...@googlegroups.com
> Welcome to the group! We definitely would be interested in playing a part
> in vispy's future. Since vispy is 100% python, this should work quite well.
> We really don't know how we are going to handle WebGL (as you can see from
> this post), but the group is trying to create a python 3 interpreter that
> will compile most if not all of python 3 syntax. We've come along way, but
> we still have a ways to go. I'd like to see brython compile all of python
> 3's standard library, and any other code that python 3 can handle. Of
> course there will not be a 100% conversion rate, since some things don't
> make sense to run on the web that runs on an OS and vice versa. FileIO is
> tricky, but we can get it work in some/most cases., etc.

This looks encouraging. I look forward to trying Brython on Vispy's code.

There's one part that is really not trivial though: even if Vispy is
pure Python itself, it still depends on NumPy, which is *really* not
pure Python! The idea of NumPy running entirely in the browser seems a
bit crazy (it contains a lot of C code, and it depends on compiled C
and FORTRAN libraries).

However, we use a tiny fraction of NumPy. We'd essentially need the
ndarray data type and vectorized computations. I think implementing
that in Javascript (typed arrays), or in pure Python so that it could
be used directly with Brython, would be really interesting in itself.
There's a whole community in scientific computing that heavily relies
on NumPy, and bringing part of NumPy in Brython would make much sense
in my opinion. That could make a nice GSoC project! :)

As far as performance is concerned, I don't really know how Brython
works, but if we can end up with the simplest Javascript "for" loop
over an ArrayBuffer, we'd probably reach the best performance we can
expect with Javascript.

Best,
Cyrille

Bruce Sherwood

unread,
Feb 8, 2014, 6:15:26 PM2/8/14
to bry...@googlegroups.com
Billy, hanks for the clarifications, and the reassurance that one can call JavaScript libraries from Brython. Yes, this is a great conversation.

The task is not to create "a wrapper around glowscript that emulates VPython". GlowScript already "emulates VPython", in that the basic concepts are very nearly the same (e.g. box() produces a 3D box in either environment) but updated to be appropriate for the browser/WebGL environment. There is a ton of architectural issues that GlowScript had to address that made it either highly advantageous (based on years of development and use of VPython) or even absolutely necessary to make some changes. In many (most?) common cases, an existing VPython program could probably run in a Brython-GlowScript environment, or could run after small tweaks (I've already written a somewhat useful Python program that converts a VPython source file to a GlowScript JavaScript source file, though the conversion currently leaves much to be desired).

I'm really glad to hear that Brython supports operator overloading, because as I said earlier it's very important for ease of use in doing 3D graphics to be able to do vector addition as A+B rather than A.add(B) and scalar multiplication of a vector as 5*A rather than A.multiply(5), etc. So check that one off the list of possible issues.

The other sizable issue takes some explaining. A VPython 3D animation is typically an infinite loop, but one which contains a statement like "rate(100", meaning "don't do more than 100 loop iterations per second, even if the computer is fast enough to do so". Without such a function you would typically have an animation too fast to see. Also, in VPython this rate function takes care of periodically calling OpenGL functions to update the screen, about 30 times per second.

In the browser/WebGL world it is essential to write an animation using callback routines; you cannot in the midst of a function update the screen, unlike the situation with VPython. Rather you have to structure the program to have a screen-update function that is driven by a timer (tied to the hardware refresh cycle). It is our experience that such "asynchronous" programs are not intuitive to beginners, and we teach novices to write "synchronous" programs like the VPython infinite loop I just described. 

In order to make it possible to write synchronous programs in an environment where that is impossible, David Scherer (originator of VPython who also made major contributions to the initial development of GlowScript) built into the preprocessing of GlowScript programs (which are written in either JavaScript, or compiled to JavaScript from CoffeeScript) a pass using Streamline (github.com/Sage/streamlinejs), which rewrites the synchronous code to be asynchronous. In the case of the infinite loop, Streamline moves the loop contents into a separate function which then is driven by the timing specified in a rate statement. The GlowScript rate statement looks like "rate(100,wait)", where wait alerts Streamline to do the necessary restructuring, and at execution time rate is the callback routine.

In my ignorance of Brython, my naive notion is that when I have the time to study Brython, it might turn out to be trivial to permit people to write GlowScript programs in Python. Just add as an option a Brython compiler-to-JavaScript, along side the existing CoffeeScript compiler-to-JavaScript. It is already the case that GlowScript programs are required to have a header line "GlowScript 1.0" for JavaScript (the default) or "GlowScript 1.0 CoffeeScript" which invokes the CoffeeScript-to-JavaScript compiler (the "1.0" is a version number so that old GlowScript programs will keep working in the future even if there are changes in GlowScript syntax -- we maintain old libraries that are invoked by old version numbers). So I look forward to stating in the header "GlowScript 1.0 Python" or possibly "GlowScript 1.0 Brython", depending on what you guys deem best. The preprocessing by Streamline would be performed on the JavaScript code.

Bruce

Bruce Sherwood

unread,
Feb 8, 2014, 6:31:22 PM2/8/14
to bry...@googlegroups.com, vi...@googlegroups.com
Here is the Brython/threejs code for a rotating cube found at http://brython.info/gallery/three.html:

    <script type="text/python">
        print('start ...')
        from browser import doc

        cameraC = JSConstructor( THREE.PerspectiveCamera )
        camera = cameraC( 75, 1, 1, 10000 )
        camera.position.z = 1000;

        sceneC = JSConstructor( THREE.Scene );
        scene = sceneC();

        geometryC = JSConstructor(THREE.CubeGeometry)
        geometry = geometryC(200, 200, 200)
        materialC = JSConstructor( THREE.MeshBasicMaterial )

        material = materialC( { "color": "#ff0000", "wireframe": True } )

        meshC = JSConstructor(THREE.Mesh)
        mesh = meshC( geometry, material )
        scene.add( mesh );

        rendererC = JSConstructor(THREE.CanvasRenderer)
        renderer = rendererC()
        renderer.setSize( 444,444);


        doc <= renderer.domElement
        renderer.render( scene, camera )

        def animate(i):
            # note: three.js includes requestAnimationFrame shim
            requestAnimationFrame( animate );

            mesh.rotation.x += 0.01;
            mesh.rotation.y += 0.02;

            renderer.render( scene, camera );   

        print('.. end.')

    </script>

Here is a complete GlowScript program that is roughly equivalent to the threejs example (it's a solid red cube rather than a white cube with red edges and red diagonals):

GlowScript 1.0 CoffeeScript
b = box(color:color.red)
loop
    rate(50, wait)
    b.rotate(angle:0.05, axis:vec(1,1,1))
The threejs environment is in some important ways more powerful than GlowScript, but GlowScript makes it feasible for nonexpert programmers to create 3D animations, people who simply are not going to become sufficiently expert to use threejs. GlowScript and threejs address different audiences with different needs.

Billy Earney

unread,
Feb 8, 2014, 6:52:58 PM2/8/14
to bry...@googlegroups.com
There's more than one way to skin a cat,  so creating a glowscript like library could be done in many different ways.  I've only looked at a few glowscript examples, but it looks like quite a bit of stuff is being done in the background. 

Bruce, to verify that I'm understanding things correctly, (for now lets just ignore Coffee script examples).  Is there still some compiling that is being done to translate code such as the bouncing ball example at http://www.glowscript.org/#/user/GlowScriptDemos/folder/Examples/program/Bounce into something that can be executed in javascript?

I'm aware of the operator overloading issue that is addressed, and the rate function, so that users don't have to worry about async programming.  Are there other issues that have to be addressed?   I've noticed that extra glowscript libraries are loaded that define things such as box, etc.  But are there other things?   I believe a custom brython library could address the issues I've raised.

Billy



--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 8, 2014, 6:54:16 PM2/8/14
to bry...@googlegroups.com, vi...@googlegroups.com
I forgot an important footnote: The tiny GlowScript program that shows a rotating cube also by default turns on mouse control of the camera (zoom and rotate), to give you different views of the scene. The default camera placement is such as to make the scene fill the canvas ("autoscaling"). Lighting is also by default. All the defaults can be changed, but the key point is that the basics are very simple, and going beyond the basics doesn't involve very much additional code. The goal is, "The simple is easy and the difficult is feasible."

Message has been deleted

Bruce Sherwood

unread,
Feb 9, 2014, 11:02:07 AM2/9/14
to bry...@googlegroups.com
The GlowScript libraries (plural, in the sense that many different files are involved) are all in JavaScript and indeed they do lots and lots of stuff "in the background". For example, the first encounter of a call to a box or sphere function (to create a box or a sphere) causes the creation of a 3D WebGL canvas, the creation of default lighting, etc. Making a change in an attribute of a sphere object sets a "changed" bit indicating that the next time we update the screen we need to rebuild the data structure for that sphere, which will be sent to the GPUs the next time we render to the screen. Etc. But all of this is just the execution of JavaScript code in the GlowScript libraries.

I'll assume that there exists in the Brython world a separable self-standing JavaScript library that can take Python as input and give JavaScript as output, and that programs can be developed at glowscript.org. Conceptually, I could do what is done with CoffeeScript, where (neglecting the operator overloading part) the chain is CoffeeScript -> JavaScript -> Streamline -> execute. The new chain would be Python -> JavaScript -> Streamline -> execute. There is a "linking" phase that may or may not be problematic. After all, when "box()" is encountered in the original source code, no matter what the source language (JavaScript, CoffeeScript, Python), somewhere there has to be the equivalent of a Python import statement to enable invoking the box function. In a GlowScript program housed at glowscript.org it is implicit that the GlowScript libraries will be invoked, but the Python -> JavaScript compiler would have to know about these external names, presumably through the mechanisms invoked by a Python "import" statement. I would also have to understand how operator overloading works in the Brython environment.

Note that glowscript.org is two things. It houses libraries for doing 3D graphics, but it is also a place where people can write and store programs and let others run those programs by clicking a link to the program, as you've seen in the links I've put in earlier notes. I'm guessing that Brython isn't like that, that anyone writing a Brython program is expected to put it on their own web site.

A different environment is someone outside the glowscript.org environment (who might be using Brython) who wishes to use the GlowScript libraries. There is already, in the GlowScript Help, documentation on how to do this:


You'll see in this documentation that in this fully "exterior" case, lacking the preprocessing phase at glowscript.org, one has to say A.add(B) instead of A+B for vector addition (operator overloading issue) and one has to write asynchronous code rather than synchronous code. One currently has to write in JavaScript, not CoffeeScript or Brython, or equivalently compile CoffeeScript or Brython to JavaScript.

There is one other modality, already in existence. At glowscript.org, when editing a file you can click "Share this program" and you get a fully preprocessed JavaScript file that is now standard JavaScript ready to embed in your own web page, the operator overloading and synchronous issues having been dealt with. Below I show what that looks like. The output is quite ugly but should be thought of as a binary or as assembler code.

Here again is the rotating box program:

GlowScript 1.0 CoffeeScript
b = box(color:color.red)
loop
    rate(50, wait)
    b.rotate(angle:0.05, axis:vec(1,1,1))

And here is the preprocessed code (operator overloading, conversion from synchronous to asynchronous code) that GlowScript provides for embedding in one's own web page. A key statement here is the one that references the version 1.0 GlowScript libraries (http://www.glowscript.org/package/glow.1.0.min.js):

<meta http-equiv="X-UA-Compatible" content="chrome=1">
<div id="glowscript" class="glowscript">
<link type="text/css" href="http://www.glowscript.org/css/redmond/jquery-ui.custom.css" rel="stylesheet" /><link href="http://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css"><link type="text/css" href="http://www.glowscript.org/css/ide.css" rel="stylesheet" /><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
<script type="text/javascript" src="http://www.glowscript.org/lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="http://www.glowscript.org/lib/jquery/jquery-ui.custom.min.js"></script>
<script type="text/javascript" src="http://www.glowscript.org/package/glow.1.0.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script> CFInstall.check({ mode: "overlay" })</script>
<script type="text/javascript">
;(function() {
var __g=typeof global!=='undefined'?global:window;__g=(__g.__streamline||(__g.__streamline={}));__g.setEF=__g.setEF||function(e,f){e.__frame = e.__frame||f};var __srcName='undefined_.js';
function __func(a,b,c,d,e,f,g){if(!a)return __future.call(b,d,c,e);f.file=__srcName,f.prev=__g.frame,__g.frame=f;try{g()}catch(h){__g.setEF(h,f.prev),__propagate(a,h)}finally{__g.frame=f.prev}}
function __cb(a,b,c,d,e){b.offset=c,b.col=d;var f=__g.context;return function g(c,d){var g=__g.frame;__g.frame=b,__g.context=f;try{return c?(__g.setEF(c,b),a(c)):e(null,d)}catch(h){return __g.setEF(h,b),__propagate(a,h)}finally{__g.frame=g}}}
function __future(a,b,c){var d,e,f,g=function(a,b){d=!0,e=a,f=b};return b=Array.prototype.slice.call(b),b[c]=function(a,b){g(a,b)},a.apply(this,b),function(a){d?a.call(this,e,f):g=a.bind(this)}.bind(this)}
function __propagate(a,b){try{a(b)}catch(c){__trap(c)}}
function __trap(a){a&&(__g.context&&__g.context.errorHandler?__g.context.errorHandler(a):console.error("UNCAUGHT EXCEPTION: "+a.message+"\n"+a.stack))}
/*     1 */ __RUN_GLOWSCRIPT = function() {
/*     2 */   var main;
/*     4 */   main = function main__1(wait) {
                var b, scene;
                var __frame = {
                  name: "main__1",
                  line: 4
                };
                return __func(wait, this, arguments, main__1, 0, __frame, function __$main__1() {
/*     6 */       scene = canvas();
/*    10 */       b = box({
/*    11 */         color: color.red
                  });
                  return (function ___(__break) {
                    var __more;
                    var __loop = __cb(wait, __frame, 0, 0, function __$main__1() {
                      __more = false;
/*    16 */           var __1 = true;
                      if (__1) {
/*    20 */             return rate(50, __cb(wait, __frame, 16, -1, function __$main__1() {
/*    24 */               b.rotate({
/*    25 */                 angle: 0.05,
/*    26 */                 axis: vec(1, 1, 1)
                          });
                          while (__more) {
                            __loop();
                          };
                          __more = true;
                        }));
                      }
                       else {
                        __break();
                      }
                    ;
                    });
                    do {
                      __loop();
                    } while (__more);
                    __more = true;
                  })(function __$main__1() {
                    wait();
                  });
                });
              };
/*    31 */   return main;
/*    33 */ };

;$(function(){ window.__context = { glowscript_container: $("#glowscript").removeAttr("id") }; __RUN_GLOWSCRIPT()() })})()
</script>
</div>

Billy Earney

unread,
Feb 9, 2014, 11:22:42 AM2/9/14
to bry...@googlegroups.com
I found this page, which seems to help me...


I'm not sure how easy it will be to integrate brython with glowscript.org.   Brython contains a lot of its own libraries that must be available when the javascript runs.    Brython produces javascript, but not "pure javascript", that you could just copy and paste in a page, and it runs.  It will require a library called brython.js which defines many of the functions brython relies on.

For example, a simple "hello world" program in python is

print("hello world")

brython compiles this to:

var $globals = __BRYTHON__.scope["__main__"].__dict__
var $locals = $globals
var __doc__=$globals["__doc__"]=""
var __name__=$globals["__name__"]="__main__"
var __file__=$globals["__file__"]="http://brython.info/tests/editor.html"
document.$line_info=[1,"__main__"];None;
getattr($print,"__call__")("hello world")


which isn't "pure javascript".  Yes, it produces something in javascript syntax, but many functions are defined internally by brython (ie, getattr, $print, etc).


So I'm not sure if Python -> JavaScript -> Streamline -> execute.   is easy or even possible. 

I'm currently taking the simple example at http://www.glowscript.org/docs/GlowScriptDocs/libraryuse.html, and trying to duplicate this in brython, by using (accessing) the glowscript libraries.  I'm still working through a few issues, but hope to have it resolved soon.

Billy 



--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Glenn Linderman

unread,
Feb 9, 2014, 11:38:00 AM2/9/14
to bry...@googlegroups.com
On 2/9/2014 8:02 AM, Bruce Sherwood wrote:
A different environment is someone outside the glowscript.org environment (who might be using Brython) who wishes to use the GlowScript libraries. There is already, in the GlowScript Help, documentation on how to do this:


You'll see in this documentation that in this fully "exterior" case, lacking the preprocessing phase at glowscript.org, one has to say A.add(B) instead of A+B for vector addition (operator overloading issue) and one has to write asynchronous code rather than synchronous code. One currently has to write in JavaScript, not CoffeeScript or Brython, or equivalently compile CoffeeScript or Brython to JavaScript.

Granted I haven't looked at the GlowScriptDocs, only followed this interesting conversation.

Brython dynamically compiles itself, within the browser, to Javascript, rather than being a preprocessing step done on the server, but potentially includes the overloading of operators, as part of standard python capabilities.

If code were written (a python class, interfacing to GlowScript libraries to do the WebGL work) could it leverage Python/Brython's operator overloading? That is, the class's + operator would implement a call to GlowScript add function?

The synchronous versus asynchronous code issue has been described as being handled by some sort of javascript preprocessor... I don't know whether it might be possible to implement that conversion also as a python class... calling the class synchronously, but having it launch the appropriate asynchronous work for GlowScript?

In any case, it seems the discussion has revealed that GlowScript & CoffeeScript are all done as server-side preprocessing steps, and that isn't the case for Brython, which is a browser-side compile-and-go implementation.  So the big question here is how to marry those two different perspectives, and the smaller question is how to implement a straightforward implementation in Brython, for the Python user that wants to use WebGL capabilities, as pleasantly abstracted by GlowScript, without being "bothered" with JavaScript syntax or interfacing... hopefully those details can be handled by a python class (or several) using Brython's available interfaces to call Javascript code (probably the libraries documented at the quoted link above), and possibly also implementing (in python) an abstraction layer for the asynchronicity, as there would seem to be no way to invoke the asynchronous preprocessor of the (unseen by the server) output of the Brython to Javascript compilation process.

Whether in the future Brython might implement a server-side python-to-Javascript preprocessor to assist with reducing the up-front performance cost of compiling the whole (as much as is needed) python runtime at every invocation is unknown. An alternate approach for that could be a browser-side plugin that implements python syntax more directly, rather than depending on the Javascript engine for browser-side execution; or a plugin that caches the compilation results so that the second load of Brython could be significantly faster than the first. So depending on, or waiting for, a server side "compile python to javascript" step would deal a probably fatal blow to marrying Brython and GlowScript.

Cyrille Rossant

unread,
Feb 9, 2014, 12:02:44 PM2/9/14
to vi...@googlegroups.com, bry...@googlegroups.com
> In terms of visualization we only use numpy as a container of data and it
> should not be too hard to make these part independent of numpy. The parts
> that *do* use numpy for calcualtions are right now limited to calculating
> normals in the mesh reader, I think.

We'll probably start using NumPy more heavily pretty soon with the
transform layer (for CPU transformations). Also, some complex
interactive features for plotting will probably require NumPy.

> In terms of using webGL/Javascript as a backend, I think we can come a long
> way by preparing the data beforehand so that in the browser we do not need
> Numpy.

Good point. We may be able to do most of the initialization step in
Python. But for interactivity, we'll need (basic) NumPy in the browser
except for most trivial things.

Bruce Sherwood

unread,
Feb 9, 2014, 12:09:08 PM2/9/14
to bry...@googlegroups.com
My note and Billy's crossed in the ether. I'll be interested to see what he's able to do.

I do realize that a GlowScript program written in Python would not only have to compile the Python to JavaScript but also invoke the Brython run-time library, just as it has to invoke the GlowScript run-time library.

I seem inadvertently have given the impression that glowscript.org does server-side processing. No, all the work is done in the client. The only server-side stuff has to do with hosting user programs.

Bruce

Glenn Linderman

unread,
Feb 9, 2014, 12:18:37 PM2/9/14
to bry...@googlegroups.com
On 2/9/2014 9:09 AM, Bruce Sherwood wrote:
I seem inadvertently have given the impression that glowscript.org does server-side processing. No, all the work is done in the client. The only server-side stuff has to do with hosting user programs.

Indeed, I got that impression, although you probably didn't state it explicitly if it isn't true. So if your "javascript post-procesing" for GlowScript synchronous -> asynchronous conversion is done in the client, that makes it more likely that more existing code can be reused. On the other hand, that conversion may need to be tweaked, as the Brython-generated javascript may not look the same as CoffeeScript-generated javascript, or hand written javascript, but likely there would still be a pattern that could be recognized and converted... and it may be necessary for Brython to implement a "hook" of some sort by which the synchronous conversion can be invoked between Brython's compilation process and execution process.... or maybe that can be implemented in code generated as part of the interface class when the first GlowScript functionality is called.

Bruce Sherwood

unread,
Feb 9, 2014, 12:28:42 PM2/9/14
to bry...@googlegroups.com
The only real "hook" is the keyword "wait" that triggers Streamline to move code out of a loop and into a callback routine (with scheduling). It might be deemed okay in the full Brython environment (outside glowscript.org) to require asynchronous coding, which the GlowScript libraries also support. Again, it may be instructive to examine the four versions of the bouncing ball program in the Example programs available at glowscript.org.

Bruce

Bruce Sherwood

unread,
Feb 9, 2014, 3:30:57 PM2/9/14
to bry...@googlegroups.com
It would be useful to repackage the GlowScript chain "(language of your choice) -> JavaScript -> operator overloading and synchronous-to-asynchronous" so that environments outside glowscript.org could take advantage of this scheme. To put it another way, currently one can from outside the glowscript.org environment take advantage of the run-time portion of the GlowScript libraries but cannot easily take advantage of the compilation machinery. This is unfortunate not just for general use of GlowScript mechanisms but even within the glowscript.org environment itself, in that a GlowScript program can import outside libraries with the get_library() function, but currently that library has to be written in asynchronous non-operator-overloaded JavaScript.

Billy Earney

unread,
Feb 9, 2014, 5:27:14 PM2/9/14
to bry...@googlegroups.com
Bruce (and only else interested in integrating python and glowscript)...

Enclosed are 3 files, save these in a directory and run the server.py (python server.py) file to create a local web server on port 8000

Then load the files in the web browser

localhost:8000/test1.html
localhost:8000/test2.html

test1.html is a copy of an example from http://www.glowscript.org/docs/GlowScriptDocs/libraryuse.html

test2.html is a brython version of the same example, and a class I called glow which "glues" the glowscript library to brython.  This class and other utilities can be placed in a module file, and don't need to be placed at the top of every example.  We could just do a 'import glow' or something similar to make it work.

There are some issues, that are probably solvable but beyond my current abilities, so consider it a hack, and improvements could probably be made. :)

FYI..  I had trouble getting  box.rotate({'angle': 0.01, 'axis': vec(0,1,0)}) to work.  There seems to be an issue with the axis argument, so for now, I just commented it out, and left a few versions of things I tried in the code, just in case others want to experiment a bit with the code.

Billy



On Sun, Feb 9, 2014 at 2:30 PM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
It would be useful to repackage the GlowScript chain "(language of your choice) -> JavaScript -> operator overloading and synchronous-to-asynchronous" so that environments outside glowscript.org could take advantage of this scheme. To put it another way, currently one can from outside the glowscript.org environment take advantage of the run-time portion of the GlowScript libraries but cannot easily take advantage of the compilation machinery. This is unfortunate not just for general use of GlowScript mechanisms but even within the glowscript.org environment itself, in that a GlowScript program can import outside libraries with the get_library() function, but currently that library has to be written in asynchronous non-operator-overloaded JavaScript.

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.
test1.html
server.py
test2.html

Bruce Sherwood

unread,
Feb 9, 2014, 5:53:31 PM2/9/14
to bry...@googlegroups.com
It's exciting to see your test2.html file run, Billy. I do in fact see the rotating cube, and moreover mouse zoom and rotate work properly.

While the important thing is that you've shown an in-principle working example, I'm puzzled by the dictionary machinery being used. I would have thought that one would write pythonly "box.rotate(angle=0.1)", not "box.rotate(dictionary)". Could you comment on this?

Bruce

P.S. For the benefit of others who might like to try this, I put Billy's three files in a folder on my Windows machine C:\Python27\Brython and then in a command prompt cd'ed to C:\Python27 and executed python Brython\server.py. Then the actual address I had to use in the browser was http://localhost:8000/Brython/test2.html.

P.P.S. Here are the instructions for GlowScript zoom and rotate of the camera (not of the scene):

   Rotate the camera by dragging with the right mouse button, or hold down the Ctrl key and drag.
   To zoom, drag with the left+right mouse buttons, or hold down the Alt key and drag, or use the mouse wheel.



Billy Earney

unread,
Feb 9, 2014, 6:08:24 PM2/9/14
to bry...@googlegroups.com
I agree, rotate(angle=0.01) is more pythonic than what I put together.   The way I know to fix this is by creating a box class and wrap the glowscript box object in the class.

For this example, I created a class to wrap the generic glowscript library, so to make it more python like, we might have to build some wrappers around each primitive (box, sphere, etc).   

Others may have more insight into this, and what is possible.  Pierre may know of a slick way of doing this without creating wrappers, but we'll still need to create __doc__ and other variables, if we want it to appear to be a "real" python library.  So I don't know if this is possible (I doubt it), unless we are willing to write some wrappers in python.

We might want to have a conversation of what the library should look like ,etc.  The box.rotate function is a good example of what can be different (mainly function arguments, etc).  

Unless I'm very familiar with a library, I usually like to use existing examples and demos and translate those.  Maybe this should be an approach we take, unless someone prefers another way.

Billy

 


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 9, 2014, 7:24:51 PM2/9/14
to bry...@googlegroups.com
Note that there are lots of examples available by clicking on "Example programs" at glowscript.org.

All of the basic graphics primitives are very similar (more similar in fact than the corresponding graphics primitives in VPython). In the Help, read the description of the cylinder object to get a feel for the attributes of these primitives. It is of course true that there's also a sizable number of other things to be accessed, such as the rotate method, controlling the size and background color of the canvas, etc. If you get things started and establish a pattern, it would probably be easy for me to fill in the blanks.

Billy Earney

unread,
Feb 9, 2014, 7:57:08 PM2/9/14
to bry...@googlegroups.com
Bruce,

I'm glad to hear you are willing to contribute to the development of a glowscript library.   I'll get things started and then pass it off to you, but I'll be willing to help you if you have questions, etc.  Give me a few days, and I'll try to have something we can start working with.

Billy


On Sun, Feb 9, 2014 at 6:24 PM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
Note that there are lots of examples available by clicking on "Example programs" at glowscript.org.

All of the basic graphics primitives are very similar (more similar in fact than the corresponding graphics primitives in VPython). In the Help, read the description of the cylinder object to get a feel for the attributes of these primitives. It is of course true that there's also a sizable number of other things to be accessed, such as the rotate method, controlling the size and background color of the canvas, etc. If you get things started and establish a pattern, it would probably be easy for me to fill in the blanks.

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 9, 2014, 9:18:53 PM2/9/14
to bry...@googlegroups.com
Now that you've produced a concrete example, I understand what you mean by a "GlowScript library", something I thought I'd already created! There does indeed need to be a Brython wrapper of the underlying JavaScript GlowScript library, and its creation may not require much work.

Bruce

Almar Klein

unread,
Feb 10, 2014, 4:34:33 AM2/10/14
to vi...@googlegroups.com, bry...@googlegroups.com
> In terms of visualization we only use numpy as a container of data and it
> should not be too hard to make these part independent of numpy. The parts
> that *do* use numpy for calcualtions are right now limited to calculating
> normals in the mesh reader, I think.

We'll probably start using NumPy more heavily pretty soon with the
transform layer (for CPU transformations). Also, some complex
interactive features for plotting will probably require NumPy.

Good point. Nevertheless, I think it would be interesting to see if we can determine a subset of features that we can support without Numpy, because if we want to someday run Vispy on mobile, we would run into the same problem.

- Almar

Cyrille Rossant

unread,
Feb 10, 2014, 7:35:35 AM2/10/14
to vi...@googlegroups.com, bry...@googlegroups.com
This looks quite interesting: 
 

Kiko

unread,
Feb 10, 2014, 8:05:40 AM2/10/14
to bry...@googlegroups.com, vi...@googlegroups.com
Maybe you just could do all the internal calculations using numpy and then extract the final data as a list or as a json object:

my_ndarray.tolist()

Brython could manage the list or the json file to interact with the webGL API.

Pierre Quentel

unread,
Feb 10, 2014, 11:00:44 AM2/10/14
to bry...@googlegroups.com
I downloaded the files and was amazed to see test2.html work. Great job Billy !

There are a few things to modify in Brython to allow the more natural syntax

_box.rotate(angle=0.01)

I will work on this shortly

I was also pleased to see that the demo uses the centralised version of Brython !


Billy Earney

unread,
Feb 12, 2014, 7:54:15 PM2/12/14
to bry...@googlegroups.com
Bruce, Pierre, etc

Here's a version of the test.html demo, using a python library I developed.   Download and unzip the glowscript.zip file, and run the server.py file to get a local web server running, then goto   http://localhost:8000/test3.html


This should be a good start to show how to develop the library.   Should we make a new bitbucket project for this library, or should be live in some type of 3rd party directory under brython?

Billy



Bruce Sherwood

unread,
Feb 12, 2014, 10:26:02 PM2/12/14
to bry...@googlegroups.com
Looking very promising, Billy. Experimenting in an unsystematic way, I was delighted to see some things Just Work. I have some immediate naive questions.

The file box.py imported by __init__.py enables not only the box object but also lets me set its color in the box constructor (color=color.cyan), but setting opacity has no effect and setting pos leads to no box visible but no error indication. I'm puzzled how the color attribute can work but the pos and opacity attributes don't. Seems like they're on the same footing. Also, I note that while I can set the box color in the constructor I can't change the color later by executing _box.color = color.red.

I don't see where/how the primitives.py module is invoked, yet I can create a cone object (though I can't set its color). Shouldn't we import from something like primitives.py, not from something like box.py?

What you can tell me about these questions may make it easier for me to understand the architecture.

I'll mention that the statements

_gs=glow.glow('glowscript')
_scene=glow.canvas()

are initializations that GlowScript (like VPython) executes if and when the program creates a displayable object such as a box; they aren't statements that appear in user programs. But this is presumably a detail. 

I'll also mention that although it is considered for good reasons to be Bad Practice, especially in sizable projects, we have our novices do inclusive imports to simplify their short programs. At this stage in their development it is more important that all the batteries be included than it is to deal with namespaces. Among the things we import for the novice is the math library, so that one can write cos instead of Math.cos or math.cos. In this context, "scene" is the name of a canvas that is created if the user doesn't create one. Here is a typical VPython or GlowScript version of your program (and it works with your machinery):

from glow import *

glow('glowscript') # initialization; should not be needed here
scene = canvas()   # also should not be needed here

scene.width = scene.height = 400
cube = box(color=color.cyan)

def spin():
    cube.rotate(angle=0.01, axis=vector(0,1,0))
    rate(100, spin)  # make spin a callback 

spin()

I append below output from the Chrome console, which says we're looking for some nonexistent files (yet the rotating box works). 

GET http://localhost:8000/libs/glow.js?v=am3zd4it 404 (File not found) brython_dist.js:5
GET http://localhost:8000//Lib/glow.py?v=hl2el1o3 404 (File not found) brython_dist.js:5
GET http://localhost:8000//libs/glow.py?v=oibjxirc 404 (File not found) brython_dist.js:5
GET http://localhost:8000/glow.py?v=ajc44apg 404 (File not found) brython_dist.js:5
GET http://localhost:8000/Lib/glow.py?v=s4lu28b4 404 (File not found) brython_dist.js:5
imported (browser) via VFS:/Lib/browser/__init__.py brython_dist.js:1299
imported (_browser) via VFS:/libs/_browser.js brython_dist.js:1299
imported (javascript) via VFS:/libs/javascript.js brython_dist.js:1299
imported (urllib) via VFS:/Lib/urllib/__init__.py brython_dist.js:1299
imported (urllib.request) via VFS:/Lib/urllib/request.py brython_dist.js:1299
imported (browser.ajax) via VFS:/Lib/browser/ajax.py brython_dist.js:1299
imported (_ajax) via VFS:/libs/_ajax.js brython_dist.js:1299
1.0 brython_dist.js:5
Uncaught TypeError: Object [object Object] has no method 'log' 

Bruce Sherwood

unread,
Feb 12, 2014, 10:31:00 PM2/12/14
to bry...@googlegroups.com
Seems like it should be either in the Brython repository or the GlowScript repository rather than being a separate project. I personally don't care which. Up to you guys.

Bruce

Billy Earney

unread,
Feb 13, 2014, 8:13:50 AM2/13/14
to bry...@googlegroups.com

The file box.py imported by __init__.py enables not only the box object but also lets me set its color in the box constructor (color=color.cyan), but setting opacity has no effect and setting pos leads to no box visible but no error indication. I'm puzzled how the color attribute can work but the pos and opacity attributes don't. Seems like they're on the same footing. Also, I note that while I can set the box color in the constructor I can't change the color later by executing _box.color = color.red.

This is what is tricky.  Brython has access to javascript objects, but javascript doesn't necessarily have access to brython objects.  That is one reason I had some trouble with the _box.rotate function.  I was passing it an axis variable, but glowscript would choke saying that axis didn't have a norm function.  This is because brython wraps javascript objects.  I had to make a few modifications to brython code so that the javascript object (and not the python object) was being passed to _box.rotate.   This is the reason I think we need to create some type of brython wrapper for each major glowscript library, so these things can be prevented.

After sending you the zip file, I was able to change the color of a box as well, using the glowscript javascript object color, but started to run into issues once I added color to the glow module.  I eventually figured it out, and I can send you a modified version if you like.

 
I don't see where/how the primitives.py module is invoked, yet I can create a cone object (though I can't set its color). Shouldn't we import from something like primitives.py, not from something like box.py?


The primitives module isn't invoked.  I started creating this module when I ran into some issues with box.py, and was waiting for a reply from Pierre.  I decided to not use the primitives in this example, because things are still a little buggy, and I don't want to complicate things further.  I guess now since I have a working example, I could see if the primitives module works.

 
What you can tell me about these questions may make it easier for me to understand the architecture.

I'll mention that the statements

_gs=glow.glow('glowscript')
_scene=glow.canvas()

are initializations that GlowScript (like VPython) executes if and when the program creates a displayable object such as a box; they aren't statements that appear in user programs. But this is presumably a detail. 

I'll also mention that although it is considered for good reasons to be Bad Practice, especially in sizable projects, we have our novices do inclusive imports to simplify their short programs. At this stage in their development it is more important that all the batteries be included than it is to deal with namespaces. Among the things we import for the novice is the math library, so that one can write cos instead of Math.cos or math.cos. In this context, "scene" is the name of a canvas that is created if the user doesn't create one. Here is a typical VPython or GlowScript version of your program (and it works with your machinery):

from glow import *

glow('glowscript') # initialization; should not be needed here
scene = canvas()   # also should not be needed here

scene.width = scene.height = 400
cube = box(color=color.cyan)

def spin():
    cube.rotate(angle=0.01, axis=vector(0,1,0))
    rate(100, spin)  # make spin a callback 

spin()


Good!  I didn't try this, but it doesn't surprise me that it works.   I like using the longer syntax in most cases, so that I know where objects are coming from.  But that is just my preference. :)

 
I append below output from the Chrome console, which says we're looking for some nonexistent files (yet the rotating box works). 


We try to emulate python's import, which searches in different locations for modules to import.  In most cases, you can ignore these. But the log type error below is interesting.

 

Billy Earney

unread,
Feb 13, 2014, 9:58:51 AM2/13/14
to bry...@googlegroups.com

Bruce,

Looking at this a little closer, the reason why the attribute pos didn't work was because of the way I've implemented the vector class.  Currently I'm holding the glowscript js vec object in a variable called _vec.  Currently, for _box.rotate, I'm looking at only the axis variable and resetting it to the _vec variable.  I probably need to cycle through all variables passed in and if they are of instance vector, reset to the instances _vec variable.    I may also talk to Pierre, and see if he has some ideas of how we can more efficiently implement this.  (There could be a better way then what I'm purposing).   I'd like to see the glowscript library behave like a python module, and I'm not sure that is possible unless we wrap each major glowscript object in a python class..

Pierre,  any suggestions?

Billy 


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Pierre Quentel

unread,
Feb 13, 2014, 12:00:27 PM2/13/14
to bry...@googlegroups.com
I'm sorry not to be able to contribute much to this discussion - I'm too busy at work at the moment. I started to work on the problem Billy mentioned about norm(), but I see he solved it exactly as I had before I could push my changeset. Great !

It's always going to be difficult to use, and almost impossible to modify, Python objects in Javascript code. Billy's solution to create intermediate classes to interact with the glowscript library might work, but is it possible to cover all the cases ? I'm not sure either

To avoid the issues with the Javascript glowscript library, I think the best solution would be to write a library in Brython, which brings us to the previous discussion on using VPython code

- Pierre


Billy Earney

unread,
Feb 13, 2014, 12:13:18 PM2/13/14
to bry...@googlegroups.com

Pierre,

Thanks for the response and the verification that I'm probably doing it the (a) correct way..  I didn't want to be off the beaten path, with the direction I was headed.  Its very tempting to just use the javascript objects since brython can access them, but this could cause the problems we have just addressed.   I'll keep moving forward with implementing the glow library, so that some basic functionality is possible before handing it over to Bruce (where I'll play a secondary role). 

Eventually I'll create some type of doc on strategies to use to wrap an existing mature javascript library, so it works with brython.   I guess the main issue I'll need to address in the docs is how to pass objects back and forth between brython and javascript function calls.  This maybe not as difficult as it sounds, and I'll just have to play around with some different ideas, until something seems right to me.   For example, maybe I'll be able to create some type of base class that can be used to help simplify this process.

Thanks!

Billy

Bruce Sherwood

unread,
Feb 13, 2014, 12:21:03 PM2/13/14
to bry...@googlegroups.com
I'm disappointed that Pierre thinks that there may be fundamental problems in using JavaScript libraries, but I'm encouraged that Billy sees the possibility of moving forward.

I had guessed (incorrectly?) that Brython, like Python, would necessarily have mechanisms for fully using libraries written in languages other than Python. For example, in VPython there are intimate connections between Python and C++ through the use of the Boost libraries.

I repeat that using the VPython code base does not sound to me like a viable option, for three reasons. It is almost entirely written in C++, and it does 3D graphics with CPU-side OpenGL whereas in a browser one needs to use GPU-side WebGL. Moreover, a couple years ago someone stepped forward with a pure Python test version of a small subset of VPython, and it was about 50 times slower than VPython, there being a reason why the large core of VPython is in C++.

Billy, I look forward to following your progress. If you can get one or two objects fully working (box and cylinder, say), I'm hopeful that I can then flesh it out, knowing what to test. There isn't a formal test suite for GlowScript or for VPython because what counts is what the display looks like to a human, not what the computations mean to a computer. But as you've seen there is an extensive suite of example programs, whose correct visual behavior is the test of new code.

Bruce

Billy Earney

unread,
Feb 13, 2014, 12:33:57 PM2/13/14
to bry...@googlegroups.com
Bruce,

FYI...  With the simple box example I sent,  the brython version does quite a bit more work (extra function calls, etc) for each call of the spin function.  There might be some work that could be done to reduce the number of function calls, but the brython version will probably never be as fast as the pure javascript implementation.

Billy


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 13, 2014, 12:39:55 PM2/13/14
to bry...@googlegroups.com
I realize that there will be a performance hit, but presumably not a factor of 50. And I expect that the actual graphics rendering will be essentially unaffected, because to render the scene there is one call (implicit in the rate function) to a render function written in JavaScript and GPU shader language, and that function typically takes milliseconds to complete.

Bruce

Billy Earney

unread,
Feb 13, 2014, 12:44:33 PM2/13/14
to bry...@googlegroups.com
I wouldn't expect a factor as high as 50.


On Thu, Feb 13, 2014 at 11:39 AM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
I realize that there will be a performance hit, but presumably not a factor of 50. And I expect that the actual graphics rendering will be essentially unaffected, because to render the scene there is one call (implicit in the rate function) to a render function written in JavaScript and GPU shader language, and that function typically takes milliseconds to complete.

Bruce

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Billy Earney

unread,
Feb 13, 2014, 7:48:03 PM2/13/14
to bry...@googlegroups.com
Bruce,

Enclosed is an updated version of the demo I sent you yesterday.  It uses the primitive library to draw a box, arrow and cylinder, which all rotate on different axis and from different locations.   I'll let you study this for a while.  Feel free to add to it, and if you have any questions, let me know and I'll try to help as much as I can.

Billy

Bruce Sherwood

unread,
Feb 14, 2014, 1:13:10 PM2/14/14
to bry...@googlegroups.com
Great and rapid progress, Billy!

Here is a more extensive example to chew on, a ball bouncing around in a box, modified from


from glow import *

glow('glowscript') # initialization; should not be needed here
scene = canvas()   # also should not be needed here

side = 4.0
thk = 0.3
s2 = 2*side - thk
s3 = 2*side + thk
wallR = box (pos=vec( side, 0, 0), size=vec(thk,s2,s3),  color=color.red)
wallL = box (pos=vec(-side, 0, 0), size=vec(thk,s2,s3),  color=color.red)
wallB = box (pos=vec(0, -side, 0), size=vec(s3,thk,s3),  color=color.blue)
wallT = box (pos=vec(0,  side, 0), size=vec(s3,thk,s3),  color=color.blue)
wallBK = box(pos=vec(0, 0, -side), size=vec(s2,s2,thk), color=color.gray(0.7))

ball = sphere(color=color.green, size=vec(0.8,0.8,0.8))
ball.mass = 1.0
ball.p = vec (-0.15, -0.23, +0.27)
attach_trail(ball, pps=200, retain=100)

side = side - thk*0.5 - ball.size.x/2
dt = 0.3

def move():
  disp = ball.p.multiply(dt/ball.mass)
  ball.pos = ball.pos.add(disp)
  if not (-side < ball.pos.x and ball.pos.x < side):
    ball.p.x = -ball.p.x
  if not (-side < ball.pos.y and ball.pos.y < side):
    ball.p.y = -ball.p.y
  if not (-side < ball.pos.z and ball.pos.z < side):
    ball.p.z = -ball.p.z
  rate(200,move) # execute the move function about 200 times per second
move() # Execute move to start the repetition

------------------------
This example doesn't run, and here are some observations:

Attempts to read the values of attributes of existing objects gives this:

   Uncaught TypeError: Object [object Object] has no method 'log' brython_dist.js:5

Assignments such as object.pos = vec(5,0,0) or object.color = vec(0,1,1) have no effect.

Even if I comment out everything after "ball = sphere(.....)" the sphere doesn't appear (changing to ball = box(...) does make the object appear). If in your own test routine I change cylinder -> sphere, the sphere does appear, but it is white instead of blue, and the rotations don't occur. This is puzzling because in your primitives.py file sphere seems to be treated the same as the other graphics primitives.

I don't think I can contribute much yet until you show me how to read and write the attributes of (say) a box object.

Bruce

Billy Earney

unread,
Feb 14, 2014, 6:23:03 PM2/14/14
to bry...@googlegroups.com
Bruce,

I had not added sphere to the namespace of glow, that is why you got an error.  Also I needed to add a few new statements to get statements such as:

print(_box.pos)
_box.pos=glow.vector(1, 2, 3)

to work properly.

Enclosed is an example, which has an arrow, box, cylinder, and sphere.  The box and sphere are moving, which shows that modifications to pos are taking place.

Enclosed is the updated code that shows these changes.


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 15, 2014, 3:01:36 PM2/15/14
to bry...@googlegroups.com
Thanks for the update. I tried very basic operations and I append what I observe. I haven't yet studied your code to understand the pattern.

<html>
<head>
<script type="text/javascript" src="brython_dist.js"></script>
<script type="text/python">
from glow import *

glow('glowscript') # initialization; should not be needed here
scene = canvas()   # also should not be needed here

b = box(pos=vec(0,0,0), size=vec(.2,2,1), color=color.red, axis=vec(1,1,0), up=vec(0,1,1))
# Trying to set opacity in box constructor gives a WebGL error.
b.pos = vector(-1,0,0) # gives an error if vec(-1,0,0); the GlowScript name is vec, not vector
print(b.pos) # print appears in console.log but should appear in a textArea under graphics canvas
#b.color = color.cyan   # has no effect
#print(b.size)   # this gives an error: TypeError: Object [object Object] has no method 'log' 
#print(b.color) # same
#print(b.axis)  # same
#print(b.up)    # same

</script>
</head>
<body onload="brython({debug:1})">
<div id="glowscript" class="glowscript"></div>
</body>
</html>

Bruce Sherwood

unread,
Feb 15, 2014, 3:42:23 PM2/15/14
to bry...@googlegroups.com
I worked through the minor problems and attach the modified files. I append a program that shows almost all of the basics working. 

Two puzzles: Despite the fact that the code looks like that for other attributes, trying to specify opacity gives a WebGL error, and trying to print the size attribute gives an error. I'll need to create a color interface module, because color.cyan isn't recognized as being of type vec. 

I'm guessing that "print" is invoking a Brython print statement, which goes to console.log, whereas GlowScript has a print function (whose syntax and capabilities are those of the Python print function) that creates a scrolling textArea object placed under the graphics canvas.

<html>
<head>
<script type="text/javascript" src="brython_dist.js"></script>

<script type="text/python">
from glow import *

glow('glowscript') # initialization; should not be needed here
scene = canvas()   # also should not be needed here

b = box(pos=vec(0,0,0), size=vec(.2,2,1), color=color.red, axis=vec(1,1,0), up=vec(0,1,-1))
# Trying to set opacity inside or outside box constructor gives a WebGL error.
b.pos = vec(-1,0,0)
print(b.pos) # print appears in console.log but should appear in textArea under graphics canvas
#b.color = color.cyan   # complains that color must be a vec; need color module (like vec module)
b.color = vec(0,1,1)    # this works; color changes to cyan
#print(b.size) # gives an error despite the code being similar to other attributes
print(b.color)
print(b.axis)
print(b.up)
vector.py
__init__.py
primitive.py

Francois Dion

unread,
Feb 15, 2014, 4:10:54 PM2/15/14
to bry...@googlegroups.com
Bruce,

print can be made to print to a text area by assigning sys.stdout.write (and stderr too if you want) to a write function that will put the text in the element of your choice. for example:

import sys

def write(data):
    doc['textarea'].value += data

sys.stdout.write = sys.stderr.write = write

Francois


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 15, 2014, 6:37:10 PM2/15/14
to bry...@googlegroups.com
Thanks for the tip, Francois, but what I want to do is to invoke the print function in the GlowScript library rather than the print function in the Brython library. The first call to the GlowScript print statement creates the textarea element.

Bruce


--
You received this message because you are subscribed to a topic in the Google Groups "brython" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/brython/p2oz_BK1_3A/unsubscribe.
To unsubscribe from this group and all its topics, send an email to brython+u...@googlegroups.com.

To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 15, 2014, 7:57:12 PM2/15/14
to bry...@googlegroups.com
Here's something strange that suggests that the toString mechanism has a problem with non-integer values:

v1 = vec(10, 20, 30)
print(v1) # okay
v2 = vec(10.1, 20, 30)
print(v2) # gives this error:

Error: Object [object Object] has no method 'toPrecision'
  module 'vector' line 48
      return self._vec.toString()
default to toString [object Object] brython_dist.js:5
[object Object]

Bruce Sherwood

unread,
Feb 15, 2014, 10:35:14 PM2/15/14
to bry...@googlegroups.com
Lots of progress. I attach an update to vector.py and a standard GlowScript bouncing ball demo now using Brython. The original bouncing ball program written in JavaScript is here:


The attached program lacks the trail that is to be left behind the moving ball, because the attach_trail function fails. I'm guessing it's not a big problem. Also, the Brython program is noticeably slower than the JavaScript program, but it's nevertheless usable.

Bruce

vector.py
bounce.html

Billy Earney

unread,
Feb 16, 2014, 10:09:01 AM2/16/14
to bry...@googlegroups.com
Bruce,

Great job!  I think I'll have some time today to look into this.


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 16, 2014, 10:21:14 AM2/16/14
to bry...@googlegroups.com
Many thanks to you, Billy, for kickstarting this.

Here's a specific question. The attach_trail function expects to be called in one of the following ways in the JavaScript context, where "ball" is a graphics primitive such as a sphere:

attach_trail(ball)
attach_trail(ball, {radius:0.1, color:color.white, retain:30, pps:5, type:'spheres'})
attach_trail(some_function)
attach_trail(function(){return 2*ball.pos})

For starters let's just try to implement the first two versions. I assume that in Brython they would look like this (where the multiple named arguments are each optional, of course):

attach_trail(ball)
attach_trail(ball, radius=0.1, color=color.white, retain=30, pps=5, type='spheres')

What does the Brython wrapper function have to look like?

Bruce

Billy Earney

unread,
Feb 16, 2014, 11:28:29 AM2/16/14
to bry...@googlegroups.com
Bruce,

I've made some adjustments to get rid of some of the warnings, etc.  (like the log issue). I was not getting the log error because I was going an import glow, instead of  from glow import *.  I figured this issue by commenting out the  #console import in __init__.py.

I also changed references of vector to vec since you make this change to class vector.    I added in the __add__, __sub__, __mul__ and __div__ so that operator overloading can occur (you've shown interest in this, so that i why I've implemented vector the way I did).  

I've modified bounce.html so that it demonstrates operator overloading..    The output graphics where performing slowly until I closed the javascript/developer window.  If you have yours open, you might want to close it.

You can see those changes in the enclosed attachments.


--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 16, 2014, 12:18:35 PM2/16/14
to bry...@googlegroups.com
Wow! I'm totally impressed, Billy.

I'm utterly mystified as to how the operator overloading Just Works. After compiling to JavaScript, what is in the generated JavaScript that enables vector addition A+B to take place? How does this work? I'll comment that the way David Scherer implemented vector operator overloading in GlowScript was essentially to turn (say) "x+y" into "add(x,y)". Since this is done for all variables, whether vectors or not, it slows down execution, and there's a special directive to turn this off in a function if full speed is required.

Thanks much for pointing out that having the browser console open slowed down the execution. And thanks for getting rid of the log error.

There's probably a host of small issues, most of which I should be able to deal with thanks to the foundation you've provided, but there remains one other distinctive feature of GlowScript, which is the ability to write synchronous code and yet have the screen regularly updated. Here's an example:

while True:
    rate(100,wait)
    ball.pos.x += .01

The way GlowScript achieves this capability, implemented by David Scherer, is to use the Streamline library (https://github.com/Sage/streamlinejs). The keyword "wait" is used by Streamline to move the loop contents into a separate function that is then driven by an interval timer based on the first rate argument. I'm assuming that I'll need to capture the JavaScript code generated by Brython and pass it through Streamline. Is there a way to access your JavaScript output?

Bruce

Bruce Sherwood

unread,
Feb 16, 2014, 12:58:27 PM2/16/14
to bry...@googlegroups.com
Billy, please update your primitives.py file to the one I sent a few messages ago. It contains important changes. As a convenience, I attach it again.

Bruce

primitive.py

Billy Earney

unread,
Feb 16, 2014, 6:18:51 PM2/16/14
to bry...@googlegroups.com
Bruce,

Sorry, I must have overlooked the primitive.py attachment before.  I'll  modify my source.   I'll need to look further into the "wait" issue, and do some experimentation to see what works.  I'm not sure this is 100% doable, but I'd like to do something similar to this in brython, so both projects could benefit from this.

The operator overloading implementation is complicated, and I'm not sure how easy this will be to implement for javascript.

To show a simple example,  I'm going to: http://brython.info/tests/editor.html

and typing in the following example:


class myclass:
  def __init__(self, value):
      self._value=value
     
  def __add__(self, other):
      return self._value + other._value
     
myvar1 = myclass(5)
myvar2 = myclass(6)

print(myvar1+myvar2)

Brython parses this code and produces the following javascript (note this is not "pure javascript" and requires the brython library). (Note, it maybe easier to create a script to parse your code, and keep track of the vector variables, and only modify those +-*/).

var $globals = __BRYTHON__.scope["__main__"].__dict__
var $locals = $globals
var __builtins__ = __BRYTHON__.builtins;
for(var $py_builtin in __builtins__){eval("var "+$py_builtin+"=__builtins__[$py_builtin]")}

var __doc__=$globals["__doc__"]=""
var __name__=$globals["__name__"]="__main__"
var __file__=$globals["__file__"]="http://brython.info/tests/editor.html"
__BRYTHON__.line_info=[1,"__main__"];None;
var $myclass=(function(){
    var $class = {$def_line:__BRYTHON__.line_info}
    __BRYTHON__.line_info=[2,"__main__"];None;
    $class.__init__= (function (){
        var $defaults = {}
        return function(){
            try{
                var $locals = __BRYTHON__.scope["1ta7bahg"].__dict__={}
                for(var $var in $defaults){eval("var "+$var+"=$locals[$var]=$defaults[$var]")}
                var $ns=__BRYTHON__.$MakeArgs("__init__",arguments,["self","value"],[],null,null,[])
                for(var $var in $ns){eval("var "+$var+"=$ns[$var]");$locals[$var]=$ns[$var]}
                __BRYTHON__.line_info=[3,"__main__"];None;
                setattr(self,"_value",value);None;
            }
            catch(err8){throw __BRYTHON__.exception(err8)}
        }
    }
    )()
    $class.__init__.__name__="__init__"
    $class.__init__.__module__ = "__main__"
    $class.__init__.__doc__=""
    $class.__init__.__code__= {__class__:__BRYTHON__.$CodeDict};None;
    __BRYTHON__.line_info=[5,"__main__"];None;
    $class.__add__= (function (){
        var $defaults = {}
        return function(){
            try{
                var $locals = __BRYTHON__.scope["4ev3uusj"].__dict__={}
                for(var $var in $defaults){eval("var "+$var+"=$locals[$var]=$defaults[$var]")}
                var $ns=__BRYTHON__.$MakeArgs("__add__",arguments,["self","other"],[],null,null,[])
                for(var $var in $ns){eval("var "+$var+"=$ns[$var]");$locals[$var]=$ns[$var]}
                __BRYTHON__.line_info=[6,"__main__"];None;
                return getattr(getattr(self,"_value"),"__add__")(getattr(other,"_value"))
            }
            catch(err8){throw __BRYTHON__.exception(err8)}
        }
    }
    )()
    $class.__add__.__name__="__add__"
    $class.__add__.__module__ = "__main__"
    $class.__add__.__doc__=""
    $class.__add__.__code__= {__class__:__BRYTHON__.$CodeDict};None;
    return $class
}
)()
$myclass.__doc__=""
$myclass.__module__="__main__"
var myclass=__BRYTHON__.$class_constructor("myclass",$myclass,tuple([]),[],[])
__BRYTHON__.scope["__main__"].__dict__["myclass"]=myclass
None;
__BRYTHON__.line_info=[8,"__main__"];None;
var myvar1=$globals["myvar1"]=getattr(myclass,"__call__")(Number(5));None;
__BRYTHON__.line_info=[9,"__main__"];None;
var myvar2=$globals["myvar2"]=getattr(myclass,"__call__")(Number(6));None;
__BRYTHON__.line_info=[11,"__main__"];None;
getattr($print,"__call__")(getattr(myvar1,"__add__")(myvar2))








On Sun, Feb 16, 2014 at 11:58 AM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
Billy, please update your primitives.py file to the one I sent a few messages ago. It contains important changes. As a convenience, I attach it again.

Bruce

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Billy Earney

unread,
Feb 16, 2014, 9:32:04 PM2/16/14
to bry...@googlegroups.com
Bruce,

I ran into http://esprima.org/  . This could help you with the vector overloading issue in javascript.

Billy

Bruce Sherwood

unread,
Feb 17, 2014, 12:03:07 AM2/17/14
to bry...@googlegroups.com
I don't understand. What if variables X and Y are assigned their type based on user input or a random number? How can the correct "+" operator be invoked? I realize these might be uncommon cases, but I don't see how to rule out such situations.

Bruce

Bruce Sherwood

unread,
Feb 17, 2014, 1:18:55 AM2/17/14
to bry...@googlegroups.com
Hmm. Maybe one could look for any variable name to which (in this case) a vector is assigned and assume it stays that way, but instead of sending x+y to a vector addition routine, send it to an "add" routine that would look at the types of both operands and decide what to do, which is currently done for all x+y sums in GlowScript, so limiting this to operands that somewhere in the program are assigned vector values would speed things up.

Bruce

Bruce Sherwood

unread,
Feb 17, 2014, 1:48:43 AM2/17/14
to bry...@googlegroups.com
Here's a tweaked "bounce.html" file that not only shows the ball bouncing around in the box but also displays instructions for how to rotate and zoom the camera.

Bruce

bounce.html

Bruce Sherwood

unread,
Feb 17, 2014, 10:38:46 AM2/17/14
to bry...@googlegroups.com
Minor issues:

At least on my Windows machine, the bounce program doesn't run on Firefox or IE (there's something wrong in general with GlowScript on IE); runs fine on Chrome.

The console shows a bunch of files not found:

Failed to load resource: the server responded with a status of 404 (File not found) http://localhost:8000/libs/glow.js?v=a7ljlndh
Failed to load resource: the server responded with a status of 404 (File not found) http://localhost:8000//Lib/glow.py?v=e329624t
Failed to load resource: the server responded with a status of 404 (File not found) http://localhost:8000//libs/glow.py?v=6bnjr48o
Failed to load resource: the server responded with a status of 404 (File not found) http://localhost:8000/glow.py?v=qsm0cpgd
Failed to load resource: the server responded with a status of 404 (File not found) http://localhost:8000/Lib/glow.py?v=glpf2xrh


Billy, you pointed out correctly that performance is much better if the browser console isn't open. I don't see this behavior in the standard GlowScript environment, and I don't see any output in the console after start up, so why does the console being open affect anything?

Bruce

Billy Earney

unread,
Feb 17, 2014, 10:46:29 AM2/17/14
to bry...@googlegroups.com
Bruce,

When you open the developer tools in firefox you get the following warning on the console tab:

Warning:
Enabling the Script panel causes a Firefox slow-down due to a platform bug. This will be fixed with the next major Firefox and Firebug versions.

In this message is a link that points to https://bugzilla.mozilla.org/show_bug.cgi?id=815603

This bug is just for firefox where I see a major slowdown.  Chrome slows down too, but not as much as FF.

Opening the javascript/developer tools, produces a slowdown in many javascript applications (not just brython or glowscript), so this is a behavior with javascript and browsers in general.  You could probably find more information by doing a google search.

So if I read your message correctly, glowscript doesn't work with IE?   If so, for now, I should just focus on Firefox issues with brython and glow?

Billy




--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.

Bruce Sherwood

unread,
Feb 17, 2014, 10:53:00 AM2/17/14
to bry...@googlegroups.com
Yes, it's Firefox that's the interesting case. Only recently did IE start supporting WebGL, and GlowScript worked; then some change took place such that GlowScript no longer works in IE even though I can run other WebGL-based applications in IE, which is puzzling.

I should have said that the performance issue with the console was in Chrome, which is the browser I normally use. In Chrome I've never seen a slowdown associated with opening the console except with our Brython/GlowScript application, where the slowdown I see is quite large. This is on Windows.

Bruce

Bruce Sherwood

unread,
Feb 17, 2014, 11:59:29 AM2/17/14
to bry...@googlegroups.com
Billy, getting the GlowScript curve object working (http://www.glowscript.org/docs/GlowScriptDocs/curve.html) looks maybe a bit challenging; I don't think I can do it myself because it isn't simply a matter of copying the wrappers you've already implemented. Note that for adding points to the curve it uses the JavaScript "push" method rather than the Python "append" method. Not clear to me whether the end user should say _curve.push or _curve.append. In any case, neither of these work currently. The curve object is important in particular for leaving trails behind a moving object.

Bruce

Billy Earney

unread,
Feb 17, 2014, 12:48:49 PM2/17/14
to bry...@googlegroups.com
okay.  I'll look into this later today.

Billy


On Mon, Feb 17, 2014 at 10:59 AM, Bruce Sherwood <bruce.s...@gmail.com> wrote:
Billy, getting the GlowScript curve object working (http://www.glowscript.org/docs/GlowScriptDocs/curve.html) looks maybe a bit challenging; I don't think I can do it myself because it isn't simply a matter of copying the wrappers you've already implemented. Note that for adding points to the curve it uses the JavaScript "push" method rather than the Python "append" method. Not clear to me whether the end user should say _curve.push or _curve.append. In any case, neither of these work currently. The curve object is important in particular for leaving trails behind a moving object.

Bruce

--
You received this message because you are subscribed to the Google Groups "brython" group.
To unsubscribe from this group and stop receiving emails from it, send an email to brython+u...@googlegroups.com.
To post to this group, send email to bry...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages