1 USING: accessors alien.c-types arrays combinators destructors
2 http.client io io.encodings.ascii io.files io.files.temp kernel
3 locals math math.matrices math.parser math.vectors opengl
4 opengl.capabilities opengl.gl opengl.demo-support sequences
5 splitting vectors words specialized-arrays ;
6 QUALIFIED-WITH: alien.c-types c
7 SPECIALIZED-ARRAY: c:float
8 SPECIALIZED-ARRAY: c:uint
11 : numbers ( str -- seq )
12 " " split [ string>number ] map sift ;
14 : (parse-model) ( vs is -- vs is )
17 { [ dup length 5 = ] [ 3 head pick push ] }
18 { [ dup first 3 = ] [ rest over push ] }
23 : parse-model ( -- vs is )
24 100000 <vector> 100000 <vector> (parse-model) ;
26 : n ( vs triple -- n )
27 swap [ nth ] curry map
28 [ [ second ] [ first ] bi v- ] [ [ third ] [ first ] bi v- ] bi cross
31 : normal ( ns vs triple -- )
32 [ n ] keep [ rot [ v+ ] change-nth ] with with each ;
34 : normals ( vs is -- ns )
35 [ [ length { 0.0 0.0 0.0 } <array> ] keep ] dip
36 [ [ 2dup ] dip normal ] each drop
39 : read-model ( stream -- model )
40 ascii [ parse-model ] with-file-reader
41 [ normals ] 2keep 3array ;
43 : model-path ( -- path ) "bun_zipper.ply" temp-file ;
45 : model-url ( -- url ) "http://factorcode.org/bun_zipper.ply" ;
47 : maybe-download ( -- path )
48 model-path dup exists? [
49 "Downloading bunny from " write
50 model-url dup print flush
54 :: (draw-triangle) ( ns vs triple -- )
60 : draw-triangles ( ns vs is -- )
61 GL_TRIANGLES [ [ (draw-triangle) ] with with each ] do-state ;
63 TUPLE: bunny-dlist list ;
64 TUPLE: bunny-buffers array element-array nv ni ;
66 : <bunny-dlist> ( model -- geom )
67 GL_COMPILE [ first3 draw-triangles ] make-dlist
70 : <bunny-buffers> ( model -- geom )
73 [ first concat ] [ second concat ] bi
74 append >float-array underlying>>
75 GL_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
78 third concat >uint-array underlying>>
79 GL_ELEMENT_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
83 } cleave bunny-buffers boa ;
85 GENERIC: bunny-geom ( geom -- )
86 GENERIC: draw-bunny ( geom draw -- )
88 M: bunny-dlist bunny-geom
91 M: bunny-buffers bunny-geom
92 dup [ array>> ] [ element-array>> ] bi [
93 { GL_VERTEX_ARRAY GL_NORMAL_ARRAY } [
94 GL_FLOAT 0 0 buffer-offset glNormalPointer
96 nv>> c:float heap-size * buffer-offset
97 [ 3 GL_FLOAT 0 ] dip glVertexPointer
100 GL_TRIANGLES swap GL_UNSIGNED_INT 0 buffer-offset glDrawElements
102 ] all-enabled-client-state
103 ] with-array-element-buffers ;
105 M: bunny-dlist dispose
106 list>> delete-dlist ;
108 M: bunny-buffers dispose
109 [ array>> ] [ element-array>> ] bi
110 delete-gl-buffer delete-gl-buffer ;
112 : <bunny-geom> ( model -- geom )
113 "1.5" { "GL_ARB_vertex_buffer_object" }
114 has-gl-version-or-extensions?
115 [ <bunny-buffers> ] [ <bunny-dlist> ] if ;