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 alien.data ;
6 FROM: sequences => change-nth ;
7 QUALIFIED-WITH: alien.c-types c
8 SPECIALIZED-ARRAY: c:float
9 SPECIALIZED-ARRAY: c:uint
12 : numbers ( str -- seq )
13 " " split [ string>number ] map sift ;
15 : (parse-model) ( vs is -- vs is )
18 { [ dup length 5 = ] [ 3 head pick push ] }
19 { [ dup first 3 = ] [ rest over push ] }
24 : parse-model ( -- vs is )
25 100000 <vector> 100000 <vector> (parse-model) ;
27 : n ( vs triple -- n )
28 swap [ nth ] curry map
29 [ [ second ] [ first ] bi v- ] [ [ third ] [ first ] bi v- ] bi cross
32 : normal ( ns vs triple -- )
33 [ n ] keep [ rot [ v+ ] change-nth ] 2with each ;
35 : normals ( vs is -- ns )
36 [ [ length { 0.0 0.0 0.0 } <array> ] keep ] dip
37 [ [ 2dup ] dip normal ] each drop
40 : read-model ( stream -- model )
41 ascii [ parse-model ] with-file-reader
42 [ normals ] 2keep 3array ;
44 : model-path ( -- path ) "bun_zipper.ply" cache-file ;
46 CONSTANT: model-url "http://duriansoftware.com/joe/media/bun_zipper.ply"
48 : download-bunny ( -- path )
49 model-url model-path [ ?download-to ] keep ;
51 :: (draw-triangle) ( ns vs triple -- )
57 : draw-triangles ( ns vs is -- )
58 GL_TRIANGLES [ [ (draw-triangle) ] 2with each ] do-state ;
60 TUPLE: bunny-dlist list ;
61 TUPLE: bunny-buffers array element-array nv ni ;
63 : <bunny-dlist> ( model -- geom )
64 GL_COMPILE [ first3 draw-triangles ] make-dlist
67 : <bunny-buffers> ( model -- geom )
70 [ first concat ] [ second concat ] bi
71 append c:float >c-array underlying>>
72 GL_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
75 third concat c:uint >c-array underlying>>
76 GL_ELEMENT_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
80 } cleave bunny-buffers boa ;
82 GENERIC: bunny-geom ( geom -- )
83 GENERIC: draw-bunny ( geom draw -- )
85 M: bunny-dlist bunny-geom
88 M: bunny-buffers bunny-geom
89 dup [ array>> ] [ element-array>> ] bi [
90 { GL_VERTEX_ARRAY GL_NORMAL_ARRAY } [
91 GL_FLOAT 0 0 buffer-offset glNormalPointer
93 nv>> c:float heap-size * buffer-offset
94 [ 3 GL_FLOAT 0 ] dip glVertexPointer
97 GL_TRIANGLES swap GL_UNSIGNED_INT 0 buffer-offset glDrawElements
99 ] all-enabled-client-state
100 ] with-array-element-buffers ;
102 M: bunny-dlist dispose
103 list>> delete-dlist ;
105 M: bunny-buffers dispose
106 [ array>> ] [ element-array>> ] bi
107 delete-gl-buffer delete-gl-buffer ;
109 : <bunny-geom> ( model -- geom )
110 "1.5" { "GL_ARB_vertex_buffer_object" }
111 has-gl-version-or-extensions?
112 [ <bunny-buffers> ] [ <bunny-dlist> ] if ;