1 USING: accessors alien.c-types arrays combinators destructors
2 http.client io io.encodings.ascii io.files kernel math
3 math.matrices math.parser math.vectors opengl
4 opengl.capabilities opengl.gl opengl.demo-support sequences
5 sequences.lib splitting vectors words
6 specialized-arrays.float specialized-arrays.uint ;
9 : numbers ( str -- seq )
10 " " split [ string>number ] map sift ;
12 : (parse-model) ( vs is -- vs is )
15 { [ dup length 5 = ] [ 3 head pick push ] }
16 { [ dup first 3 = ] [ rest over push ] }
21 : parse-model ( -- vs is )
22 100000 <vector> 100000 <vector> (parse-model) ;
24 : n ( vs triple -- n )
25 swap [ nth ] curry map
26 dup third over first v- >r dup second swap first v- r> cross
29 : normal ( ns vs triple -- )
30 [ n ] keep [ rot [ v+ ] change-nth ] each-with2 ;
32 : normals ( vs is -- ns )
33 over length { 0.0 0.0 0.0 } <array> -rot
34 [ >r 2dup r> normal ] each drop
37 : read-model ( stream -- model )
38 ascii [ parse-model ] with-file-reader
39 [ normals ] 2keep 3array ;
41 : model-path ( -- path ) "bun_zipper.ply" temp-file ;
43 : model-url ( -- url ) "http://factorcode.org/bun_zipper.ply" ;
45 : maybe-download ( -- path )
46 model-path dup exists? [
47 "Downloading bunny from " write
48 model-url dup print flush
52 : (draw-triangle) ( ns vs triple -- )
53 [ dup roll nth gl-normal swap nth gl-vertex ] each-with2 ;
55 : draw-triangles ( ns vs is -- )
56 GL_TRIANGLES [ [ (draw-triangle) ] each-with2 ] do-state ;
58 TUPLE: bunny-dlist list ;
59 TUPLE: bunny-buffers array element-array nv ni ;
61 : <bunny-dlist> ( model -- geom )
62 GL_COMPILE [ first3 draw-triangles ] make-dlist
65 : <bunny-buffers> ( model -- geom )
68 [ first concat ] [ second concat ] bi
69 append >float-array underlying>>
70 GL_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
73 third concat >uint-array underlying>>
74 GL_ELEMENT_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
78 } cleave bunny-buffers boa ;
80 GENERIC: bunny-geom ( geom -- )
81 GENERIC: draw-bunny ( geom draw -- )
83 M: bunny-dlist bunny-geom
86 M: bunny-buffers bunny-geom
87 dup [ array>> ] [ element-array>> ] bi [
88 { GL_VERTEX_ARRAY GL_NORMAL_ARRAY } [
89 GL_FLOAT 0 0 buffer-offset glNormalPointer
91 nv>> "float" heap-size * buffer-offset
92 3 GL_FLOAT 0 roll glVertexPointer
95 GL_TRIANGLES swap GL_UNSIGNED_INT 0 buffer-offset glDrawElements
97 ] all-enabled-client-state
98 ] with-array-element-buffers ;
100 M: bunny-dlist dispose
101 list>> delete-dlist ;
103 M: bunny-buffers dispose
104 [ array>> ] [ element-array>> ] bi
105 delete-gl-buffer delete-gl-buffer ;
107 : <bunny-geom> ( model -- geom )
108 "1.5" { "GL_ARB_vertex_buffer_object" }
109 has-gl-version-or-extensions?
110 [ <bunny-buffers> ] [ <bunny-dlist> ] if ;