text
stringlengths
0
601k
let view_collapse st ( ) = match st . tree_widget with Some tw -> | None -> ( ) ; ;
let init_application top = let directory_xpm = Imagebitmap . create ~ file " : directory . xpm " ~ background ` : White ( ) in let selected_xpm = Imagebitmap . create ~ file " : selected . xpm " ~ background ` : White ( ) in let unselected_xpm = Imagebitmap . create ~ file " : unselected . xpm " ~ background ` : White ( ) in let workframe = Frame . create ~ width : 400 ~ height : 600 top in let st = { current_directory = Sys . getcwd ( ) ; list_file = " " ; tree_widget = None ; info_widget = None ; dir_context_menu = None ; dir_context_suffix_menu = None ; dir_context_unsuffix_menu = None ; file_context_menu = None ; context_menu_tree = dummy_tree ; modified = false ; workframe = workframe ; topwdg = top ; directory_xpm = directory_xpm ; selected_xpm = selected_xpm ; unselected_xpm = unselected_xpm ; display = ( fun _ _ -> Lx_tree . display_text " " ) ; } in st . display <- display_node st ; let menuframe = Frame . create ~ relief ` : Groove ~ borderwidth : 2 top in let file_mb = Menubutton . create ~ text " : File " menuframe in let file_m = Menu . create file_mb in Menu . add_command ~ label " : New Tree " ~ command ( : file_new st ) file_m ; Menu . add_command ~ label " : Open " ~ command ( : file_open st ) file_m ; Menu . add_command ~ label " : Check " file_m ; Menu . add_command ~ label " : Save " ~ command ( : file_save st ) file_m ; Menu . add_command ~ label " : Quit " ~ command ( : file_quit st ) file_m ; Menubutton . configure ~ menu : file_m file_mb ; Wm . protocol_set top ~ name " : WM_DELETE_WINDOW " ~ command ( : file_quit st ) ; Menu . add_command ~ label " : Select by suffix " edit_m ; Menu . add_command ~ label " : Select by regexp " edit_m ; Menu . add_command ~ label " : Select all " edit_m ; Menubutton . configure ~ menu : edit_m edit_mb ; ) * let view_mb = Menubutton . create ~ text " : View " menuframe in let view_m = Menu . create view_mb in Menu . add_command ~ label " : Expand all " ~ command ( : view_expand ~ all : true st ) view_m ; Menu . add_command ~ label " : Expand as needed " ~ command ( : view_expand st ) view_m ; Menu . add_command ~ label " : Collapse all " ~ command ( : view_collapse st ) view_m ; Menubutton . configure ~ menu : view_m view_mb ; pack ~ side ` : Left [ file_mb ; view_mb ] ; pack ~ anchor ` : W ~ fill ` : X [ menuframe ] ; pack ~ anchor ` : W [ workframe ] ; ;
let top_window = openTk ( ) in try mainLoop ( ) with Sys . Break -> prerr_endline " EXIT " ; ( ) ; ;
type ts_point = Tree_sitter_output_t . position = { row : int ; column : int ; }
module Parser = struct type t = ts_parser external parse_string : ts_parser -> string -> ts_tree = " octs_parser_parse_string " type read_function = int -> int -> int -> string option external parse : ts_parser -> ts_tree option -> read_function -> ts_tree = " octs_parser_parse " let parse_read_function = ( ref ( fun _ _ _ -> None ) : read_function ref ) let parse_read ( byte_offset : int ) ( row : int ) ( col : int ) = ! parse_read_function byte_offset row col let parse ( parser : t ) ( tree : ts_tree option ) read_function = parse_read_function := read_function ; parse parser tree parse_read let ( ) = Callback . register " octs__parse_read " parse_read end
module Tree = struct type t = ts_tree external root_node : ts_tree -> ts_node = " octs_tree_root_node " external edit : ts_tree -> int -> int -> int -> int -> int -> int -> ts_tree = " octs_tree_edit_bytecode " " octs_tree_edit_native " external delete : ts_tree -> unit = " octs_tree_delete " end
module Point = struct type t = ts_point end
module Node = struct external string : ts_node -> string = " octs_node_string " external child_count : ts_node -> int = " octs_node_child_count " external child : ts_node -> int -> ts_node = " octs_node_child " external parent : ts_node -> ts_node = " octs_node_parent " external named_child_count : ts_node -> int = " octs_node_named_child_count " external named_child : ts_node -> int -> ts_node = " octs_node_named_child " external bounded_named_index : ts_node -> int = " octs_node_bounded_named_index " external named_index : ts_node -> int = " octs_node_named_index " external index : ts_node -> int = " octs_node_index " external descendant_for_point_range : ts_node -> int -> int -> int -> int -> ts_node = " octs_node_descendant_for_point_range " external start_byte : ts_node -> int = " octs_node_start_byte " external end_byte : ts_node -> int = " octs_node_end_byte " external start_point : ts_node -> ts_point = " octs_node_start_point " external end_point : ts_node -> ts_point = " octs_node_end_point " external has_changes : ts_node -> bool = " octs_node_has_changes " external has_error : ts_node -> bool = " octs_node_has_error " external is_missing : ts_node -> bool = " octs_node_is_missing " external is_null : ts_node -> bool = " octs_node_is_null " external is_named : ts_node -> bool = " octs_node_is_named " external is_error : ts_node -> bool = " octs_node_is_error " external is_extra : ts_node -> bool = " octs_node_is_extra " external symbol : ts_node -> int = " octs_node_symbol " external type_ : ts_node -> string = " octs_node_type " end
type error_class = { parent : node_kind ; left_sibling : node_kind option ; first_child : node_kind option ; }
type t = { kind : Tree_sitter_error_t . error_kind ; msg : string ; file : Src_file . info ; start_pos : position ; end_pos : position ; substring : string ; snippet : Snippet . t ; error_class : error_class option ; }
let string_of_node_kind ( x : node_kind ) = match x with | Literal s -> sprintf " % S " s | Name s -> s | Error -> " ERROR "
let string_of_node ( x : node ) = let node_kind = string_of_node_kind x . kind in match x . children with | None -> sprintf " node type : % s " node_kind | Some children -> sprintf " \ % s ] " node_kind ( List . map ( fun ( x : node ) -> sprintf " % s \ n " ( string_of_node_kind x . kind ) ) children |> String . concat " " )
let string_of_error_class ( x : error_class ) = let parent = sprintf " parent : % s " ( string_of_node_kind x . parent ) in let left_sibling = match x . left_sibling with | None -> " , no left sibling " | Some x -> sprintf " , left sibling : % s " ( string_of_node_kind x ) in let first_child = match x . first_child with | None -> " , no children " | Some x -> sprintf " , first child : % s " ( string_of_node_kind x ) in parent ^ left_sibling ^ first_child
let rec find_left_sibling ( children : node list ) target_node = match children with | left :: node :: _ when node == target_node -> Some left . kind | node :: _ when node == target_node -> None | _ :: xs -> find_left_sibling xs target_node | [ ] -> assert false
let error_class_of_node ( ~ parent : node option ) node = match parent with | None -> None | Some { children = None ; _ } -> assert false | Some { kind ; children = Some children ; _ } -> let left_sibling = find_left_sibling children node in let first_child = match node . children with | None | Some [ ] -> None | Some ( x :: _ ) -> Some x . kind in Some { parent = kind ; left_sibling ; first_child ; }
let create kind src ? parent node msg = let msg = sprintf " \ % s % s " ( string_of_node node ) msg in let start_pos = node . start_pos in let end_pos = node . end_pos in { kind ; msg ; file = Src_file . info src ; start_pos ; end_pos ; substring = Src_file . get_region src start_pos end_pos ; snippet = Snippet . extract src ~ start_pos ~ end_pos ; error_class = error_class_of_node ~ parent node ; }
let fail kind src node msg = raise ( Error ( create kind src node msg ) )
let external_error src node msg = fail External src node msg
let internal_error src node msg = fail Internal src node msg
let string_of_file_info ( src_info : Src_file . info ) = match src_info . path with | Some path -> sprintf " File % s " path | None -> src_info . name
let to_string ( ? color = false ) ( err : t ) = let start = err . start_pos in let end_ = err . end_pos in let loc = let src_name = string_of_file_info err . file in if start . row = end_ . row then sprintf " % s , line % i , characters % i -% i " : src_name ( start . row + 1 ) start . column end_ . column else sprintf " % s , line % i , character % i to line % i , character % i " : src_name ( start . row + 1 ) start . column ( end_ . row + 1 ) end_ . column in let error_class = match err . error_class with | None -> " " | Some x -> sprintf " % s \ n " ( string_of_error_class x ) in sprintf " \ % s % s % s % s " loc ( Snippet . format ~ color err . snippet ) error_class err . msg
let to_json_error ( x : t ) : Tree_sitter_error_t . json_error = { kind = x . kind ; msg = x . msg ; file = x . file . name ; start_pos = x . start_pos ; end_pos = x . end_pos ; substring = x . substring ; error_class = Option . map string_of_error_class x . error_class ; }
let log_json_errors out_file errors = let oc = open_out_gen [ Open_creat ; Open_text ; Open_append ] 0o666 out_file in Fun . protect ~ finally ( : fun ( ) -> close_out_noerr oc ) ( fun ( ) -> List . iter ( fun err -> let simplified_err = to_json_error err in let json = Tree_sitter_error_j . string_of_json_error simplified_err in fprintf oc " % s \ n " json ) errors )
let rec of_ts_node get_node_id ts_node = let id = get_node_id ( ) in let type_ = Node . type_ ts_node in let start_pos = Node . start_point ts_node in let end_pos = Node . end_point ts_node in let children = read_children get_node_id ts_node in let kind = match type_ with | " ERROR " -> Error | _ -> match children with | None -> Literal type_ | Some _ -> Name type_ in { type_ ; start_pos ; end_pos ; children ; kind ; id ; } if Node . is_named ts_node then match Node . child_count ts_node with | 0 -> Some [ ] | child_count -> Some ( List . init child_count ( fun i -> of_ts_node get_node_id ( Node . child ts_node i ) ) ) else None
let of_ts_tree ts_tree = let root = Tree . root_node ts_tree in let counter = ref ( - 1 ) in let get_node_id ( ) = incr counter ; ! counter in let res = of_ts_node get_node_id root in Tree . delete ts_tree ; res
let to_json ( ? pretty = false ) node = let compact_json = Tree_sitter_output_j . string_of_node node in if pretty then Yojson . Safe . prettify compact_json else compact_json
type t = { src : Src_file . t ; root : Tree_sitter_output_t . node }
let src x = x . src
let root x = x . root
let set_missing_fields root_node = let open Tree_sitter_output_t in let counter = ref ( - 1 ) in let create_id ( ) = incr counter ; ! counter in let rec map node = let id = create_id ( ) in assert ( id >= 0 ) ; let children = Option . map ( List . map map ) node . children in let kind = match children with | None -> Literal node . type_ | Some _ -> Name node . type_ in { node with id ; children ; kind } in map root_node
let parse_json_file json_file = Atdgen_runtime . Util . Json . from_file Tree_sitter_output_j . read_node json_file |> set_missing_fields
let load_json_file ~ src_file ~ json_file = let root = parse_json_file json_file in let src = Src_file . load_file src_file in { src ; root }
let parse_source_string ? src_file ts_parser src_data = let src = Src_file . load_string ? src_file src_data in let root = Tree_sitter_API . Parser . parse_string ts_parser src_data |> Tree_sitter_output . of_ts_tree in { src ; root }
let parse_source_file ts_parser src_file = let src_data = Util_file . read_file src_file in parse_source_string ~ src_file ts_parser src_data
let print src = Tree_sitter_dump . to_stdout [ src . root ]
type ' a binary_tree = | Empty | Node of ' a * ' a binary_tree * ' a binary_tree
let rec tree_string = function | Empty -> " " | Node ( x , Empty , Empty ) -> Char . escaped x | Node ( x , left , right ) -> ( Char . escaped x ) ^ " ( " ^ tree_string left ^ " , " ^ tree_string right ^ " ) "
let tree = Node ( ' n ' , Node ( ' k ' , Node ( ' c ' , Node ( ' a ' , Empty , Empty ) , Node ( ' e ' , Node ( ' d ' , Empty , Empty ) , Node ( ' g ' , Empty , Empty ) ) ) , Node ( ' m ' , Empty , Empty ) ) , Node ( ' u ' , Node ( ' p ' , Empty , Node ( ' q ' , Empty , Empty ) ) , Empty ) )
let ( ) = let result = tree_string tree in Printf . printf " % s \ n " result
type ' a node = | Empty | Node of ' a * ' a node * ' a node
let naive_pre_order ( x ' : a node ) : ' a list = let rec aux x = match x with | Empty -> [ ] | Node ( v , l , r ) -> v ( :: aux l ) ( @ aux r ) in aux x
let pre_order ( x ' : a node ) : ' a list = let rec aux l rs = match l with | Empty -> begin match rs with | [ ] -> [ ] | r :: rs -> aux r rs end | Node ( v , l , r ) -> v ( :: aux l ( r :: rs ) ) in aux x [ ]
let naive_post_order ( x ' : a node ) : ' a list = let rec aux x = match x with | Empty -> [ ] | Node ( v , l , r ) -> ( aux l ) ( @ aux r ) [ @ v ] in aux x
let post_order ( x ' : a node ) : ' a list = let rec aux r ls vs = match r with | Empty -> begin match ls with | [ ] -> vs | l :: ls -> aux l ls vs end | Node ( v , l , r ) -> aux r ( l :: ls ) ( v :: vs ) in aux x [ ] [ ]
let naive_in_order ( x ' : a node ) : ' a list = let rec aux x = match x with | Empty -> [ ] | Node ( v , l , r ) -> ( aux l ) ( @ v ( :: aux r ) ) in aux x
let in_order ( x ' : a node ) : ' a list = let rec aux l rs vs = match l with | Empty -> begin match rs with | [ ] -> [ ] | r :: rs -> begin match vs with | [ ] -> [ ] | v :: vs -> v ( :: aux r rs vs ) end end | Node ( v , l , r ) -> aux l ( r :: rs ) ( v :: vs ) in aux x [ ] [ ]
let level_order ( x ' : a node ) : ' a list = let q = Queue . create ( ) in let _ = Queue . add x q in let rec aux q = if Queue . is_empty q then [ ] else match Queue . take q with | Empty -> aux q | Node ( v , l , r ) -> let _ = Queue . add l q in let _ = Queue . add r q in v ( :: aux q ) in aux q
let level_order_list ( x ' : a node ) : ' a list list = let q = Queue . create ( ) in let _ = Queue . add x q in let rec aux acc q curr next = if Queue . is_empty q then [ acc ] else match Queue . take q with | Empty -> aux acc q curr next | Node ( v , l , r ) -> let _ = Queue . add r q in let _ = Queue . add l q in let curr = curr - 1 in let next = next + 2 in if curr = 0 then let curr , next = next , 0 in ( v :: acc ) ( :: aux [ ] q curr next ) else aux ( v :: acc ) q curr next in aux [ ] q 1 0
module Impl = Snarky . Snark . Make ( Snarky . Backends . Mnt4 . Default )
let f __implicit2__ __implicit1__ ( x : ' x * ' y ) ( y : ' b ) b = let y = let typ x___2 = x___2 in Snarky . exists ( typ __implicit2__ ) ~ compute : ( let open As_prover in fun ( ) -> let typ x___1 = x___1 in As_prover . read ( typ __implicit1__ ) y ) in if b then x else y
let g __implicit4__ ( b : boolean ) ( x : field_var ) = ignore ( f { Snarky . Types . Typ . store = ( fun ( x0 , x1 ) -> Snarky . Typ_monads . Store . bind ( Typ . boolean . Snarky . Types . Typ . store x0 ) ~ f ( : fun x0 -> Snarky . Typ_monads . Store . bind ( Typ . boolean . Snarky . Types . Typ . store x1 ) ~ f ( : fun x1 -> Snarky . Typ_monads . Store . return ( x0 , x1 ) ) ) ) ; Snarky . Types . Typ . read = ( fun ( x0 , x1 ) -> Snarky . Typ_monads . Read . bind ( Typ . boolean . Snarky . Types . Typ . read x0 ) ~ f ( : fun x0 -> Snarky . Typ_monads . Read . bind ( Typ . boolean . Snarky . Types . Typ . read x1 ) ~ f ( : fun x1 -> Snarky . Typ_monads . Read . return ( x0 , x1 ) ) ) ) ; Snarky . Types . Typ . alloc = Snarky . Typ_monads . Alloc . bind Typ . boolean . Snarky . Types . Typ . alloc ~ f ( : fun x0 -> Snarky . Typ_monads . Alloc . bind Typ . boolean . Snarky . Types . Typ . alloc ~ f ( : fun x1 -> Snarky . Typ_monads . Alloc . return ( x0 , x1 ) ) ) ; Snarky . Types . Typ . check = ( fun ( x0 , x1 ) -> Snarky . Checked . bind ( Typ . boolean . Snarky . Types . Typ . check x0 ) ~ f ( : fun ( ) -> Snarky . Checked . bind ( Typ . boolean . Snarky . Types . Typ . check x1 ) ~ f ( : fun ( ) -> Snarky . Checked . return ( ) ) ) ) } __implicit4__ ( b , b ) ( true , false ) true ) ; f { Snarky . Types . Typ . store = ( fun ( x0 , x1 ) -> Snarky . Typ_monads . Store . bind ( Typ . field . Snarky . Types . Typ . store x0 ) ~ f ( : fun x0 -> Snarky . Typ_monads . Store . bind ( Typ . field . Snarky . Types . Typ . store x1 ) ~ f ( : fun x1 -> Snarky . Typ_monads . Store . return ( x0 , x1 ) ) ) ) ; Snarky . Types . Typ . read = ( fun ( x0 , x1 ) -> Snarky . Typ_monads . Read . bind ( Typ . field . Snarky . Types . Typ . read x0 ) ~ f ( : fun x0 -> Snarky . Typ_monads . Read . bind ( Typ . field . Snarky . Types . Typ . read x1 ) ~ f ( : fun x1 -> Snarky . Typ_monads . Read . return ( x0 , x1 ) ) ) ) ; Snarky . Types . Typ . alloc = Snarky . Typ_monads . Alloc . bind Typ . field . Snarky . Types . Typ . alloc ~ f ( : fun x0 -> Snarky . Typ_monads . Alloc . bind Typ . field . Snarky . Types . Typ . alloc ~ f ( : fun x1 -> Snarky . Typ_monads . Alloc . return ( x0 , x1 ) ) ) ; Snarky . Types . Typ . check = ( fun ( x0 , x1 ) -> Snarky . Checked . bind ( Typ . field . Snarky . Types . Typ . check x0 ) ~ f ( : fun ( ) -> Snarky . Checked . bind ( Typ . field . Snarky . Types . Typ . check x1 ) ~ f ( : fun ( ) -> Snarky . Checked . return ( ) ) ) ) } { Snarky . Types . Typ . store = ( fun ( x0 , x1 ) -> Snarky . Typ_monads . Store . bind ( Typ . field . Snarky . Types . Typ . store x0 ) ~ f ( : fun x0 -> Snarky . Typ_monads . Store . bind ( Typ . field . Snarky . Types . Typ . store x1 ) ~ f ( : fun x1 -> Snarky . Typ_monads . Store . return ( x0 , x1 ) ) ) ) ; Snarky . Types . Typ . read = ( fun ( x0 , x1 ) -> Snarky . Typ_monads . Read . bind ( Typ . field . Snarky . Types . Typ . read x0 ) ~ f ( : fun x0 -> Snarky . Typ_monads . Read . bind ( Typ . field . Snarky . Types . Typ . read x1 ) ~ f ( : fun x1 -> Snarky . Typ_monads . Read . return ( x0 , x1 ) ) ) ) ; Snarky . Types . Typ . alloc = Snarky . Typ_monads . Alloc . bind Typ . field . Snarky . Types . Typ . alloc ~ f ( : fun x0 -> Snarky . Typ_monads . Alloc . bind Typ . field . Snarky . Types . Typ . alloc ~ f ( : fun x1 -> Snarky . Typ_monads . Alloc . return ( x0 , x1 ) ) ) ; Snarky . Types . Typ . check = ( fun ( x0 , x1 ) -> Snarky . Checked . bind ( Typ . field . Snarky . Types . Typ . check x0 ) ~ f ( : fun ( ) -> Snarky . Checked . bind ( Typ . field . Snarky . Types . Typ . check x1 ) ~ f ( : fun ( ) -> Snarky . Checked . return ( ) ) ) ) } ( x , x ) ( x , x ) false
module Utils = struct let ( . ) # x f = f x let pp_opt pp ppf = function | None -> ( ) | Some x -> pp ppf x let debug fmt = Format . printf ( " Debug : " ^^ fmt ^^ " . " ) @ let ( ) <?> x s = match x with | Ok ( r , x ) -> Format . printf " % a : % s . " @ Vkt . Result . raw_pp r s ; x | Error k -> Format . eprintf " Error % a : % s . " @ Vkt . Result . raw_pp k s ; exit 1 let ( ) <!> x s = match x with | Ok ( ` Success , x ) -> x | Ok ( ` Suboptimal_khr as r , x ) -> Format . printf " % a : % s . " @ Vkt . Result . raw_pp r s ; x | Error k -> Format . eprintf " Error % a : % s . " @ Vkt . Result . raw_pp k s ; exit 1 let ( ) ! = Ctypes . ( ) !@ let ( ) +@ = Ctypes . ( ) +@ let ( <-@ ) = Ctypes . ( <-@ ) let from_array typ a = let n = Array . length a in let a ' = Ctypes . allocate_n ~ count : n typ in Array . iteri ( fun i x -> ( a ' +@ i ) <-@ x ) a ; n , a ' let nullptr typ = Ctypes . ( coerce ( ptr void ) ( ptr typ ) null ) let read_spirv filename = let chan = open_in_bin filename in let len = in_channel_length chan in really_input_string chan len end
module Sdl = struct open Tsdl let ( ) <?> x s = match x with | Ok x -> Format . printf " SDL : Success : % s . " @ s ; x | Error _ -> Format . eprintf " SDL : Error : % s . " @ s ; exit 1 let ( ) = Sdl . ( init Init . ( video + events ) ) <?> " Sdl init " let ( ) = Format . eprintf " Initialization error :% s \ n " %! @@ Sdl . get_error ( ) let w = Sdl . create_window " Vulkan + SDL test " ~ w : 512 ~ h : 512 Sdl . Window . ( allow_highdpi + vulkan ) <?> " Window creation " let ( ) = Sdl . show_window w let e = Sdl . Event . create ( ) let rec event_loop idle e = idle ( ) ; let open Sdl . Event in if Sdl . poll_event @@ Some e && get e typ = key_down && get e keyboard_keycode = Sdl . K . escape then exit 0 else event_loop idle e end
module Instance = struct let extensions = A . of_list Ctypes . string [ " VK_KHR_surface " ; " VK_KHR_xlib_surface " ] let info = Vkt . Instance_create_info . make ~ flags : Vkt . Instance_create_flags . empty ~ enabled_extension_names : extensions ( ) ; ; debug " Info created " let x = Vkc . create_instance info ( ) <?> " instance " let extension_properties = Vkc . enumerate_instance_extension_properties ( ) <?> " Extension properties " ; ; A . iter ( debug " extension properties : % a " Vkt . Extension_properties . pp ) extension_properties end
module Device = struct let phy_devices = let d = Vkc . enumerate_physical_devices instance <?> " physical device " in debug " Number of devices : % d \ n " ( A . length d ) ; d let property device = debug " Device properties acquisition " ; let p = Vkc . get_physical_device_properties device in debug " Device properties acquired " ; p let ( ) = for i = 0 to A . length phy_devices - 1 do Format . printf " Device % d properties :% a " i Vkt . Physical_device_properties . pp ( property @@ A . get phy_devices i ) done let phy = A . get phy_devices 0 let queue_family_properties = Vkc . get_physical_device_queue_family_properties phy ; ; A . iter ( debug " Queue flags :@ [ @% a ] " @ Vkt . Queue_family_properties . pp ) queue_family_properties let queue_family = 0 let priorities = A . of_list Ctypes . float [ 1 . ] let queue_create_info = Vkt . Device_queue_create_info . make ~ queue_family_index : queue_family ~ queue_priorities : priorities ( ) let device_extensions = Vkc . enumerate_device_extension_properties phy ( ) <?> " device extensions " ; ; A . iter ( debug " Device extension :@ [ @% a ] " @ Vkt . Extension_properties . pp ) device_extensions let surface_khr = Vkt . Surface_khr . unsafe_from_int64 @@ Tsdl . Sdl . Vulkan . unsafe_uint64_of_surface @@ match Tsdl . Sdl . Vulkan . create_surface Sdl . w @@ Tsdl . Sdl . Vulkan . unsafe_instance_of_ptr @@ Vkt . Instance . to_ptr instance with | None -> exit 2 | Some s -> s let capabilities = Surface . get_physical_device_surface_capabilities_khr phy surface_khr <?> " Surface capabilities " ; ; debug " Surface capabilities : % a " Vkt . Surface_capabilities_khr . pp capabilities let supported_formats = Surface . get_physical_device_surface_formats_khr phy surface_khr <?> " supported surface formats " ; ; A . iter ( debug " Supported formats : % a " Vkt . Surface_format_khr . pp ) supported_formats let present_modes = Surface . get_physical_device_surface_present_modes_khr phy surface_khr <?> " present modes " ; ; A . iter ( debug " % a " Vkt . Present_mode_khr . pp ) present_modes let support = let x = Surface . get_physical_device_surface_support_khr phy queue_family surface_khr <?> " Compatibility surface / device " in assert ( x = true ) let x = let exts = A . of_list Ctypes . string [ " VK_KHR_swapchain " ] in let info = let queue_create_infos = A . of_list Vkt . Device_queue_create_info . ctype [ queue_create_info ] in Vkt . Device_create_info . make ~ queue_create_infos ~ enabled_extension_names : exts ( ) in Vkc . create_device phy info ( ) <?> " Create logical device " end
module Image = struct let surface_format = A . get Device . supported_formats 0 let format , colorspace = let open Vkt . Surface_format_khr in surface_format . # format , surface_format . # color_space let image_count , extent = let open Vkt . Surface_capabilities_khr in Device . capabilities |> min_image_count , Device . capabilities |> current_extent let swap_chain_info = let qfi = A . of_list Bt . uint_32_t [ 0 ] in Vkt . Swapchain_create_info_khr . make ~ surface : surface_khr ~ min_image_count : image_count ~ image_format : format ~ image_color_space : colorspace ~ image_extent : extent ~ image_array_layers : 1 ~ image_usage : Vkt . Image_usage_flags . ( color_attachment + sampled ) ~ image_sharing_mode : Vkt . Sharing_mode . Exclusive ~ queue_family_indices : qfi ~ pre_transform : Vkt . Surface_transform_flags_khr . identity ~ composite_alpha : Vkt . Composite_alpha_flags_khr . opaque ~ present_mode : Vkt . Present_mode_khr . Fifo ~ clipped : true ~ old_swapchain : Vkt . Swapchain_khr . null ( ) let swap_chain = Swapchain . create_swapchain_khr device swap_chain_info ( ) <?> " swap chain creation " let images = Swapchain . get_swapchain_images_khr device swap_chain <?> " Swapchain images " ; ; debug " Swapchain : % d images " ( A . length images ) let component_mapping = let id = Vkt . Component_swizzle . Identity in Vkt . Component_mapping . make ~ r : id ~ g : id ~ b : id ~ a : id let subresource_range = Vkt . Image_subresource_range . make ~ aspect_mask : Vkt . Image_aspect_flags . color ~ base_mip_level : 0 ~ level_count : 1 ~ base_array_layer : 0 ~ layer_count : 1 let image_view_info im = Vkt . Image_view_create_info . make ~ image : im ~ view_type : Vkt . Image_view_type . N2d ~ format ~ subresource_range ~ components : component_mapping ( ) let views = let create im = Vkc . create_image_view device ( image_view_info im ) ( ) <?> " Creating image view " in A . map Vkt . Image_view . ctype create images end
module Pipeline = struct module Shaders = struct let frag = read_spirv " shaders / triangle / frag . spv " let vert = read_spirv " shaders / triangle / vert . spv " let shader_module_info s = let len = String . length s in let code = A . make Bt . uint_32_t ( len / Ctypes . ( sizeof uint32_t ) ) in let c ' = A . from_ptr Ctypes . ( coerce ( ptr Bt . uint_32_t ) ( ptr char ) @@ A . start code ) len in String . iteri ( fun n x -> A . set c ' n x ) s ; Vkt . Shader_module_create_info . make ~ code_size ( : Unsigned . Size_t . of_int len ) ~ code ( ) let create_shader name s = let info = shader_module_info s in Vkc . create_shader_module device info ( ) <?> " Shader creation " : ^ name let frag_shader = create_shader " fragment " frag let vert_shader = create_shader " vertex " vert let make_stage stage module ' = Vkt . Pipeline_shader_stage_create_info . make ~ stage ~ module ' ~ name : " main " ( ) let frag_stage = make_stage Vkt . Shader_stage_flags . fragment frag_shader let vert_stage = make_stage Vkt . Shader_stage_flags . vertex vert_shader end let null_input = Vkt . Pipeline_vertex_input_state_create_info . make ( ) let input_assembly = Vkt . Pipeline_input_assembly_state_create_info . make ~ flags : Vkt . Pipeline_input_assembly_state_create_flags . empty ~ topology : Vkt . Primitive_topology . Triangle_list ~ primitive_restart_enable : false ( ) let viewport = let width = float Image . extent . # Vkt . Extent_2d . width and height = float Image . extent . # Vkt . Extent_2d . height in Vkt . Viewport . make ~ x : 0 . ~ y : 0 . ~ width ~ height ~ min_depth : 0 . ~ max_depth : 1 . let scissor = Vkt . Rect_2d . make ~ offset : ( Vkt . Offset_2d . make ~ x : 0 ~ y : 0 ) ~ extent : Image . extent let viewports = A . of_list Vkt . Viewport . ctype [ viewport ] let scissors = A . of_list Vkt . Rect_2d . ctype [ scissor ] let viewport_state = Vkt . Pipeline_viewport_state_create_info . make ~ viewports ~ scissors ( ) let rasterizer = Vkt . Pipeline_rasterization_state_create_info . make ~ depth_clamp_enable : false ~ rasterizer_discard_enable : false ~ polygon_mode : Vkt . Polygon_mode . Fill ~ cull_mode : Vkt . Cull_mode_flags . back ~ front_face : Vkt . Front_face . Clockwise ~ depth_bias_enable : false ~ depth_bias_constant_factor : 0 . ~ depth_bias_clamp : 0 . ~ depth_bias_slope_factor : 0 . ~ line_width : 1 . ( ) let no_multisampling = Vkt . Pipeline_multisample_state_create_info . make ~ flags : Vkt . Pipeline_multisample_state_create_flags . empty ~ rasterization_samples : Vkt . Sample_count_flags . n1 ~ sample_shading_enable : false ~ min_sample_shading : 1 . ~ alpha_to_coverage_enable : false ~ alpha_to_one_enable : false ( ) let no_blend = Vkt . Pipeline_color_blend_attachment_state . make ~ blend_enable : false ~ color_write_mask : Vkt . Color_component_flags . ( r + g + b + a ) ~ src_color_blend_factor : Vkt . Blend_factor . One ~ dst_color_blend_factor : Vkt . Blend_factor . Zero ~ color_blend_op : Vkt . Blend_op . Add ~ src_alpha_blend_factor : Vkt . Blend_factor . One ~ dst_alpha_blend_factor : Vkt . Blend_factor . Zero ~ alpha_blend_op : Vkt . Blend_op . Add ( ) let blend_state_info = let attachments = A . of_list Vkt . Pipeline_color_blend_attachment_state . ctype [ no_blend ] in let consts = A . of_list Ctypes . float [ 0 . ; 0 . ; 0 . ; 0 . ] in Vkt . Pipeline_color_blend_state_create_info . make ~ logic_op_enable : false ~ logic_op : Vkt . Logic_op . Copy ~ attachments ~ blend_constants : consts ( ) let no_uniform = Vkt . Pipeline_layout_create_info . make ( ) let simple_layout = Vkc . create_pipeline_layout device no_uniform ( ) <?> " Creating pipeline layout " let color_attachment = Vkt . Attachment_description . make ~ format : Image . format ~ samples : Vkt . Sample_count_flags . n1 ~ load_op : Vkt . Attachment_load_op . Clear ~ store_op : Vkt . Attachment_store_op . Store ~ stencil_load_op : Vkt . Attachment_load_op . Dont_care ~ stencil_store_op : Vkt . Attachment_store_op . Dont_care ~ initial_layout : Vkt . Image_layout . Undefined ~ final_layout : Vkt . Image_layout . Present_src_khr ( ) let attachment = Vkt . Attachment_reference . make ~ attachment : 0 ~ layout : Vkt . Image_layout . Color_attachment_optimal let subpass = let color = A . of_list Vkt . Attachment_reference . ctype [ attachment ] in Vkt . Subpass_description . make ~ pipeline_bind_point : Vkt . Pipeline_bind_point . Graphics ~ color_attachments : color ( ) let render_pass_info = let attachments = A . of_list Vkt . Attachment_description . ctype [ color_attachment ] in let subpasses = A . of_list Vkt . Subpass_description . ctype [ subpass ] in Vkt . Render_pass_create_info . make ~ attachments ~ subpasses ( ) let simple_render_pass = Vkc . create_render_pass device render_pass_info ( ) <?> " Creating render pass " let pipeline_info = let stages = A . of_list Vkt . Pipeline_shader_stage_create_info . ctype Shaders . [ vert_stage ; frag_stage ] in Vkt . Graphics_pipeline_create_info . make ~ stages ~ vertex_input_state : null_input ~ input_assembly_state : input_assembly ~ viewport_state : viewport_state ~ rasterization_state : rasterizer ~ multisample_state : no_multisampling ~ color_blend_state : blend_state_info ~ layout : simple_layout ~ render_pass : simple_render_pass ~ subpass : 0 ~ base_pipeline_index : 0 ( ) let pipeline_infos = A . of_list Vkt . Graphics_pipeline_create_info . ctype [ pipeline_info ] let pipelines = Vkc . create_graphics_pipelines device pipeline_infos ( ) <?> " Graphics pipeline creation " let x = A . get pipelines 0 end
module Cmd = struct let framebuffer_info image = let images = A . of_list Vkt . Image_view . ctype [ image ] in Vkt . Framebuffer_create_info . make ~ render_pass : Pipeline . simple_render_pass ~ attachments : images ~ width : Image . extent . # Vkt . Extent_2d . width ~ height : Image . extent . # Vkt . Extent_2d . height ~ layers : 1 ( ) let framebuffer index = Vkc . create_framebuffer device ( framebuffer_info index ) ( ) <?> " Framebuffer creation " let framebuffers = A . map Vkt . Framebuffer . ctype framebuffer Image . views let my_fmb = framebuffer let queue = Vkc . get_device_queue device Device . queue_family 0 let command_pool_info = Vkt . Command_pool_create_info . make ~ queue_family_index : Device . queue_family ( ) let command_pool = Vkc . create_command_pool device command_pool_info ( ) <?> " Command pool creation " let my_cmd_pool = command_pool let n_cmd_buffers = ( A . length framebuffers ) let buffer_allocate_info = Vkt . Command_buffer_allocate_info . make ~ command_pool : my_cmd_pool ~ level : Vkt . Command_buffer_level . Primary ~ command_buffer_count : n_cmd_buffers ( ) let cmd_buffers = Vkc . allocate_command_buffers device buffer_allocate_info <?> " Command buffers allocation " ; ; debug " Created % d cmd buffers " n_cmd_buffers let cmd_begin_info = Vkt . Command_buffer_begin_info . make ~ flags : Vkt . Command_buffer_usage_flags . simultaneous_use ( ) let clear_values = let a = A . of_list Ctypes . float [ 0 . ; 0 . ; 0 . ; 1 . ] in let c = Vkt . Clear_color_value . float_32 a in Vkt . Clear_value . color c let render_pass_info fmb = let clear_values = A . of_list Vkt . Clear_value . ctype [ clear_values ] in Vkt . Render_pass_begin_info . make ~ render_pass : Pipeline . simple_render_pass ~ framebuffer : fmb ~ render_area : Pipeline . scissor ~ clear_values : clear_values ( ) let cmd b fmb = Vkc . begin_command_buffer b cmd_begin_info <?> " Begin command buffer " ; Vkc . cmd_begin_render_pass b ( render_pass_info fmb ) Vkt . Subpass_contents . Inline ; Vkc . cmd_bind_pipeline b Vkt . Pipeline_bind_point . Graphics Pipeline . x ; Vkc . cmd_draw b 3 1 0 0 ; Vkc . cmd_end_render_pass b ; Vkc . end_command_buffer b <?> " Command buffer recorded " let iter2 f a b = for i = 0 to min ( A . length a ) ( A . length b ) - 1 do f ( A . get a i ) ( A . get b i ) done let ( ) = iter2 cmd cmd_buffers framebuffers end
module Render = struct let semaphore_info = Vkt . Semaphore_create_info . make ( ) let create_semaphore ( ) = Vkc . create_semaphore device semaphore_info ( ) <?> " Created semaphore " let im_semaphore = create_semaphore ( ) let render_semaphore = create_semaphore ( ) let wait_sems = Vkt . Semaphore . array [ im_semaphore ] let sign_sems = Vkt . Semaphore . array [ render_semaphore ] let wait_stage = let open Vkt . Pipeline_stage_flags in A . of_list ctype [ top_of_pipe ] let submit_info _index = Vkt . Submit_info . array [ Vkt . Submit_info . make ~ wait_semaphores : wait_sems ~ wait_dst_stage_mask : wait_stage ~ command_buffers : Cmd . cmd_buffers ~ signal_semaphores : sign_sems ( ) ] let swapchains = Vkt . Swapchain_khr . array [ Image . swap_chain ] let present_indices = A . of_list Bt . uint_32_t [ 0 ] let present_info = Vkt . Present_info_khr . make ~ wait_semaphores : sign_sems ~ swapchains ~ image_indices : present_indices ( ) let debug_draw ( ) = let n = Swapchain . acquire_next_image_khr ~ device ~ swapchain : Image . swap_chain ~ timeout : Unsigned . UInt64 . max_int ~ semaphore : im_semaphore ( ) <?> " Acquire image " in A . set present_indices 0 n ; debug " Image % d acquired " n ; Vkc . queue_submit ~ queue : Cmd . queue ~ submits ( : submit_info n ) ( ) <?> " Submitting command to queue " ; Swapchain . queue_present_khr Cmd . queue present_info <?> " Image presented " let rec acquire_next ( ) = match Swapchain . acquire_next_image_khr ~ device ~ swapchain : Image . swap_chain ~ timeout : Unsigned . UInt64 . max_int ~ semaphore : im_semaphore ( ) with | Ok ( ( ` Success ` | Suboptimal_khr ) , n ) -> n | Ok ( ( ` Timeout ` | Not_ready ) , _ ) -> acquire_next ( ) | Error x -> ( Format . eprintf " Error % a in acquire_next " Vkt . Result . raw_pp x ; exit 2 ) let draw ( ) = A . set present_indices 0 @@ acquire_next ( ) ; Vkc . queue_submit ~ queue : Cmd . queue ~ submits ( : submit_info present_indices ) ( ) <!> " Submit to queue " ; Swapchain . queue_present_khr Cmd . queue present_info <!> " Present to queue " end
module type M = sig type key type ' a t val empty : ' a t val is_empty : ' a t -> bool val add : key -> ' a -> ' a t -> ' a t val find : key -> ' a t -> ' a val remove : key -> ' a t -> ' a t val fold : ( key -> ' a -> ' b -> ' b ) -> ' a t -> ' b -> ' b val compare : ( ' a -> ' a -> int ) -> ' a t -> ' a t -> int val equal : ( ' a -> ' a -> bool ) -> ' a t -> ' a t -> bool end
module type S = sig include M val mem : key -> ' a t -> bool val iter : ( key -> ' a -> unit ) -> ' a t -> unit val map : ( ' a -> ' b ) -> ' a t -> ' b t val mapi : ( key -> ' a -> ' b ) -> ' a t -> ' b t val keys : ' a t -> key list val data : ' a t -> ' a list val find_approximate : max_differences : int -> key -> ' a t -> ' a list end
module Make ( M : M ) = struct type key = M . key list type ' a t = Node of ' a option * ' a t M . t let empty = Node ( None , M . empty ) let is_empty = function | Node ( None , m1 ) -> M . is_empty m1 | _ -> false let rec find l t = match ( l , t ) with | [ ] , Node ( None , _ ) -> raise Not_found | [ ] , Node ( Some v , _ ) -> v | x :: r , Node ( _ , m ) -> find r ( M . find x m ) let mem l t = try ignore ( find l t ) ; true with Not_found -> false let add l v t = let rec ins = function | [ ] , Node ( _ , m ) -> Node ( Some v , m ) | x :: r , Node ( v , m ) -> let t ' = try M . find x m with Not_found -> empty in let t ' ' = ins ( r , t ' ) in Node ( v , M . add x t ' ' m ) in ins ( l , t ) let rec remove l t = match ( l , t ) with | [ ] , Node ( _ , m ) -> Node ( None , m ) | x :: r , Node ( v , m ) -> try let t ' = remove r ( M . find x m ) in Node ( v , if is_empty t ' then M . remove x m else M . add x t ' m ) with Not_found -> t let fold f t acc = let rec traverse revp t acc = match t with | Node ( None , m ) -> M . fold ( fun x -> traverse ( x :: revp ) ) m acc | Node ( Some v , m ) -> f ( List . rev revp ) v ( M . fold ( fun x -> traverse ( x :: revp ) ) m acc ) in traverse [ ] t acc let map f t = fold ( fun key value acc -> add key ( f value ) acc ) t empty let mapi f t = fold ( fun key value acc -> add key ( f key value ) acc ) t empty let iter f t = fold ( fun key value ( ) -> f key value ) t ( ) let compare cmp a b = let rec comp a b = match a , b with | Node ( Some _ , _ ) , Node ( None , _ ) -> 1 | Node ( None , _ ) , Node ( Some _ , _ ) -> - 1 | Node ( None , m1 ) , Node ( None , m2 ) -> M . compare comp m1 m2 | Node ( Some a , m1 ) , Node ( Some b , m2 ) -> let c = cmp a b in if c <> 0 then c else M . compare comp m1 m2 in comp a b let equal eq a b = let rec comp a b = match a , b with | Node ( None , m1 ) , Node ( None , m2 ) -> M . equal comp m1 m2 | Node ( Some a , m1 ) , Node ( Some b , m2 ) -> eq a b && M . equal comp m1 m2 | _ -> false in comp a b let keys t = fold ( fun key _ acc -> key :: acc ) t [ ] |> List . rev let data t = fold ( fun _ value acc -> value :: acc ) t [ ] |> List . rev let find_approximate ~ max_differences key t = if max_differences < 0 then invalid_arg " max_differences must be >= 0 " ; let rec find_approximate ' ~ max_differences key t acc = if max_differences = 0 then try ( find key t ) :: acc with Not_found -> acc else let with_difference f = f ~ max_differences ( : max_differences - 1 ) in match key , t with | [ ] , Node ( value , links ) -> let acc = match value with | Some value -> value :: acc | None -> acc in with_difference ( fun ~ max_differences -> M . fold ( fun _ next acc -> find_approximate ' ~ max_differences [ ] next acc ) links acc ) | current_key :: remaining_key , Node ( _ , links ) -> with_difference ( find_approximate ' remaining_key t acc ) |> M . fold ( fun link_key next acc -> if current_key = link_key then find_approximate ' ~ max_differences remaining_key next acc else with_difference ( fun ~ max_differences -> find_approximate ' ~ max_differences remaining_key next acc |> find_approximate ' ~ max_differences key next ) ) links in find_approximate ' ~ max_differences key t [ ] end
let ( >>= ) x f = match x with Ok v -> f v | Error _ as e -> e
let bigarray_create k len = Bigarray . ( Array1 . create k c_layout len )
let get_int = let a = bigarray_create Bigarray . int32 1 in fun f -> f a ; Int32 . to_int a . { 0 }
let set_int = let a = bigarray_create Bigarray . int32 1 in fun f i -> a . { 0 } <- Int32 . of_int i ; f a
let get_string len f = let a = bigarray_create Bigarray . char len in f a ; Gl . string_of_bigarray a
let glsl_version gl_version = match gl_version with
let vertex_shader v = str " # version % s core in vec3 vertex ; in vec3 color ; out vec4 v_color ; void main ( ) { v_color = vec4 ( color , 1 . 0 ) ; gl_Position = vec4 ( vertex , 1 . 0 ) ; } " v
let fragment_shader v = str " # version % s core in vec4 v_color ; out vec4 color ; void main ( ) { color = v_color ; } " v
let set_3d ba i x y z = let start = i * 3 in ba . { start } <- x ; ba . { start + 1 } <- y ; ba . { start + 2 } <- z
let vertices = let vs = bigarray_create Bigarray . float32 ( 3 * 3 ) in set_3d vs 0 ( - 0 . 8 ) ( - 0 . 8 ) 0 . 0 ; set_3d vs 1 0 . 8 ( - 0 . 8 ) 0 . 0 ; set_3d vs 2 0 . 0 0 . 8 0 . 0 ; vs
let colors = let cs = bigarray_create Bigarray . float32 ( 3 * 3 ) in set_3d cs 0 1 . 0 0 . 0 0 . 0 ; set_3d cs 1 0 . 0 1 . 0 0 . 0 ; set_3d cs 2 0 . 0 0 . 0 1 . 0 ; cs
let indices = let is = bigarray_create Bigarray . int8_unsigned 3 in set_3d is 0 0 1 2 ; is
let create_buffer b = let id = get_int ( Gl . gen_buffers 1 ) in let bytes = Gl . bigarray_byte_size b in Gl . bind_buffer Gl . array_buffer id ; Gl . buffer_data Gl . array_buffer bytes ( Some b ) Gl . static_draw ; id
let delete_buffer bid = set_int ( Gl . delete_buffers 1 ) bid
let create_geometry ( ) = let gid = get_int ( Gl . gen_vertex_arrays 1 ) in let iid = create_buffer indices in let vid = create_buffer vertices in let cid = create_buffer colors in let bind_attrib id loc dim typ = Gl . bind_buffer Gl . array_buffer id ; Gl . enable_vertex_attrib_array loc ; Gl . vertex_attrib_pointer loc dim typ false 0 ( ` Offset 0 ) ; in Gl . bind_vertex_array gid ; Gl . bind_buffer Gl . element_array_buffer iid ; bind_attrib vid 0 3 Gl . float ; bind_attrib cid 1 3 Gl . float ; Gl . bind_vertex_array 0 ; Gl . bind_buffer Gl . array_buffer 0 ; Gl . bind_buffer Gl . element_array_buffer 0 ; Ok ( gid , [ iid ; vid ; cid ] )
let delete_geometry gid bids = set_int ( Gl . delete_vertex_arrays 1 ) gid ; List . iter delete_buffer bids ; Ok ( )
let compile_shader src typ = let get_shader sid e = get_int ( Gl . get_shaderiv sid e ) in let sid = Gl . create_shader typ in Gl . shader_source sid src ; Gl . compile_shader sid ; if get_shader sid Gl . compile_status = Gl . true_ then Ok sid else let len = get_shader sid Gl . info_log_length in let log = get_string len ( Gl . get_shader_info_log sid len None ) in ( Gl . delete_shader sid ; Error ( ` Msg log ) )
let create_program glsl_v = compile_shader ( vertex_shader glsl_v ) Gl . vertex_shader >>= fun vid -> compile_shader ( fragment_shader glsl_v ) Gl . fragment_shader >>= fun fid -> let pid = Gl . create_program ( ) in let get_program pid e = get_int ( Gl . get_programiv pid e ) in Gl . attach_shader pid vid ; Gl . delete_shader vid ; Gl . attach_shader pid fid ; Gl . delete_shader fid ; Gl . bind_attrib_location pid 0 " vertex " ; Gl . bind_attrib_location pid 1 " color " ; Gl . link_program pid ; if get_program pid Gl . link_status = Gl . true_ then Ok pid else let len = get_program pid Gl . info_log_length in let log = get_string len ( Gl . get_program_info_log pid len None ) in ( Gl . delete_program pid ; Error ( ` Msg log ) )
let delete_program pid = Gl . delete_program pid ; Ok ( )
let draw pid gid win = Gl . clear_color 0 . 0 . 0 . 1 . ; Gl . clear Gl . color_buffer_bit ; Gl . use_program pid ; Gl . bind_vertex_array gid ; Gl . draw_elements Gl . triangles 3 Gl . unsigned_byte ( ` Offset 0 ) ; Gl . bind_vertex_array 0 ; Sdl . gl_swap_window win ; Ok ( )
let reshape win w h = Gl . viewport 0 0 w h
let pp_opengl_info ppf ( ) = let pp = Format . fprintf in let pp_opt ppf = function None -> pp ppf " error " | Some s -> pp ppf " % s " s in pp ppf " [ @< v , " ; >@ pp ppf " Renderer [ @< v [ >@% a ] , " @@ pp_opt ( Gl . get_string Gl . renderer ) ; pp ppf " [ @ OpenGL % a / GLSL % a ] ] , " @@@ pp_opt ( Gl . get_string Gl . version ) pp_opt ( Gl . get_string Gl . shading_language_version ) ; pp ppf " ] " @
let create_window ~ gl ( : maj , min ) = let w_atts = Sdl . Window . ( opengl + resizable ) in let w_title = Printf . sprintf " OpenGL % d . % d ( core profile ) " maj min in let set a v = Sdl . gl_set_attribute a v in set Sdl . Gl . context_profile_mask Sdl . Gl . context_profile_core >>= fun ( ) -> set Sdl . Gl . context_major_version maj >>= fun ( ) -> set Sdl . Gl . context_minor_version min >>= fun ( ) -> set Sdl . Gl . doublebuffer 1 >>= fun ( ) -> Sdl . create_window ~ w : 640 ~ h : 480 w_title w_atts >>= fun win -> Sdl . gl_create_context win >>= fun ctx -> Sdl . gl_make_current win ctx >>= fun ( ) -> Sdl . log " % a " pp_opengl_info ( ) ; Ok ( win , ctx )
let destroy_window win ctx = Sdl . gl_delete_context ctx ; Sdl . destroy_window win ; Ok ( )
let event_loop win draw = let e = Sdl . Event . create ( ) in let key_scancode e = Sdl . Scancode . enum Sdl . Event . ( get e keyboard_scancode ) in let event e = Sdl . Event . ( enum ( get e typ ) ) in let window_event e = Sdl . Event . ( window_event_enum ( get e window_event_id ) ) in let rec loop ( ) = ignore ( Sdl . wait_event_timeout ( Some e ) 1 ) ; match event e with | ` Quit -> Ok ( ) | ` Key_down when key_scancode e = ` Escape -> Ok ( ) | ` Window_event -> begin match window_event e with | ` Exposed | ` Resized -> let w , h = Sdl . get_window_size win in reshape win w h ; draw win ; draw win ; loop ( ) | _ -> loop ( ) end | _ -> loop ( ) in ( draw win ; loop ( ) )
let tri ~ gl ( : maj , min as gl ) = Sdl . init Sdl . Init . video >>= fun ( ) -> create_window ~ gl >>= fun ( win , ctx ) -> create_geometry ( ) >>= fun ( gid , bids ) -> create_program ( glsl_version gl ) >>= fun pid -> event_loop win ( draw pid gid ) >>= fun ( ) -> delete_program pid >>= fun ( ) -> delete_geometry gid bids >>= fun ( ) -> destroy_window win ctx >>= fun ( ) -> Sdl . quit ( ) ; Ok ( )
let main ( ) = let exec = Filename . basename Sys . executable_name in let usage = str " Usage : % s [ OPTION ] \ n Tests Tgl3 . \ nOptions " : exec in let minor = ref 2 in let options = [ " - minor " , Arg . Set_int minor , " < x > use Use an OpenGL 3 . x context ( defaults to 3 . 2 ) " ; ] in let anon _ = raise ( Arg . Bad " no arguments are supported " ) in Arg . parse ( Arg . align options ) anon usage ; match tri ~ gl ( : 3 , ! minor ) with | Ok ( ) -> exit 0 | Error ( ` Msg msg ) -> Sdl . log " % s . " @ msg ; exit 1
let ( ) = main ( )
let ( >>= ) x f = match x with Ok v -> f v | Error _ as e -> e
let bigarray_create k len = Bigarray . ( Array1 . create k c_layout len )
let get_int = let a = bigarray_create Bigarray . int32 1 in fun f -> f a ; Int32 . to_int a . { 0 }
let set_int = let a = bigarray_create Bigarray . int32 1 in fun f i -> a . { 0 } <- Int32 . of_int i ; f a
let get_string len f = let a = bigarray_create Bigarray . char len in f a ; Gl . string_of_bigarray a
let glsl_version gl_version = match gl_version with
let vertex_shader v = str " # version % s core in vec3 vertex ; in vec3 color ; out vec4 v_color ; void main ( ) { v_color = vec4 ( color , 1 . 0 ) ; gl_Position = vec4 ( vertex , 1 . 0 ) ; } " v
let fragment_shader v = str " # version % s core in vec4 v_color ; out vec4 color ; void main ( ) { color = v_color ; } " v
let set_3d ba i x y z = let start = i * 3 in ba . { start } <- x ; ba . { start + 1 } <- y ; ba . { start + 2 } <- z
let vertices = let vs = bigarray_create Bigarray . float32 ( 3 * 3 ) in set_3d vs 0 ( - 0 . 8 ) ( - 0 . 8 ) 0 . 0 ; set_3d vs 1 0 . 8 ( - 0 . 8 ) 0 . 0 ; set_3d vs 2 0 . 0 0 . 8 0 . 0 ; vs