text:
package org.codehaus.groovy.grails.compiler;

import grails.util.PluginBuildSettings;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.groovy.ant.Groovyc;
import org.codehaus.groovy.grails.compiler.support.GrailsResourceLoader;
import org.codehaus.groovy.grails.compiler.support.GrailsResourceLoaderHolder;
import org.springframework.core.io.Resource;

public class Grailsc extends Groovyc {

    private List<File> destList = new ArrayList<File>();
    private PluginBuildSettings pluginBuildSettings;

    @Override
    protected void scanDir(File srcDir, File destDir, String[] files) {
       List<File> srcList = new ArrayList<File>();
       String srcPath = srcDir.getAbsolutePath();
       String destPath = destDir.getAbsolutePath();
       for (String f : files) {
           File sf = new File(srcPath, f);
           File df = null;
           if (f.endsWith(".groovy") ) {
               df = new File(destPath, f.substring(0, f.length()-7) + ".class");
               int i = f.lastIndexOf('/');
               if (!df.exists() && i > -1) {
                   // check root package
                   File tmp = new File(destPath, f.substring(i, f.length()-7) + ".class");
                   if (tmp.exists()) {
                       df = tmp;
                   }
               }
           }
           else if (f.endsWith(".java")) {
               df = new File(destPath, f.substring(0, f.length()-5) + ".class");
           }
           else {
               continue;
           }

           if (sf.lastModified() > df.lastModified()) {
               srcList.add(sf);
               destList.add(df);
           }
       }
       addToCompileList(srcList.toArray(new File[srcList.size()]));
    }

    @Override
    protected void compile() {
        configureResourceLoader();

        if (compileList.length > 0) {
            long now = System.currentTimeMillis();
            try {
                super.compile();
                getDestdir().setLastModified(now);
            }
            finally {
                // set the destination files as modified so recompile doesn't happen continuously
                for (File f : destList) {
                    f.setLastModified(now);
                }
            }
        }
    }

    private void configureResourceLoader() {
        if (pluginBuildSettings != null) {
            Resource[] resources = pluginBuildSettings.getArtefactResources();
            GrailsResourceLoader resourceLoader = new GrailsResourceLoader(resources);
            GrailsResourceLoaderHolder.setResourceLoader(resourceLoader);
        }
    }
}


text:
/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
window.Oncoprint = (function() {
	var events = oncoprint_events;
	var utils = oncoprint_utils;
	var RuleSet = oncoprint_RuleSet;

	var defaultOncoprintConfig = {
		cell_width: 6,
		cell_padding: 2.5,
		legend: true,
	};

	var hiddenOncoprintConfig = {
		pre_track_padding: 0,
	};

	var defaultTrackConfig = {
		label: 'Gene',
		datum_id_key: 'patient',
		cell_height: 23,
		track_height: 20,
		track_padding: 5,
		sort_cmp: undefined,
		tooltip: function(d) {
			return d['patient'];
		},
		removable: false,
		sort_direction_changable: false
	};

	function Oncoprint(config) {
		var self = this;
		var getTrackId = utils.makeIdCounter();

		self.config = config;

		self.id_order = [];
		self.inverted_id_order = {};
		self.visible_id_order = [];
		self.visible_inverted_id_order = {};
		self.hidden_ids = {};
		self.track_groups = [[],[]];
		self.track_group_sort_order = [0,1];
		self.sort_direction = {};
		self.tracks = {};
		self.sort_config = {type: 'track'};

		self.cell_padding_on = true;
		self.true_cell_width = config.cell_width;

		self.zoomed_cell_width = self.true_cell_width;
		self.zoom = 1;

		// Cell Padding
		self.toggleCellPadding = function() {
			self.cell_padding_on = !self.cell_padding_on;
			$(self).trigger(events.SET_CELL_PADDING);
		};
		self.getCellPadding = function() {
			return Math.ceil(self.config.cell_padding*self.getZoom())*(+self.cell_padding_on);
		};

		// Zoom
		self.getZoom = function() {
			return self.zoom;
		};
		self.setZoom = function(z) {
			self.zoom = utils.clamp(z, 0, 1);
			updateZoomedCellWidth();
			updateZoom();
			$(self).trigger(events.SET_ZOOM);
			return self.zoom;
		};
		var updateZoom = function() {
			// maps {1, ... , true_cell_width} to [0,1]
			self.zoom = (self.zoomed_cell_width-1)/(self.true_cell_width - 1);
		};
		var updateZoomedCellWidth = function() {
			// maps [0,1] to {1, ... , true_cell_width}
			self.zoomed_cell_width = Math.round(self.zoom*(self.true_cell_width-1) + 1);
		};
		self.increaseZoom = function() {
			self.zoomed_cell_width = utils.clamp(self.zoomed_cell_width+1, 1, self.true_cell_width);
			updateZoom();
			$(self).trigger(events.SET_ZOOM);
			return self.zoom;
		};
		self.decreaseZoom = function() {
			self.zoomed_cell_width = utils.clamp(self.zoomed_cell_width-1, 1, self.true_cell_width);
			updateZoom();
			$(self).trigger(events.SET_ZOOM);
			return self.zoom;
		};

		// Cell Width
		self.getFullCellWidth = function() {
			return self.true_cell_width;
		};
		self.getZoomedCellWidth = function() {
			return self.zoomed_cell_width;
		};

		// Cell Height
		self.getCellHeight = function(track_id) {
			return self.tracks[track_id].config.cell_height;
		};

		// Track Height
		self.getTrackHeight = function(track_id) {
			return self.tracks[track_id].config.track_height;
		};

		// Track Padding
		self.getTrackPadding = function(track_id) {
			return self.tracks[track_id].config.track_padding;
		};

		// Id Order
		self.getFilteredIdOrder = function(data_filter_fn, track_ids) {
			var tracks = track_ids || self.getTracks();
			return _.filter(self.id_order, function(id) {
				var d = _.map(tracks, function(track_id) {
					return self.getTrackDatum(track_id, id);
				});
				return data_filter_fn(d);
			});
		};
		self.getIdOrder = function() {
			return self.id_order;
		};
		self.getInvertedIdOrder = function() {
			return self.inverted_id_order;
		};
		self.getVisibleIdOrder = function() {
			return self.visible_id_order;
		};
		self.getVisibleInvertedIdOrder = function() {
			return self.visible_inverted_id_order;
		};
		var updateVisibleIdOrder = function() {
			self.visible_id_order = _.filter(self.id_order, function(id) {
				return !self.hidden_ids[id];
			});
			self.visible_inverted_id_order = utils.invert_array(self.visible_id_order);
			$(self).trigger(events.SET_VISIBLE_ID_ORDER);
		};
		self.setIdOrder = function(id_order) {
			self.id_order = id_order.slice();
			self.inverted_id_order = utils.invert_array(self.id_order);
			updateVisibleIdOrder();
			$(self).trigger(events.SET_ID_ORDER);
		};
		// Hide Ids
		self.hideIds = function(ids, clear_existing) {
			if (clear_existing) {
				self.hidden_ids = {};
			}
			_.each(ids, function(id) {
				self.hidden_ids[id] = true;
			});
			updateVisibleIdOrder();
		};
		self.showIds = function(ids) {
			if (!ids) {
				self.hidden_ids = {};
			} else {
				_.each(ids, function(id) {
					delete self.hidden_ids[id];
				});
			}
			updateVisibleIdOrder();
		};

		// Sorting
		self.getTopmostTrack = function() {
			return (self.track_groups[0].length > 0 ? self.track_groups[0][0] : self.track_groups[1][0]);
		};
		self.setTrackSortComparator = function(track_id, cmp) {
			self.tracks[track_id].config.sort_cmp = cmp;
		};
		self.getTrackSortComparator = function(track_id) {
			return self.tracks[track_id].config.sort_cmp;
		};
		self.getTrackSortDirection = function(track_id) {
			return self.sort_direction[track_id];
		};
		self.setTrackSortDirection = function(track_id, dir) {
			self.sort_direction[track_id] = dir;
			self.sort();
		};
		self.setTrackGroupSortOrder = function(order) {
			self.track_group_sort_order = order.slice();
		};
		self.getTrackGroupSortOrder = function() {
			return self.track_group_sort_order.slice();
		};
		self.getTrackSortOrder = function() {
			var ret = [];
			var track_groups = self.getTrackGroups();
			_.each(self.getTrackGroupSortOrder(), function(group_id) {
				ret = ret.concat(track_groups[group_id]);
			});
			return ret;
		};
		self.setSortConfig = function(config) {
			self.sort_config = config;
		};
		var sortById = function(desc) {
			var ret = _.sortBy(self.getIdOrder(), _.identity);
			if (desc) {
				ret.reverse();
			}
			self.setIdOrder(ret);
		};
		var sortByTrack = function() {
			var track_id_list = self.getTrackSortOrder();
			var cmp_list = _.map(track_id_list, function(track_id) {
				return self.getTrackSortComparator(track_id);
			});
			var data = {};
			var id_order = self.getIdOrder();
			_.each(id_order, function(id) {
				data[id] = {};
				_.each(track_id_list, function(track_id) {
					data[id][track_id] = self.getTrackDatum(track_id, id);
				});
			});
			var lexicographically_ordered_cmp = function(id1,id2) {
				var cmp_result = 0;
				for (var i=0, _len = track_id_list.length; i<_len; i++) {
					var track_id = track_id_list[i];
					var cmp = cmp_list[i];
					var d1 = data[id1][track_id];
					var d2 = data[id2][track_id];
					var d1_undef = (typeof d1 === "undefined");
					var d2_undef = (typeof d2 === "undefined");
					if (!d1_undef && !d2_undef) {
						cmp_result = cmp(d1, d2);
					} else if (d1_undef && d2_undef) {
						cmp_result = 0;
					} else if (d1_undef) {
						cmp_result = 1;
					} else {
						cmp_result = -1;
					}
					if (isFinite(cmp_result)) {
						// reverse direction unless infinite, which is a signal that an NA is involved
						cmp_result *= self.sort_direction[track_id];
					}
					if (cmp_result !== 0) {
						break;
					}
				}
				return cmp_result;
			};
			self.setIdOrder(utils.stableSort(self.getIdOrder(), lexicographically_ordered_cmp));
		};
		self.sort = function() {
			var config = self.sort_config;
			if (config.type === 'track') {
				sortByTrack();
			} else if (config.type === 'id') {
				sortById(config.desc);
			}
		};

		// Track Creation/Destruction
		self.addTrack = function(config, group) {
			group = utils.ifndef(group, 1);
			var track_id = getTrackId();
			self.tracks[track_id] ={id: track_id,
						data: [],
						config: $.extend({}, defaultTrackConfig, config),
						id_data_map: {}};
			self.track_groups[group].push(track_id);
			self.sort_direction[track_id] = 1;

			$(self).trigger(events.ADD_TRACK, {track_id: track_id});
			return track_id;
		};
		self.removeTrack = function(track_id) {
			var track = self.tracks[track_id];
			delete self.tracks[track_id];
			delete self.sort_direction[track_id];

			var track_group = self.getContainingTrackGroup(track_id, true);
			if (!track_group) {
				return false;
			} else {
				var old_position = track_group.indexOf(track_id);
				track_group.splice(old_position, 1);

				$(self).trigger(events.REMOVE_TRACK, {track: track, track_id: track_id});
				return true;
			}
		};

		// Track Ordering
		self.getTrackGroups = function(reference) {
			return (reference === true ? self.track_groups : $.extend(true, [], self.track_groups));
		};
		self.getTracks = function() {
			return _.flatten(self.getTrackGroups());
		};
		self.getContainingTrackGroup = function(track_id, reference) {
			var group = false;
			_.find(self.track_groups, function(grp) {
				if (grp.indexOf(track_id) > -1) {
					group = grp;
					return true;
				}
				return false;
			});
			return (reference === true ? group : group.slice());
		};
		self.moveTrack = function(track_id, new_position) {
			var track_group = self.getContainingTrackGroup(track_id, true);
			if (!track_group) {
				return false;
			}
			var old_position = track_group.indexOf(track_id);
			new_position = utils.clamp(new_position, 0, track_group.length-1);
			track_group.splice(old_position, 1);
			track_group.splice(new_position, 0, track_id);
			var moved_tracks = track_group.slice(Math.min(old_position, new_position), Math.max(old_position, new_position) + 1);
			$(self).trigger(events.MOVE_TRACK, {moved_tracks: moved_tracks});
		};

		// Track Label
		self.getTrackLabel = function(track_id) {
			return self.tracks[track_id].config.label;
		};

		// Track Tooltip
		self.getTrackTooltip = function(track_id) {
			return self.tracks[track_id].config.tooltip;
		};
		self.setTrackTooltip = function(track_id, tooltip) {
			self.tracks[track_id].config.tooltip = tooltip;
		};

		// Track Data
		self.getTrackData = function(track_id) {
			return self.tracks[track_id].data;
		};
		self.setTrackData = function(track_id, data) {
			var id_accessor = self.getTrackDatumIdAccessor(track_id);

			self.tracks[track_id].data = data;

			var current_id_order = self.getIdOrder();
			var current_inverted_id_order = self.getInvertedIdOrder();
			_.each(_.map(data, id_accessor), function(id) {
				if (!(id in current_inverted_id_order)) {
					current_id_order.push(id);
				}
			});
			self.setIdOrder(current_id_order);

			self.tracks[track_id].id_data_map = {};
			var id_data_map = self.tracks[track_id].id_data_map;
			_.each(self.tracks[track_id].data, function(datum) {
				id_data_map[id_accessor(datum)] = datum;
			});
			$(self).trigger(events.SET_TRACK_DATA, {track_id: track_id});
		};
		self.getTrackDatum = function(track_id, datum_id) {
			return self.tracks[track_id].id_data_map[datum_id];
		};
		self.getTrackDatumDataKey = function(track_id) {
			return self.tracks[track_id].config.datum_data_key;
		};

		// Track Datum Id
		self.getTrackDatumIdAccessor = function(track_id) {
			var key = self.getTrackDatumIdKey(track_id);
			return function(d) {
				return d[key];
			};
		};
		self.getTrackDatumIdKey = function(track_id) {
			return self.tracks[track_id].config.datum_id_key;
		};
		self.setTrackDatumIdKey = function(track_id, key) {
			self.tracks[track_id].config.datum_id_key = key;
		};

		// Track info
		self.isTrackRemovable = function(track_id) {
			return self.tracks[track_id].config.removable;
		};
		self.isTrackSortDirectionChangable = function(track_id) {
			return self.tracks[track_id].config.sort_direction_changable;
		};

		// Clearing
		self.clearData = function() {
			_.each(self.getTracks(), function(track_id) {
				self.setTrackData(track_id, []);
			});
			self.setIdOrder([]);
		}
	}

	return {
		CATEGORICAL_COLOR: RuleSet.CATEGORICAL_COLOR,
		GRADIENT_COLOR: RuleSet.GRADIENT_COLOR,
		GENETIC_ALTERATION: RuleSet.GENETIC_ALTERATION,
		BAR_CHART: RuleSet.BAR_CHART,
		create: function CreateOncoprint(container_selector_string, config) {
			config = $.extend({}, defaultOncoprintConfig, config || {});
			config = $.extend(config, hiddenOncoprintConfig);
			var oncoprint = new Oncoprint(config);
			var renderer = new OncoprintSVGRenderer(container_selector_string, oncoprint, {label_font: 'Arial', legend:config.legend});
			var ret = {
				onc_dev: oncoprint,
				ren_dev: renderer,
				addTrack: function(config, group) {
					var track_id = oncoprint.addTrack(config, group);
					return track_id;
				},
				removeTrack: function(track_id) {
					oncoprint.removeTrack(track_id);
				},
				moveTrack: function(track_id, position) {
					oncoprint.moveTrack(track_id, position);
				},
				setTrackDatumIdKey: function(track_id, key) {
					oncoprint.setTrackDatumIdKey(track_id, key);
				},
				setTrackData: function(track_id, data) {
					oncoprint.setTrackData(track_id, data);
				},
				setRuleSet: function(track_id, type, params) {
					renderer.setRuleSet(track_id, type, params);
				},
				useSameRuleSet: function(target_track_id, source_track_id) {
					renderer.useSameRuleSet(target_track_id, source_track_id);
				},
				toggleCellPadding: function() {
					oncoprint.toggleCellPadding();
				},
				toSVG: function() {
					return renderer.toSVG();
				},
				setTrackGroupSortOrder: function(order) {
					oncoprint.setTrackGroupSortOrder(order);
				},
				sort: function() {
					oncoprint.sort();
				},
				setSortConfig: function(config) {
					oncoprint.setSortConfig(config);
				},
				setIdOrder: function(id_order) {
					oncoprint.setIdOrder(id_order);
				},
				getTrackSortDirection: function(track_id) {
					return oncoprint.getTrackSortDirection(track_id);
				},
				setTrackSortDirection: function(track_id, dir) {
					oncoprint.setTrackSortDirection(track_id, dir);
				},
				setZoom: function(z) {
					return oncoprint.setZoom(z);
				},
				increaseZoom: function() {
					return oncoprint.increaseZoom();
				},
				decreaseZoom: function() {
					return oncoprint.decreaseZoom();
				},
				suppressRendering: function() {
					renderer.suppressRendering();
				},
				releaseRendering: function() {
					renderer.releaseRendering();
				},
				setLegendVisible: function(track_ids, visible) {
					renderer.setLegendVisible(track_ids, visible);
				},
				getFilteredIdOrder: function(data_filter_fn, track_ids) {
					return oncoprint.getFilteredIdOrder(data_filter_fn, track_ids);
				},
				getVisibleIdOrder: function() {
					return oncoprint.getVisibleIdOrder();
				},
				hideIds: function(ids) {
					oncoprint.hideIds(ids);
				},
				showIds: function(ids) {
					oncoprint.showIds(ids);
				},
				clearData: function() {
					oncoprint.clearData();
				},
				setTrackTooltip: function(track_id, tooltip) {
					oncoprint.setTrackTooltip(track_id, tooltip);
				}
			};
			$(oncoprint).on(events.MOVE_TRACK, function() {
				$(ret).trigger(events.MOVE_TRACK);
			});
			$(renderer).on(events.FINISHED_RENDERING, function() {
				$(ret).trigger(events.FINISHED_RENDERING);
			});
			$(oncoprint).on(events.REMOVE_TRACK, function(evt, data) {
				$(ret).trigger(events.REMOVE_TRACK, {track_id: data.track_id});
			});
			$(renderer).on(events.CONTENT_AREA_MOUSEENTER, function(evt, data) {
				$(ret).trigger(events.CONTENT_AREA_MOUSEENTER);
			});
			$(renderer).on(events.CONTENT_AREA_MOUSELEAVE, function(evt, data) {
				$(ret).trigger(events.CONTENT_AREA_MOUSELEAVE);
			});
			return ret;
		}
	};
})();

redpajama_set_name: RedPajamaGithub


text:
var http = require("http");
var url  = require('url');

var sys = require('sys');
var exec = require('child_process').exec;

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});

    var url_parts = url.parse(request.url, true);
    var query = url_parts.query;

    console.log(query.message);

    if (!query.message) return;

    response.write("Saying: ");
    response.write("" + query.message);

    child = exec('(say || espeak)', function (error, stdout, stderr) {
        if (error !== null) {
            console.log('exec error: ' + error);
            console.log("STDOUT: " + stdout);
            console.log("STDERR: " + stderr);
            response.write("ERROR: " + error);
            response.write("STDOUT: " + stdout);
            response.write("STDERR: " + stderr);
        }
    });
    child.stdin.end(query.message);

    response.end("");

    return query.message;
}).listen(8888);


text: include_recipe 'chef-dev-workstation::linux_setup'


text:
/*!
 * \file
 * \brief Tests using non-uniform arguments with traceRayExt().
 *//*--------------------------------------------------------------------*/

#include "vktRayTracingNonUniformArgsTests.hpp"
#include "vktTestCase.hpp"

#include "vkRayTracingUtil.hpp"
#include "vkObjUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkBarrierUtil.hpp"

#include "tcuTestLog.hpp"

#include <vector>
#include <iostream>

namespace vkt
{
namespace RayTracing
{
namespace
{

using namespace vk;

// Causes for hitting the miss shader due to argument values.
enum class MissCause
{
	NONE = 0,
	FLAGS,
	CULL_MASK,
	ORIGIN,
	TMIN,
	DIRECTION,
	TMAX,
	CAUSE_COUNT,
};

struct NonUniformParams
{
	bool miss;

	struct
	{
		deUint32	rayTypeCount;
		deUint32	rayType;
	} hitParams;

	struct
	{
		MissCause	missCause;
		deUint32	missIndex;
	} missParams;
};

class NonUniformArgsCase : public TestCase
{
public:
							NonUniformArgsCase		(tcu::TestContext& testCtx, const std::string& name, const std::string& description, const NonUniformParams& params);
	virtual					~NonUniformArgsCase		(void) {}

	virtual void			checkSupport			(Context& context) const;
	virtual void			initPrograms			(vk::SourceCollections& programCollection) const;
	virtual TestInstance*	createInstance			(Context& context) const;

protected:
	NonUniformParams		m_params;
};

class NonUniformArgsInstance : public TestInstance
{
public:
								NonUniformArgsInstance	(Context& context, const NonUniformParams& params);
	virtual						~NonUniformArgsInstance	(void) {}

	virtual tcu::TestStatus		iterate					(void);

protected:
	NonUniformParams			m_params;
};

NonUniformArgsCase::NonUniformArgsCase (tcu::TestContext& testCtx, const std::string& name, const std::string& description, const NonUniformParams& params)
	: TestCase	(testCtx, name, description)
	, m_params	(params)
{}

void NonUniformArgsCase::checkSupport (Context& context) const
{
	context.requireDeviceFunctionality("VK_KHR_acceleration_structure");
	context.requireDeviceFunctionality("VK_KHR_ray_tracing_pipeline");
}

struct ArgsBufferData
{
	tcu::Vec4	origin;
	tcu::Vec4	direction;
	float		Tmin;
	float		Tmax;
	deUint32	rayFlags;
	deUint32	cullMask;
	deUint32	sbtRecordOffset;
	deUint32	sbtRecordStride;
	deUint32	missIndex;
};

void NonUniformArgsCase::initPrograms (vk::SourceCollections& programCollection) const
{
	const ShaderBuildOptions buildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_4, 0u, true);

	std::ostringstream descriptors;
	descriptors
		<< "layout(set=0, binding=0) uniform accelerationStructureEXT topLevelAS;\n"
		<< "layout(set=0, binding=1, std430) buffer ArgumentsBlock {\n" // Must match ArgsBufferData.
		<< "  vec4  origin;\n"
		<< "  vec4  direction;\n"
		<< "  float Tmin;\n"
		<< "  float Tmax;\n"
		<< "  uint  rayFlags;\n"
		<< "  uint  cullMask;\n"
		<< "  uint  sbtRecordOffset;\n"
		<< "  uint  sbtRecordStride;\n"
		<< "  uint  missIndex;\n"
		<< "} args;\n"
		<< "layout(set=0, binding=2, std430) buffer ResultBlock {\n"
		<< "  uint shaderId;\n"
		<< "} result;\n"
		;
	const auto descriptorsStr = descriptors.str();

	std::ostringstream rgen;
	rgen
		<< "#version 460 core\n"
		<< "#extension GL_EXT_ray_tracing : require\n"
		<< "\n"
		<< descriptorsStr
		<< "layout(location=0) rayPayloadEXT vec4 unused;\n"
		<< "\n"
		<< "void main()\n"
		<< "{\n"
		<< "  traceRayEXT(topLevelAS,\n"
		<< "    args.rayFlags,\n"
		<< "    args.cullMask,\n"
		<< "    args.sbtRecordOffset,\n"
		<< "    args.sbtRecordStride,\n"
		<< "    args.missIndex,\n"
		<< "    args.origin.xyz,\n"
		<< "    args.Tmin,\n"
		<< "    args.direction.xyz,\n"
		<< "    args.Tmax,\n"
		<< "    0);\n"
		<< "}\n"
		;

	std::ostringstream chit;
	chit
		<< "#version 460 core\n"
		<< "#extension GL_EXT_ray_tracing : require\n"
		<< "\n"
		<< descriptorsStr
		<< "layout(constant_id=0) const uint chitShaderId = 0;\n"
		<< "layout(location=0) rayPayloadInEXT vec4 unused;\n"
		<< "\n"
		<< "void main()\n"
		<< "{\n"
		<< "  result.shaderId = chitShaderId;\n"
		<< "}\n"
		;

	std::ostringstream miss;
	miss
		<< "#version 460 core\n"
		<< "#extension GL_EXT_ray_tracing : require\n"
		<< "\n"
		<< descriptorsStr
		<< "layout(constant_id=0) const uint missShaderId = 0;\n"
		<< "layout(location=0) rayPayloadInEXT vec4 unused;\n"
		<< "\n"
		<< "void main()\n"
		<< "{\n"
		<< "  result.shaderId = missShaderId;\n"
		<< "}\n"
		;

	programCollection.glslSources.add("rgen") << glu::RaygenSource(rgen.str()) << buildOptions;
	programCollection.glslSources.add("chit") << glu::ClosestHitSource(chit.str()) << buildOptions;
	programCollection.glslSources.add("miss") << glu::MissSource(miss.str()) << buildOptions;
}

TestInstance* NonUniformArgsCase::createInstance (Context& context) const
{
	return new NonUniformArgsInstance(context, m_params);
}

NonUniformArgsInstance::NonUniformArgsInstance (Context& context, const NonUniformParams& params)
	: TestInstance	(context)
	, m_params		(params)
{}

deUint32 joinMostLeast (deUint32 most, deUint32 least)
{
	constexpr auto kMaxUint16 = static_cast<deUint32>(std::numeric_limits<deUint16>::max());
	DE_UNREF(kMaxUint16); // For release builds.
	DE_ASSERT(most <= kMaxUint16 && least <= kMaxUint16);
	return ((most << 16) | least);
}

deUint32 makeMissId (deUint32 missIndex)
{
	// 1 on the highest 16 bits for miss shaders.
	return joinMostLeast(1u, missIndex);
}

deUint32 makeChitId (deUint32 chitIndex)
{
	// 2 on the highest 16 bits for closest hit shaders.
	return joinMostLeast(2u, chitIndex);
}

tcu::TestStatus NonUniformArgsInstance::iterate (void)
{
	const auto&	vki		= m_context.getInstanceInterface();
	const auto	physDev	= m_context.getPhysicalDevice();
	const auto&	vkd		= m_context.getDeviceInterface();
	const auto	device	= m_context.getDevice();
	auto&		alloc	= m_context.getDefaultAllocator();
	const auto	qIndex	= m_context.getUniversalQueueFamilyIndex();
	const auto	queue	= m_context.getUniversalQueue();
	const auto	stages	= (VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR | VK_SHADER_STAGE_MISS_BIT_KHR);

	// Geometry data constants.
	const std::vector<tcu::Vec3> kOffscreenTriangle =
	{
		// Triangle around (x=0, y=2) z=-5
		tcu::Vec3( 0.0f, 2.5f, -5.0f),
		tcu::Vec3(-0.5f, 1.5f, -5.0f),
		tcu::Vec3( 0.5f, 1.5f, -5.0f),
	};
	const std::vector<tcu::Vec3> kOnscreenTriangle =
	{
		// Triangle around (x=0, y=2) z=5
		tcu::Vec3( 0.0f, 2.5f, 5.0f),
		tcu::Vec3(-0.5f, 1.5f, 5.0f),
		tcu::Vec3( 0.5f, 1.5f, 5.0f),
	};
	const tcu::Vec4		kGoodOrigin		(0.0f, 2.0f, 0.0f, 0.0f);	// Around (x=0, y=2) z=0.
	const tcu::Vec4		kBadOrigin		(0.0f, 8.0f, 0.0f, 0.0f);	// Too high, around (x=0, y=8) depth 0.
	const tcu::Vec4		kGoodDirection	(0.0f, 0.0f, 1.0f, 0.0f);	// Towards +z.
	const tcu::Vec4		kBadDirection	(1.0f, 0.0f, 0.0f, 0.0f);	// Towards +x.
	const float			kGoodTmin		= 4.0f;						// Good to travel from z=0 to z=5.
	const float			kGoodTmax		= 6.0f;						// Ditto.
	const float			kBadTmin		= 5.5f;						// Tmin after triangle.
	const float			kBadTmax		= 4.5f;						// Tmax before triangle.
	const deUint32		kGoodFlags		= 0u;						// MaskNone
	const deUint32		kBadFlags		= 256u;						// SkipTrianglesKHR
	const deUint32		kGoodCullMask	= 0x0Fu;					// Matches instance.
	const deUint32		kBadCullMask	= 0xF0u;					// Does not match instance.

	// Command pool and buffer.
	const auto cmdPool		= makeCommandPool(vkd, device, qIndex);
	const auto cmdBufferPtr	= allocateCommandBuffer(vkd, device, cmdPool.get(), VK_COMMAND_BUFFER_LEVEL_PRIMARY);
	const auto cmdBuffer	= cmdBufferPtr.get();

	beginCommandBuffer(vkd, cmdBuffer);

	// Build acceleration structures.
	auto topLevelAS		= makeTopLevelAccelerationStructure();
	auto bottomLevelAS	= makeBottomLevelAccelerationStructure();

	// Putting the offscreen triangle first makes sure hits have a geometryIndex=1, meaning sbtRecordStride matters.
	std::vector<const std::vector<tcu::Vec3>*> geometries;
	geometries.push_back(&kOffscreenTriangle);
	geometries.push_back(&kOnscreenTriangle);

	for (const auto& geometryPtr : geometries)
		bottomLevelAS->addGeometry(*geometryPtr, true /* is triangles */);

	bottomLevelAS->createAndBuild(vkd, device, cmdBuffer, alloc);

	de::SharedPtr<BottomLevelAccelerationStructure> blasSharedPtr (bottomLevelAS.release());
	topLevelAS->setInstanceCount(1);
	topLevelAS->addInstance(blasSharedPtr, identityMatrix3x4, 0u, kGoodCullMask, 0u, VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR);
	topLevelAS->createAndBuild(vkd, device, cmdBuffer, alloc);

	// Input storage buffer.
	const auto			inputBufferSize		= static_cast<VkDeviceSize>(sizeof(ArgsBufferData));
	const auto			inputBufferInfo		= makeBufferCreateInfo(inputBufferSize, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
	BufferWithMemory	inputBuffer			(vkd, device, alloc, inputBufferInfo, MemoryRequirement::HostVisible);
	auto&				inputBufferAlloc	= inputBuffer.getAllocation();

	// Output storage buffer.
	const auto			outputBufferSize	= static_cast<VkDeviceSize>(sizeof(deUint32));
	const auto			outputBufferInfo	= makeBufferCreateInfo(outputBufferSize, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
	BufferWithMemory	outputBuffer		(vkd, device, alloc, outputBufferInfo, MemoryRequirement::HostVisible);
	auto&				outputBufferAlloc	= outputBuffer.getAllocation();

	// Fill output buffer with an initial value.
	deMemset(outputBufferAlloc.getHostPtr(), 0, static_cast<size_t>(outputBufferSize));
	flushAlloc(vkd, device, outputBufferAlloc);

	// Descriptor set layout and pipeline layout.
	DescriptorSetLayoutBuilder setLayoutBuilder;
	setLayoutBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, stages);
	setLayoutBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, stages);
	setLayoutBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, stages);
	const auto setLayout		= setLayoutBuilder.build(vkd, device);
	const auto pipelineLayout	= makePipelineLayout(vkd, device, setLayout.get());

	// Descriptor pool and set.
	DescriptorPoolBuilder poolBuilder;
	poolBuilder.addType(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR);
	poolBuilder.addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2u);
	const auto descriptorPool	= poolBuilder.build(vkd, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
	const auto descriptorSet	= makeDescriptorSet(vkd, device, descriptorPool.get(), setLayout.get());

	// Update descriptor set.
	{
		const VkWriteDescriptorSetAccelerationStructureKHR accelDescInfo =
		{
			VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR,
			nullptr,
			1u,
			topLevelAS.get()->getPtr(),
		};

		const auto inputBufferDescInfo	= makeDescriptorBufferInfo(inputBuffer.get(), 0ull, VK_WHOLE_SIZE);
		const auto outputBufferDescInfo	= makeDescriptorBufferInfo(outputBuffer.get(), 0ull, VK_WHOLE_SIZE);

		DescriptorSetUpdateBuilder updateBuilder;
		updateBuilder.writeSingle(descriptorSet.get(), DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, &accelDescInfo);
		updateBuilder.writeSingle(descriptorSet.get(), DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &inputBufferDescInfo);
		updateBuilder.writeSingle(descriptorSet.get(), DescriptorSetUpdateBuilder::Location::binding(2u), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &outputBufferDescInfo);
		updateBuilder.update(vkd, device);
	}

	// Shader modules.
	auto rgenModule = makeVkSharedPtr(createShaderModule(vkd, device, m_context.getBinaryCollection().get("rgen"), 0));
	auto missModule = makeVkSharedPtr(createShaderModule(vkd, device, m_context.getBinaryCollection().get("miss"), 0));
	auto chitModule = makeVkSharedPtr(createShaderModule(vkd, device, m_context.getBinaryCollection().get("chit"), 0));

	// Get some ray tracing properties.
	deUint32 shaderGroupHandleSize		= 0u;
	deUint32 shaderGroupBaseAlignment	= 1u;
	{
		const auto rayTracingPropertiesKHR	= makeRayTracingProperties(vki, physDev);
		shaderGroupHandleSize				= rayTracingPropertiesKHR->getShaderGroupHandleSize();
		shaderGroupBaseAlignment			= rayTracingPropertiesKHR->getShaderGroupBaseAlignment();
	}

	// Create raytracing pipeline and shader binding tables.
	Move<VkPipeline>				pipeline;

	de::MovePtr<BufferWithMemory>	raygenSBT;
	de::MovePtr<BufferWithMemory>	missSBT;
	de::MovePtr<BufferWithMemory>	hitSBT;
	de::MovePtr<BufferWithMemory>	callableSBT;

	VkStridedDeviceAddressRegionKHR	raygenSBTRegion		= makeStridedDeviceAddressRegionKHR(DE_NULL, 0, 0);
	VkStridedDeviceAddressRegionKHR	missSBTRegion		= makeStridedDeviceAddressRegionKHR(DE_NULL, 0, 0);
	VkStridedDeviceAddressRegionKHR	hitSBTRegion		= makeStridedDeviceAddressRegionKHR(DE_NULL, 0, 0);
	VkStridedDeviceAddressRegionKHR	callableSBTRegion	= makeStridedDeviceAddressRegionKHR(DE_NULL, 0, 0);

	// Generate ids for the closest hit and miss shaders according to the test parameters.
	DE_ASSERT(m_params.hitParams.rayTypeCount > 0u);
	DE_ASSERT(m_params.hitParams.rayType < m_params.hitParams.rayTypeCount);
	DE_ASSERT(geometries.size() > 0u);

	std::vector<deUint32> missShaderIds;
	for (deUint32 missIdx = 0; missIdx <= m_params.missParams.missIndex; ++missIdx)
		missShaderIds.push_back(makeMissId(missIdx));

	deUint32				chitCounter		= 0u;
	std::vector<deUint32>	chitShaderIds;

	for (size_t geoIdx = 0; geoIdx < geometries.size(); ++geoIdx)
	for (deUint32 rayIdx = 0; rayIdx < m_params.hitParams.rayTypeCount; ++rayIdx)
		chitShaderIds.push_back(makeChitId(chitCounter++));

	{
		const auto						rayTracingPipeline		= de::newMovePtr<RayTracingPipeline>();
		const VkSpecializationMapEntry	specializationMapEntry	=
		{
			0u,											//	deUint32	constantID;
			0u,											//	deUint32	offset;
			static_cast<deUintptr>(sizeof(deUint32)),	//	deUintptr	size;
		};
		VkSpecializationInfo			specInfo				=
		{
			1u,											//	deUint32						mapEntryCount;
			&specializationMapEntry,					//	const VkSpecializationMapEntry*	pMapEntries;
			static_cast<deUintptr>(sizeof(deUint32)),	//	deUintptr						dataSize;
			nullptr,									//	const void*						pData;
		};

		std::vector<VkSpecializationInfo> specInfos;
		specInfos.reserve(missShaderIds.size() + chitShaderIds.size());

		deUint32 shaderGroupIdx = 0u;
		rayTracingPipeline->addShader(VK_SHADER_STAGE_RAYGEN_BIT_KHR, rgenModule, shaderGroupIdx++);

		for (size_t missIdx = 0; missIdx < missShaderIds.size(); ++missIdx)
		{
			specInfo.pData = &missShaderIds.at(missIdx);
			specInfos.push_back(specInfo);
			rayTracingPipeline->addShader(VK_SHADER_STAGE_MISS_BIT_KHR, missModule, shaderGroupIdx++, &specInfos.back());
		}

		const auto firstChitGroup = shaderGroupIdx;

		for (size_t chitIdx = 0; chitIdx < chitShaderIds.size(); ++chitIdx)
		{
			specInfo.pData = &chitShaderIds.at(chitIdx);
			specInfos.push_back(specInfo);
			rayTracingPipeline->addShader(VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, chitModule, shaderGroupIdx++, &specInfos.back());
		}

		pipeline = rayTracingPipeline->createPipeline(vkd, device, pipelineLayout.get());

		raygenSBT		= rayTracingPipeline->createShaderBindingTable(vkd, device, pipeline.get(), alloc, shaderGroupHandleSize, shaderGroupBaseAlignment, 0u, 1u);
		raygenSBTRegion	= makeStridedDeviceAddressRegionKHR(getBufferDeviceAddress(vkd, device, raygenSBT->get(), 0), shaderGroupHandleSize, shaderGroupHandleSize);

		missSBT			= rayTracingPipeline->createShaderBindingTable(vkd, device, pipeline.get(), alloc, shaderGroupHandleSize, shaderGroupBaseAlignment, 1u, static_cast<deUint32>(missShaderIds.size()));
		missSBTRegion	= makeStridedDeviceAddressRegionKHR(getBufferDeviceAddress(vkd, device, missSBT->get(), 0), shaderGroupHandleSize, shaderGroupHandleSize * missShaderIds.size());

		hitSBT			= rayTracingPipeline->createShaderBindingTable(vkd, device, pipeline.get(), alloc, shaderGroupHandleSize, shaderGroupBaseAlignment, firstChitGroup, static_cast<deUint32>(chitShaderIds.size()));
		hitSBTRegion	= makeStridedDeviceAddressRegionKHR(getBufferDeviceAddress(vkd, device, hitSBT->get(), 0), shaderGroupHandleSize, shaderGroupHandleSize * chitShaderIds.size());
	}

	// Fill input buffer values.
	{
		DE_ASSERT(!(m_params.miss && m_params.missParams.missCause == MissCause::NONE));

		const ArgsBufferData argsBufferData =
		{
			((m_params.miss && m_params.missParams.missCause == MissCause::ORIGIN)		? kBadOrigin	: kGoodOrigin),
			((m_params.miss && m_params.missParams.missCause == MissCause::DIRECTION)	? kBadDirection	: kGoodDirection),
			((m_params.miss && m_params.missParams.missCause == MissCause::TMIN)		? kBadTmin		: kGoodTmin),
			((m_params.miss && m_params.missParams.missCause == MissCause::TMAX)		? kBadTmax		: kGoodTmax),
			((m_params.miss && m_params.missParams.missCause == MissCause::FLAGS)		? kBadFlags		: kGoodFlags),
			((m_params.miss && m_params.missParams.missCause == MissCause::CULL_MASK)	? kBadCullMask	: kGoodCullMask),
			m_params.hitParams.rayType,
			m_params.hitParams.rayTypeCount,
			m_params.missParams.missIndex,
		};

		deMemcpy(inputBufferAlloc.getHostPtr(), &argsBufferData, sizeof(argsBufferData));
		flushAlloc(vkd, device, inputBufferAlloc);
	}

	// Trace rays.
	vkd.cmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline.get());
	vkd.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipelineLayout.get(), 0u, 1u, &descriptorSet.get(), 0u, nullptr);
	vkd.cmdTraceRaysKHR(cmdBuffer, &raygenSBTRegion, &missSBTRegion, &hitSBTRegion, &callableSBTRegion, 1u, 1u, 1u);

	// Barrier for the output buffer.
	const auto bufferBarrier = makeMemoryBarrier(VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
	vkd.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR, VK_PIPELINE_STAGE_HOST_BIT, 0u, 1u, &bufferBarrier, 0u, nullptr, 0u, nullptr);

	endCommandBuffer(vkd, cmdBuffer);
	submitCommandsAndWait(vkd, device, queue, cmdBuffer);

	// Check output value.
	invalidateAlloc(vkd, device, outputBufferAlloc);
	deUint32 outputVal = std::numeric_limits<deUint32>::max();
	deMemcpy(&outputVal, outputBufferAlloc.getHostPtr(), sizeof(outputVal));
	const auto expectedVal = (m_params.miss ? makeMissId(m_params.missParams.missIndex) : makeChitId(m_params.hitParams.rayTypeCount + m_params.hitParams.rayType));

	std::ostringstream msg;
	msg << "Output value: 0x" << std::hex << outputVal << " (expected 0x" << expectedVal << ")";

	if (outputVal != expectedVal)
		return tcu::TestStatus::fail(msg.str());

	auto& log = m_context.getTestContext().getLog();
	log << tcu::TestLog::Message << msg.str() << tcu::TestLog::EndMessage;

	return tcu::TestStatus::pass("Pass");
}

} // anonymous

tcu::TestCaseGroup*	createNonUniformArgsTests (tcu::TestContext& testCtx)
{
	de::MovePtr<tcu::TestCaseGroup> nonUniformGroup(new tcu::TestCaseGroup(testCtx, "non_uniform_args", "Test non-uniform arguments in traceRayExt()"));

	// Closest hit cases.
	{
		NonUniformParams params;
		params.miss = false;
		params.missParams.missIndex = 0u;
		params.missParams.missCause = MissCause::NONE;

		for (deUint32 typeCount = 1u; typeCount <= 4u; ++typeCount)
		{
			params.hitParams.rayTypeCount = typeCount;
			for (deUint32 rayType = 0u; rayType < typeCount; ++rayType)
			{
				params.hitParams.rayType = rayType;
				nonUniformGroup->addChild(new NonUniformArgsCase(testCtx, "chit_" + de::toString(typeCount) + "_types_" + de::toString(rayType), "", params));
			}
		}
	}

	// Miss cases.
	{
		NonUniformParams params;
		params.miss = true;
		params.hitParams.rayTypeCount = 1u;
		params.hitParams.rayType = 0u;

		for (int causeIdx = static_cast<int>(MissCause::NONE) + 1; causeIdx < static_cast<int>(MissCause::CAUSE_COUNT); ++causeIdx)
		{
			params.missParams.missCause = static_cast<MissCause>(causeIdx);
			params.missParams.missIndex = static_cast<deUint32>(causeIdx-1);
			nonUniformGroup->addChild(new NonUniformArgsCase(testCtx, "miss_cause_" + de::toString(causeIdx), "", params));
		}
	}

	return nonUniformGroup.release();
}

}	// RayTracing
}	// vkt


text:
<?php // phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact

declare(strict_types=1);

namespace Mwop\App;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Throwable;

class LoggingErrorListener
{
   /**
    * Log message string with placeholders
    */
    private const LOG_STRING = '{status} [{method}] {uri}: {error}';

    public function __construct(private LoggerInterface $logger)
    {
    }

    public function __invoke(
        Throwable $error,
        ServerRequestInterface $request,
        ResponseInterface $response
    ) {
        $this->logger->error(self::LOG_STRING, [
            'status' => $response->getStatusCode(),
            'method' => $request->getMethod(),
            'uri'    => (string) $request->getUri(),
            'error'  => $error->getMessage(),
        ]);
    }
}


text:
extern "C" {
    __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
}
#endif

#if !defined(APIENTRYP)
#   define APIENTRYP APIENTRY *
#endif

#if defined(DEBUG_GL)
#   define GL_CHECK(SPEC, ...) debugCheck((SPEC), __func__, file, line, __VA_ARGS__)
#else
#   define GL_CHECK(...)
#endif

typedef GLuint (APIENTRYP MYPFNGLCREATESHADERPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLSHADERSOURCEPROC)(GLuint, GLsizei, const GLchar**, const GLint*);
typedef void (APIENTRYP MYPFNGLCOMPILESHADERPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLATTACHSHADERPROC)(GLuint, GLuint);
typedef GLuint (APIENTRYP MYPFNGLCREATEPROGRAMPROC)();
typedef void (APIENTRYP MYPFNGLLINKPROGRAMPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLUSEPROGRAMPROC)(GLuint);
typedef GLint (APIENTRYP MYPFNGLGETUNIFORMLOCATIONPROC)(GLuint, const GLchar*);
typedef void (APIENTRYP MYPFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLUNIFORMMATRIX4FVPROC)(GLint, GLsizei, GLboolean, const GLfloat*);
typedef void (APIENTRYP MYPFNGLBINDBUFFERPROC)(GLenum, GLuint);
typedef void (APIENTRYP MYPFNGLGENBUFFERSPROC)(GLsizei, GLuint*);
typedef void (APIENTRYP MYPFNGLVERTEXATTRIBPOINTERPROC)(GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid*);
typedef void (APIENTRYP MYPFNGLBUFFERDATAPROC)(GLenum, GLsizeiptr, const GLvoid*, GLenum);
typedef void (APIENTRYP MYPFNGLVALIDATEPROGRAMPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLGENVERTEXARRAYSPROC)(GLsizei, GLuint*);
typedef void (APIENTRYP MYPFNGLBINDVERTEXARRAYPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLDELETEPROGRAMPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLDELETEBUFFERSPROC)(GLsizei, const GLuint*);
typedef void (APIENTRYP MYPFNGLDELETEVERTEXARRAYSPROC)(GLsizei, const GLuint*);
typedef void (APIENTRYP MYPFNGLUNIFORM1IPROC)(GLint, GLint);
typedef void (APIENTRYP MYPFNGLUNIFORM2IPROC)(GLint, GLint, GLint);
typedef void (APIENTRYP MYPFNGLUNIFORM1FPROC)(GLint, GLfloat);
typedef void (APIENTRYP MYPFNGLUNIFORM2FPROC)(GLint, GLfloat, GLfloat);
typedef void (APIENTRYP MYPFNGLUNIFORM2FVPROC)(GLint, GLsizei, const GLfloat*);
typedef void (APIENTRYP MYPFNGLUNIFORM3FVPROC)(GLint, GLsizei, const GLfloat*);
typedef void (APIENTRYP MYPFNGLUNIFORM4FVPROC)(GLint, GLsizei, const GLfloat*);
typedef void (APIENTRYP MYPFNGLUNIFORMMATRIX3X4FVPROC)(GLint, GLsizei, GLboolean, const GLfloat*);
typedef void (APIENTRYP MYPFNGLGENERATEMIPMAPPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLDELETESHADERPROC)(GLuint);
typedef void (APIENTRYP MYPFNGLGETSHADERIVPROC)(GLuint, GLenum, GLint*);
typedef void (APIENTRYP MYPFNGLGETPROGRAMIVPROC)(GLuint, GLenum, GLint*);
typedef void (APIENTRYP MYPFNGLGETSHADERINFOLOGPROC)(GLuint, GLsizei, GLsizei*, GLchar*);
typedef void (APIENTRYP MYPFNGLACTIVETEXTUREPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLGENFRAMEBUFFERSPROC)(GLsizei, GLuint*);
typedef void (APIENTRYP MYPFNGLBINDFRAMEBUFFERPROC)(GLenum, GLuint);
typedef void (APIENTRYP MYPFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum, GLenum, GLenum, GLuint, GLint);
typedef void (APIENTRYP MYPFNGLDRAWBUFFERSPROC)(GLsizei, const GLenum*);
typedef GLenum (APIENTRYP MYPFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLDELETEFRAMEBUFFERSPROC)(GLsizei, const GLuint*);
typedef void (APIENTRYP MYPFNGLCLEARPROC)(GLbitfield);
typedef void (APIENTRYP MYPFNGLCLEARCOLORPROC)(GLfloat, GLfloat, GLfloat, GLfloat);
typedef void (APIENTRYP MYPFNGLFRONTFACEPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLCULLFACEPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLENABLEPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLDISABLEPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLDRAWELEMENTSPROC)(GLenum, GLsizei, GLenum, const GLvoid*);
typedef void (APIENTRYP MYPFNGLDEPTHMASKPROC)(GLboolean);
typedef void (APIENTRYP MYPFNGLBINDTEXTUREPROC)(GLenum, GLuint);
typedef void (APIENTRYP MYPFNGLTEXIMAGE2DPROC)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*);
typedef void (APIENTRYP MYPFNGLDELETETEXTURESPROC)(GLsizei, const GLuint*);
typedef void (APIENTRYP MYPFNGLGENTEXTURESPROC)(GLsizei, GLuint*);
typedef void (APIENTRYP MYPFNGLTEXPARAMETERFPROC)(GLenum, GLenum, GLfloat);
typedef void (APIENTRYP MYPFNGLTEXPARAMETERIPROC)(GLenum, GLenum, GLint);
typedef void (APIENTRYP MYPFNGLDRAWARRAYSPROC)(GLenum, GLint, GLsizei);
typedef void (APIENTRYP MYPFNGLBLENDEQUATIONPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLBLENDFUNCPROC)(GLenum, GLenum);
typedef void (APIENTRYP MYPFNGLDEPTHFUNCPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLCOLORMASKPROC)(GLboolean, GLboolean, GLboolean, GLboolean);
typedef void (APIENTRYP MYPFNGLREADPIXELSPROC)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoid*);
typedef void (APIENTRYP MYPFNGLVIEWPORTPROC)(GLint, GLint, GLsizei, GLsizei);
typedef void (APIENTRYP MYPFNGLGETINTEGERVPROC)(GLenum, GLint*);
typedef const GLubyte* (APIENTRYP MYPFNGLGETSTRINGPROC)(GLenum);
typedef const GLubyte* (APIENTRYP MYPFNGLGETSTRINGIPROC)(GLenum, GLuint);
typedef void (APIENTRYP MYPFNGLGETFLOATVPROC)(GLenum, GLfloat*);
typedef GLenum (APIENTRYP MYPFNGLGETERRORPROC)();
typedef void (APIENTRYP MYPFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum, GLint, GLenum, GLint*);
typedef void (APIENTRYP MYPFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum, GLint, GLvoid*);
typedef void (APIENTRYP MYPFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*);
typedef void (APIENTRYP MYPFNGLPIXELSTOREIPROC)(GLenum, GLint);
typedef void (APIENTRYP MYPFNGLSCISSORPROC)(GLint, GLint, GLsizei, GLsizei);
typedef void (APIENTRYP MYPFNGLPOLYGONMODEPROC)(GLenum, GLenum);
typedef void (APIENTRYP MYPFNGLHINTPROC)(GLenum, GLenum);
typedef void (APIENTRYP MYPFNGLGENQUERIESPROC)(GLsizei, GLuint*);
typedef void (APIENTRYP MYPFNGLBEGINQUERYPROC)(GLenum, GLuint);
typedef void (APIENTRYP MYPFNGLENDQUERYPROC)(GLenum, GLuint);
typedef void (APIENTRYP MYPFNGLDELETEQUERIESPROC)(GLsizei, const GLuint*);
typedef void (APIENTRYP MYPFNGLGETQUERYOBJECTUIVPROC)(GLuint, GLenum, GLuint*);
typedef void (APIENTRYP MYPFNGLFLUSHPROC)();
typedef void (APIENTRYP MYPFNGLSTENCILFUNCPROC)(GLenum, GLint, GLuint);
typedef void (APIENTRYP MYPFNGLSTENCILOPPROC)(GLenum, GLenum, GLenum);
typedef void (APIENTRYP MYPFNGLTEXIMAGE3DPROC)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*);
typedef void (APIENTRYP MYPFNGLTEXSUBIMAGE3DPROC)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
typedef void (APIENTRYP MYPFNGLGETPROGRAMINFOLOGPROC)(GLuint, GLsizei, GLsizei*, GLchar*);
typedef void (APIENTRYP MYPFNGLBINDATTRIBLOCATIONPROC)(GLuint, GLuint, const GLchar*);
typedef void (APIENTRYP MYPFNGLBINDFRAGDATALOCATIONPROC)(GLuint, GLuint, const GLchar*);
typedef void (APIENTRYP MYPFNGLTEXSUBIMAGE2DPROC)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*);
typedef void (APIENTRYP MYPFNGLDRAWBUFFERPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLREADBUFFERPROC)(GLenum);
typedef void (APIENTRYP MYPFNGLBUFFERSUBDATAPROC)(GLenum, GLintptr, GLsizeiptr, const GLvoid*);
typedef void (APIENTRYP MYPFNGLPOLYGONOFFSETPROC)(GLfloat, GLfloat);
typedef void (APIENTRYP MYPFNGLDEPTHRANGEPROC)(GLclampd, GLclampd);
typedef void (APIENTRYP MYPFNGLPROGRAMPARAMETERIPROC)(GLuint, GLenum, GLint);
typedef void (APIENTRYP MYPFNGLGETPROGRAMBINARYPROC)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*);
typedef void (APIENTRYP MYPFNGLPROGRAMBINARYPROC)(GLuint, GLenum, const GLvoid*, GLsizei);

static MYPFNGLCREATESHADERPROC              glCreateShader_             = nullptr;
static MYPFNGLSHADERSOURCEPROC              glShaderSource_             = nullptr;
static MYPFNGLCOMPILESHADERPROC             glCompileShader_            = nullptr;
static MYPFNGLATTACHSHADERPROC              glAttachShader_             = nullptr;
static MYPFNGLCREATEPROGRAMPROC             glCreateProgram_            = nullptr;
static MYPFNGLLINKPROGRAMPROC               glLinkProgram_              = nullptr;
static MYPFNGLUSEPROGRAMPROC                glUseProgram_               = nullptr;
static MYPFNGLGETUNIFORMLOCATIONPROC        glGetUniformLocation_       = nullptr;
static MYPFNGLENABLEVERTEXATTRIBARRAYPROC   glEnableVertexAttribArray_  = nullptr;
static MYPFNGLDISABLEVERTEXATTRIBARRAYPROC  glDisableVertexAttribArray_ = nullptr;
static MYPFNGLUNIFORMMATRIX4FVPROC          glUniformMatrix4fv_         = nullptr;
static MYPFNGLBINDBUFFERPROC                glBindBuffer_               = nullptr;
static MYPFNGLGENBUFFERSPROC                glGenBuffers_               = nullptr;
static MYPFNGLVERTEXATTRIBPOINTERPROC       glVertexAttribPointer_      = nullptr;
static MYPFNGLBUFFERDATAPROC                glBufferData_               = nullptr;
static MYPFNGLVALIDATEPROGRAMPROC           glValidateProgram_          = nullptr;
static MYPFNGLGENVERTEXARRAYSPROC           glGenVertexArrays_          = nullptr;
static MYPFNGLBINDVERTEXARRAYPROC           glBindVertexArray_          = nullptr;
static MYPFNGLDELETEPROGRAMPROC             glDeleteProgram_            = nullptr;
static MYPFNGLDELETEBUFFERSPROC             glDeleteBuffers_            = nullptr;
static MYPFNGLDELETEVERTEXARRAYSPROC        glDeleteVertexArrays_       = nullptr;
static MYPFNGLUNIFORM1IPROC                 glUniform1i_                = nullptr;
static MYPFNGLUNIFORM2IPROC                 glUniform2i_                = nullptr;
static MYPFNGLUNIFORM1FPROC                 glUniform1f_                = nullptr;
static MYPFNGLUNIFORM2FPROC                 glUniform2f_                = nullptr;
static MYPFNGLUNIFORM2FVPROC                glUniform2fv_               = nullptr;
static MYPFNGLUNIFORM3FVPROC                glUniform3fv_               = nullptr;
static MYPFNGLUNIFORM4FVPROC                glUniform4fv_               = nullptr;
static MYPFNGLUNIFORMMATRIX3X4FVPROC        glUniformMatrix3x4fv_       = nullptr;
static MYPFNGLGENERATEMIPMAPPROC            glGenerateMipmap_           = nullptr;
static MYPFNGLDELETESHADERPROC              glDeleteShader_             = nullptr;
static MYPFNGLGETSHADERIVPROC               glGetShaderiv_              = nullptr;
static MYPFNGLGETPROGRAMIVPROC              glGetProgramiv_             = nullptr;
static MYPFNGLGETSHADERINFOLOGPROC          glGetShaderInfoLog_         = nullptr;
static MYPFNGLACTIVETEXTUREPROC             glActiveTexture_            = nullptr;
static MYPFNGLGENFRAMEBUFFERSPROC           glGenFramebuffers_          = nullptr;
static MYPFNGLBINDFRAMEBUFFERPROC           glBindFramebuffer_          = nullptr;
static MYPFNGLFRAMEBUFFERTEXTURE2DPROC      glFramebufferTexture2D_     = nullptr;
static MYPFNGLDRAWBUFFERSPROC               glDrawBuffers_              = nullptr;
static MYPFNGLCHECKFRAMEBUFFERSTATUSPROC    glCheckFramebufferStatus_   = nullptr;
static MYPFNGLDELETEFRAMEBUFFERSPROC        glDeleteFramebuffers_       = nullptr;
static MYPFNGLCLEARPROC                     glClear_                    = nullptr;
static MYPFNGLCLEARCOLORPROC                glClearColor_               = nullptr;
static MYPFNGLFRONTFACEPROC                 glFrontFace_                = nullptr;
static MYPFNGLCULLFACEPROC                  glCullFace_                 = nullptr;
static MYPFNGLENABLEPROC                    glEnable_                   = nullptr;
static MYPFNGLDISABLEPROC                   glDisable_                  = nullptr;
static MYPFNGLDRAWELEMENTSPROC              glDrawElements_             = nullptr;
static MYPFNGLDEPTHMASKPROC                 glDepthMask_                = nullptr;
static MYPFNGLBINDTEXTUREPROC               glBindTexture_              = nullptr;
static MYPFNGLTEXIMAGE2DPROC                glTexImage2D_               = nullptr;
static MYPFNGLDELETETEXTURESPROC            glDeleteTextures_           = nullptr;
static MYPFNGLGENTEXTURESPROC               glGenTextures_              = nullptr;
static MYPFNGLTEXPARAMETERFPROC             glTexParameterf_            = nullptr;
static MYPFNGLTEXPARAMETERIPROC             glTexParameteri_            = nullptr;
static MYPFNGLDRAWARRAYSPROC                glDrawArrays_               = nullptr;
static MYPFNGLBLENDEQUATIONPROC             glBlendEquation_            = nullptr;
static MYPFNGLBLENDFUNCPROC                 glBlendFunc_                = nullptr;
static MYPFNGLDEPTHFUNCPROC                 glDepthFunc_                = nullptr;
static MYPFNGLCOLORMASKPROC                 glColorMask_                = nullptr;
static MYPFNGLREADPIXELSPROC                glReadPixels_               = nullptr;
static MYPFNGLVIEWPORTPROC                  glViewport_                 = nullptr;
static MYPFNGLGETINTEGERVPROC               glGetIntegerv_              = nullptr;
static MYPFNGLGETSTRINGPROC                 glGetString_                = nullptr;
static MYPFNGLGETSTRINGIPROC                glGetStringi_               = nullptr;
static MYPFNGLGETFLOATVPROC                 glGetFloatv_                = nullptr;
static MYPFNGLGETERRORPROC                  glGetError_                 = nullptr;
static MYPFNGLGETTEXLEVELPARAMETERIVPROC    glGetTexLevelParameteriv_   = nullptr;
static MYPFNGLGETCOMPRESSEDTEXIMAGEPROC     glGetCompressedTexImage_    = nullptr;
static MYPFNGLCOMPRESSEDTEXIMAGE2DPROC      glCompressedTexImage2D_     = nullptr;
static MYPFNGLPIXELSTOREIPROC               glPixelStorei_              = nullptr;
static MYPFNGLSCISSORPROC                   glScissor_                  = nullptr;
static MYPFNGLPOLYGONMODEPROC               glPolygonMode_              = nullptr;
static MYPFNGLHINTPROC                      glHint_                     = nullptr;
static MYPFNGLGENQUERIESPROC                glGenQueries_               = nullptr;
static MYPFNGLBEGINQUERYPROC                glBeginQuery_               = nullptr;
static MYPFNGLENDQUERYPROC                  glEndQuery_                 = nullptr;
static MYPFNGLDELETEQUERIESPROC             glDeleteQueries_            = nullptr;
static MYPFNGLGETQUERYOBJECTUIVPROC         glGetQueryObjectuiv_        = nullptr;
static MYPFNGLFLUSHPROC                     glFlush_                    = nullptr;
static MYPFNGLSTENCILFUNCPROC               glStencilFunc_              = nullptr;
static MYPFNGLSTENCILOPPROC                 glStencilOp_                = nullptr;
static MYPFNGLTEXIMAGE3DPROC                glTexImage3D_               = nullptr;
static MYPFNGLTEXSUBIMAGE3DPROC             glTexSubImage3D_            = nullptr;
static MYPFNGLGETPROGRAMINFOLOGPROC         glGetProgramInfoLog_        = nullptr;
static MYPFNGLBINDATTRIBLOCATIONPROC        glBindAttribLocation_       = nullptr;
static MYPFNGLBINDFRAGDATALOCATIONPROC      glBindFragDataLocation_     = nullptr;
static MYPFNGLTEXSUBIMAGE2DPROC             glTexSubImage2D_            = nullptr;
static MYPFNGLDRAWBUFFERPROC                glDrawBuffer_               = nullptr;
static MYPFNGLREADBUFFERPROC                glReadBuffer_               = nullptr;
static MYPFNGLBUFFERSUBDATAPROC             glBufferSubData_            = nullptr;
static MYPFNGLPOLYGONOFFSETPROC             glPolygonOffset_            = nullptr;
static MYPFNGLDEPTHRANGEPROC                glDepthRange_               = nullptr;
static MYPFNGLPROGRAMPARAMETERIPROC         glProgramParameteri_        = nullptr;
static MYPFNGLGETPROGRAMBINARYPROC          glGetProgramBinary_         = nullptr;
static MYPFNGLPROGRAMBINARYPROC             glProgramBinary_            = nullptr;

#if defined(DEBUG_GL)
///! ARB_debug_output
typedef void (APIENTRYP MYPFNGLDEBUGMESSAGECALLBACKARBPROC)(
    void (APIENTRYP)(GLenum, GLenum, GLuint, GLenum, GLsizei, const GLchar *, GLvoid *),
    const GLvoid *);

template <char C, typename T>
u::string stringize(T, char base='?');

template<>
u::string stringize<'1', GLchar>(GLchar value, char) {
    return u::format("GLchar=%c", value);
}
template<>
u::string stringize<'2', GLenum>(GLenum value, char) {
    return u::format("GLenum=0x%X", value);
}
template<>
u::string stringize<'3', GLboolean>(GLboolean value, char) {
    return u::format("GLboolean=%c", value);
}
template<>
u::string stringize<'4', GLbitfield>(GLbitfield value, char) {
    return u::format("GLbitfield=%u", value);
}
template<>
u::string stringize<'5', GLbyte>(GLbyte value, char) {
    return u::format("GLbyte=%x", value);
}
template<>
u::string stringize<'6', GLshort>(GLshort value, char) {
    return u::format("GLshort=%d", value);
}
template<>
u::string stringize<'7', GLint>(GLint value, char) {
    return u::format("GLint=%d", value);
}
template<>
u::string stringize<'8', GLsizei>(GLsizei value, char) {
    return u::format("GLsizei=%d", value);
}
template<>
u::string stringize<'9', GLubyte>(GLubyte value, char) {
    return u::format("GLubyte=%X", value);
}
template<>
u::string stringize<'a', GLushort>(GLushort value, char) {
    return u::format("GLushort=%u", value);
}
template<>
u::string stringize<'b', GLuint>(GLuint value, char) {
    return u::format("GLuint=%u", value);
}
template<>
u::string stringize<'c', GLfloat>(GLfloat value, char) {
    return u::format("GLfloat=%.2f", value);
}
template<>
u::string stringize<'d', GLclampf>(GLclampf value, char) {
    return u::format("GLclampf=%f", value);
}
template<>
u::string stringize<'e', GLintptr>(GLintptr value, char) {
    return u::format("GLintptr=%p", value);
}
template<>
u::string stringize<'f', GLsizeiptr>(GLsizeiptr value, char) {
    return u::format("GLsizeiptr=%p", value);
}
template<>
u::string stringize<'g', GLclampd>(GLclampd value, char) {
    return u::format("GLclampd=%.2f", value);
}
template <>
u::string stringize<'*', void *>(void *value, char base) {
    switch (base) {
        case '?': return "unknown";
        case '0': return u::format("GLvoid*=%p", value);
        case '1': return u::format("GLchar*=%p", value);
        case '2': return u::format("GLenum*=%p", value);
        case '3': return u::format("GLboolean*=%p", value);
        case '4': return u::format("GLbitfield*=%p", value);
        case '5': return u::format("GLbyte*=%p", value);
        case '6': return u::format("GLshort*=%p", value);
        case '7': return u::format("GLint*=%p", value);
        case '8': return u::format("GLsizei*=%p", value);
        case '9': return u::format("GLubyte*=%p", value);
        case 'a': return u::format("GLushort*=%p", value);
        case 'b': return u::format("GLuint*=%p", value);
        case 'c': return u::format("GLfloat*=%p", value);
        case 'd': return u::format("GLclampf*=%p", value);
        case 'e': return u::format("GLintptr*=%p", value);
        case 'f': return u::format("GLsizeiptr*=%p", value);
        case 'g': return u::format("GLclampd*=%p", value);
    }

    return u::format("GLchar*=\"%s\"", (const char *)value);
}

static const char *debugErrorString(GLenum error) {
    switch (error) {
        case GL_INVALID_ENUM:
            return "GL_INVALID_ENUM";
        case GL_INVALID_VALUE:
            return "GL_INVALID_VALUE";
        case GL_INVALID_OPERATION:
            return "GL_INVALID_OPERATION";
        case GL_INVALID_FRAMEBUFFER_OPERATION:
            return "GL_INVALID_FRAMEBUFFER_OPERATION";
    }
    return "unknown";
}

static void debugCheck(const char *spec, const char *function, const char *file, size_t line, ...) {
    GLenum error = glGetError_();
    if (error == GL_NO_ERROR)
        return;

    va_list va;
    va_start(va, line);
    u::string contents;

    for (const char *s = spec; *s; s++) {
        switch (*s) {
            case '1':
                contents += stringize<'1'>((GLchar)va_arg(va, int));
                break;
            case '2':
                contents += stringize<'2'>((GLenum)va_arg(va, unsigned int));
                break;
            case '3':
                contents += stringize<'3'>((GLboolean)va_arg(va, int));
                break;
            case '4':
                contents += stringize<'4'>((GLbitfield)va_arg(va, unsigned int));
                break;
            case '5':
                contents += stringize<'5'>((GLbyte)va_arg(va, int));
                break;
            case '6':
                contents += stringize<'6'>((GLshort)va_arg(va, int));
                break;
            case '7':
                contents += stringize<'7'>((GLint)va_arg(va, int));
                break;
            case '8':
                contents += stringize<'8'>((GLsizei)va_arg(va, int));
                break;
            case '9':
                contents += stringize<'9'>((GLubyte)va_arg(va, unsigned int));
                break;
            case 'a':
                contents += stringize<'a'>((GLushort)va_arg(va, unsigned int));
                break;
            case 'b':
                contents += stringize<'b'>((GLuint)va_arg(va, unsigned int));
                break;
            case 'c':
                contents += stringize<'c'>((GLfloat)va_arg(va, double));
                break;
            case 'd':
                contents += stringize<'d'>((GLclampf)va_arg(va, double));
                break;
            case 'e':
                contents += stringize<'e'>((GLintptr)va_arg(va, intptr_t));
                break;
            case 'f':
                contents += stringize<'f'>((GLsizeiptr)va_arg(va, intptr_t));
                break;
            case 'g':
                contents += stringize<'g'>((GLclampd)va_arg(va, double));
                break;
            case '*':
                contents += stringize<'*'>(va_arg(va, void *), s[1]);
                s++; // skip basetype spec
                break;
        }
        if (s[1])
            contents += ", ";
    }
    va_end(va);
    u::fprint(stderr, "error %s(%s) (%s:%zu) %s\n", function, contents,
        file, line, debugErrorString(error));
}

static inline const char *debugSource(GLenum source) {
    switch (source) {
    case GL_DEBUG_SOURCE_API_ARB:             return "API";
    case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:   return "windowing system";
    case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: return "shader compiler";
    case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:     return "third party";
    case GL_DEBUG_SOURCE_OTHER_ARB:           return "other";
    }
    return "unknown";
}

static inline const char *debugType(GLenum type) {
    switch (type) {
    case GL_DEBUG_TYPE_ERROR_ARB:               return "error";
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: return "deprecated behavior";
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:  return "undefined behavior";
    case GL_DEBUG_TYPE_PORTABILITY_ARB:         return "portability";
    case GL_DEBUG_TYPE_PERFORMANCE_ARB:         return "performance";
    case GL_DEBUG_TYPE_OTHER_ARB:               return "other";
    }
    return "unknown";
}

static inline const char *debugSeverity(GLenum type) {
    switch (type) {
    case GL_DEBUG_SEVERITY_HIGH_ARB:   return "high";
    case GL_DEBUG_SEVERITY_MEDIUM_ARB: return "medium";
    case GL_DEBUG_SEVERITY_LOW_ARB:    return "low";
    }
    return "unknown";
}

static void APIENTRY debugCallback(GLenum source, GLenum type, GLuint, GLenum severity,
    GLsizei, const GLchar *message, GLvoid *)
{
    u::fprint(stderr, "%s with %s severity = %s (%s)", debugType(type),
        debugSource(source), debugSeverity(severity), message);
}
#endif

namespace gl {

static u::set<size_t> gExtensions;
static const char *kExtensions[] = {
    "GL_EXT_texture_compression_s3tc",
    "GL_EXT_texture_compression_rgtc",
    "GL_EXT_texture_filter_anisotropic",
    "GL_ARB_texture_compression_bptc",
    "GL_ARB_texture_rectangle",
    "GL_ARB_debug_output",
    "GL_ARB_half_float_vertex",
    "GL_ARB_get_program_binary",
    "GL_ATI_meminfo",
    "GL_NVX_gpu_memory_info"
};

static int gGLSLVersion = -1;

int glslVersion() {
    return gGLSLVersion;
}

const char *glslVersionString() {
    switch (gGLSLVersion) {
    case 130: return "3.0";
    case 140: return "3.1";
    case 150: return "3.2";
    case 330: return "3.3";
    }
    U_UNREACHABLE();
}

const char *extensionString(size_t what) {
    return kExtensions[what];
}

const u::set<size_t> &extensions() {
    return gExtensions;
}

bool has(size_t ext) {
    return gExtensions.find(ext) != gExtensions.end();
}

void init() {
    glCreateShader_             = (MYPFNGLCREATESHADERPROC)neoGetProcAddress("glCreateShader");
    glShaderSource_             = (MYPFNGLSHADERSOURCEPROC)neoGetProcAddress("glShaderSource");
    glCompileShader_            = (MYPFNGLCOMPILESHADERPROC)neoGetProcAddress("glCompileShader");
    glAttachShader_             = (MYPFNGLATTACHSHADERPROC)neoGetProcAddress("glAttachShader");
    glCreateProgram_            = (MYPFNGLCREATEPROGRAMPROC)neoGetProcAddress("glCreateProgram");
    glLinkProgram_              = (MYPFNGLLINKPROGRAMPROC)neoGetProcAddress("glLinkProgram");
    glUseProgram_               = (MYPFNGLUSEPROGRAMPROC)neoGetProcAddress("glUseProgram");
    glGetUniformLocation_       = (MYPFNGLGETUNIFORMLOCATIONPROC)neoGetProcAddress("glGetUniformLocation");
    glEnableVertexAttribArray_  = (MYPFNGLENABLEVERTEXATTRIBARRAYPROC)neoGetProcAddress("glEnableVertexAttribArray");
    glDisableVertexAttribArray_ = (MYPFNGLDISABLEVERTEXATTRIBARRAYPROC)neoGetProcAddress("glDisableVertexAttribArray");
    glUniformMatrix4fv_         = (MYPFNGLUNIFORMMATRIX4FVPROC)neoGetProcAddress("glUniformMatrix4fv");
    glBindBuffer_               = (MYPFNGLBINDBUFFERPROC)neoGetProcAddress("glBindBuffer");
    glGenBuffers_               = (MYPFNGLGENBUFFERSPROC)neoGetProcAddress("glGenBuffers");
    glVertexAttribPointer_      = (MYPFNGLVERTEXATTRIBPOINTERPROC)neoGetProcAddress("glVertexAttribPointer");
    glBufferData_               = (MYPFNGLBUFFERDATAPROC)neoGetProcAddress("glBufferData");
    glValidateProgram_          = (MYPFNGLVALIDATEPROGRAMPROC)neoGetProcAddress("glValidateProgram");
    glGenVertexArrays_          = (MYPFNGLGENVERTEXARRAYSPROC)neoGetProcAddress("glGenVertexArrays");
    glBindVertexArray_          = (MYPFNGLBINDVERTEXARRAYPROC)neoGetProcAddress("glBindVertexArray");
    glDeleteProgram_            = (MYPFNGLDELETEPROGRAMPROC)neoGetProcAddress("glDeleteProgram");
    glDeleteBuffers_            = (MYPFNGLDELETEBUFFERSPROC)neoGetProcAddress("glDeleteBuffers");
    glDeleteVertexArrays_       = (MYPFNGLDELETEVERTEXARRAYSPROC)neoGetProcAddress("glDeleteVertexArrays");
    glUniform1i_                = (MYPFNGLUNIFORM1IPROC)neoGetProcAddress("glUniform1i");
    glUniform2i_                = (MYPFNGLUNIFORM2IPROC)neoGetProcAddress("glUniform2i");
    glUniform1f_                = (MYPFNGLUNIFORM1FPROC)neoGetProcAddress("glUniform1f");
    glUniform2f_                = (MYPFNGLUNIFORM2FPROC)neoGetProcAddress("glUniform2f");
    glUniform2fv_               = (MYPFNGLUNIFORM2FVPROC)neoGetProcAddress("glUniform2fv");
    glUniform3fv_               = (MYPFNGLUNIFORM3FVPROC)neoGetProcAddress("glUniform3fv");
    glUniform4fv_               = (MYPFNGLUNIFORM4FVPROC)neoGetProcAddress("glUniform4fv");
    glUniformMatrix3x4fv_       = (MYPFNGLUNIFORMMATRIX3X4FVPROC)neoGetProcAddress("glUniformMatrix3x4fv");
    glGenerateMipmap_           = (MYPFNGLGENERATEMIPMAPPROC)neoGetProcAddress("glGenerateMipmap");
    glDeleteShader_             = (MYPFNGLDELETESHADERPROC)neoGetProcAddress("glDeleteShader");
    glGetShaderiv_              = (MYPFNGLGETSHADERIVPROC)neoGetProcAddress("glGetShaderiv");
    glGetProgramiv_             = (MYPFNGLGETPROGRAMIVPROC)neoGetProcAddress("glGetProgramiv");
    glGetShaderInfoLog_         = (MYPFNGLGETSHADERINFOLOGPROC)neoGetProcAddress("glGetShaderInfoLog");
    glActiveTexture_            = (MYPFNGLACTIVETEXTUREPROC)neoGetProcAddress("glActiveTexture");
    glGenFramebuffers_          = (MYPFNGLGENFRAMEBUFFERSPROC)neoGetProcAddress("glGenFramebuffers");
    glBindFramebuffer_          = (MYPFNGLBINDFRAMEBUFFERPROC)neoGetProcAddress("glBindFramebuffer");
    glFramebufferTexture2D_     = (MYPFNGLFRAMEBUFFERTEXTURE2DPROC)neoGetProcAddress("glFramebufferTexture2D");
    glDrawBuffers_              = (MYPFNGLDRAWBUFFERSPROC)neoGetProcAddress("glDrawBuffers");
    glCheckFramebufferStatus_   = (MYPFNGLCHECKFRAMEBUFFERSTATUSPROC)neoGetProcAddress("glCheckFramebufferStatus");
    glDeleteFramebuffers_       = (MYPFNGLDELETEFRAMEBUFFERSPROC)neoGetProcAddress("glDeleteFramebuffers");
    glClear_                    = (MYPFNGLCLEARPROC)neoGetProcAddress("glClear");
    glClearColor_               = (MYPFNGLCLEARCOLORPROC)neoGetProcAddress("glClearColor");
    glFrontFace_                = (MYPFNGLFRONTFACEPROC)neoGetProcAddress("glFrontFace");
    glCullFace_                 = (MYPFNGLCULLFACEPROC)neoGetProcAddress("glCullFace");
    glEnable_                   = (MYPFNGLENABLEPROC)neoGetProcAddress("glEnable");
    glDisable_                  = (MYPFNGLDISABLEPROC)neoGetProcAddress("glDisable");
    glDrawElements_             = (MYPFNGLDRAWELEMENTSPROC)neoGetProcAddress("glDrawElements");
    glDepthMask_                = (MYPFNGLDEPTHMASKPROC)neoGetProcAddress("glDepthMask");
    glBindTexture_              = (MYPFNGLBINDTEXTUREPROC)neoGetProcAddress("glBindTexture");
    glTexImage2D_               = (MYPFNGLTEXIMAGE2DPROC)neoGetProcAddress("glTexImage2D");
    glDeleteTextures_           = (MYPFNGLDELETETEXTURESPROC)neoGetProcAddress("glDeleteTextures");
    glGenTextures_              = (MYPFNGLGENTEXTURESPROC)neoGetProcAddress("glGenTextures");
    glTexParameterf_            = (MYPFNGLTEXPARAMETERFPROC)neoGetProcAddress("glTexParameterf");
    glTexParameteri_            = (MYPFNGLTEXPARAMETERIPROC)neoGetProcAddress("glTexParameteri");
    glDrawArrays_               = (MYPFNGLDRAWARRAYSPROC)neoGetProcAddress("glDrawArrays");
    glBlendEquation_            = (MYPFNGLBLENDEQUATIONPROC)neoGetProcAddress("glBlendEquation");
    glBlendFunc_                = (MYPFNGLBLENDFUNCPROC)neoGetProcAddress("glBlendFunc");
    glDepthFunc_                = (MYPFNGLDEPTHFUNCPROC)neoGetProcAddress("glDepthFunc");
    glColorMask_                = (MYPFNGLCOLORMASKPROC)neoGetProcAddress("glColorMask");
    glReadPixels_               = (MYPFNGLREADPIXELSPROC)neoGetProcAddress("glReadPixels");
    glViewport_                 = (MYPFNGLVIEWPORTPROC)neoGetProcAddress("glViewport");
    glGetIntegerv_              = (MYPFNGLGETINTEGERVPROC)neoGetProcAddress("glGetIntegerv");
    glGetString_                = (MYPFNGLGETSTRINGPROC)neoGetProcAddress("glGetString");
    glGetStringi_               = (MYPFNGLGETSTRINGIPROC)neoGetProcAddress("glGetStringi");
    glGetFloatv_                = (MYPFNGLGETFLOATVPROC)neoGetProcAddress("glGetFloatv");
    glGetError_                 = (MYPFNGLGETERRORPROC)neoGetProcAddress("glGetError");
    glGetTexLevelParameteriv_   = (MYPFNGLGETTEXLEVELPARAMETERIVPROC)neoGetProcAddress("glGetTexLevelParameteriv");
    glGetCompressedTexImage_    = (MYPFNGLGETCOMPRESSEDTEXIMAGEPROC)neoGetProcAddress("glGetCompressedTexImage");
    glCompressedTexImage2D_     = (MYPFNGLCOMPRESSEDTEXIMAGE2DPROC)neoGetProcAddress("glCompressedTexImage2D");
    glPixelStorei_              = (MYPFNGLPIXELSTOREIPROC)neoGetProcAddress("glPixelStorei");
    glScissor_                  = (MYPFNGLSCISSORPROC)neoGetProcAddress("glScissor");
    glPolygonMode_              = (MYPFNGLPOLYGONMODEPROC)neoGetProcAddress("glPolygonMode");
    glHint_                     = (MYPFNGLHINTPROC)neoGetProcAddress("glHint");
    glGenQueries_               = (MYPFNGLGENQUERIESPROC)neoGetProcAddress("glGenQueries");
    glBeginQuery_               = (MYPFNGLBEGINQUERYPROC)neoGetProcAddress("glBeginQuery");
    glEndQuery_                 = (MYPFNGLENDQUERYPROC)neoGetProcAddress("glEndQuery");
    glDeleteQueries_            = (MYPFNGLDELETEQUERIESPROC)neoGetProcAddress("glDeleteQueries");
    glGetQueryObjectuiv_        = (MYPFNGLGETQUERYOBJECTUIVPROC)neoGetProcAddress("glGetQueryObjectuiv");
    glFlush_                    = (MYPFNGLFLUSHPROC)neoGetProcAddress("glFlush");
    glStencilFunc_              = (MYPFNGLSTENCILFUNCPROC)neoGetProcAddress("glStencilFunc");
    glStencilOp_                = (MYPFNGLSTENCILOPPROC)neoGetProcAddress("glStencilOp");
    glTexImage3D_               = (MYPFNGLTEXIMAGE3DPROC)neoGetProcAddress("glTexImage3D");
    glTexSubImage3D_            = (MYPFNGLTEXSUBIMAGE3DPROC)neoGetProcAddress("glTexSubImage3D");
    glGetProgramInfoLog_        = (MYPFNGLGETPROGRAMINFOLOGPROC)neoGetProcAddress("glGetProgramInfoLog");
    glBindAttribLocation_       = (MYPFNGLBINDATTRIBLOCATIONPROC)neoGetProcAddress("glBindAttribLocation");
    glBindFragDataLocation_     = (MYPFNGLBINDFRAGDATALOCATIONPROC)neoGetProcAddress("glBindFragDataLocation");
    glTexSubImage2D_            = (MYPFNGLTEXSUBIMAGE2DPROC)neoGetProcAddress("glTexSubImage2D");
    glDrawBuffer_               = (MYPFNGLDRAWBUFFERPROC)neoGetProcAddress("glDrawBuffer");
    glReadBuffer_               = (MYPFNGLREADBUFFERPROC)neoGetProcAddress("glReadBuffer");
    glBufferSubData_            = (MYPFNGLBUFFERSUBDATAPROC)neoGetProcAddress("glBufferSubData");
    glPolygonOffset_            = (MYPFNGLPOLYGONOFFSETPROC)neoGetProcAddress("glPolygonOffset");
    glDepthRange_               = (MYPFNGLDEPTHRANGEPROC)neoGetProcAddress("glDepthRange");
    glProgramParameteri_        = (MYPFNGLPROGRAMPARAMETERIPROC)neoGetProcAddress("glProgramParameteri");
    glGetProgramBinary_         = (MYPFNGLGETPROGRAMBINARYPROC)neoGetProcAddress("glGetProgramBinary");
    glProgramBinary_            = (MYPFNGLPROGRAMBINARYPROC)neoGetProcAddress("glProgramBinary");

    if (!glGetIntegerv_ || !glGetStringi_)
        neoFatal("Failed to initialize OpenGL\n");

    GLint count = 0;
    glGetIntegerv_(GL_NUM_EXTENSIONS, &count);
    for (GLint i = 0; i < count; i++)
        for (size_t j = 0; j < sizeof(kExtensions)/sizeof(*kExtensions); j++)
            if (!strcmp(kExtensions[j], (const char *)glGetStringi_(GL_EXTENSIONS, i)))
                gExtensions.insert(j);

    auto &aniso = c::Console::value<int>("r_aniso");
    if (has(gl::EXT_texture_filter_anisotropic)) {
        float largest;
        glGetFloatv_(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest);
        aniso.setMax(int(largest));
    } else {
        aniso.setMax(0);
    }

    static constexpr int kGLSLVersions[] = {
        130, 140, 150, 330
    };

    for (auto &it : kGLSLVersions) {
        const u::string source = u::format("#version %d\nvoid main() { }\n", it);
        const char *sources[1] = { source.c_str() };
        GLuint s = glCreateShader_(GL_VERTEX_SHADER);
        glShaderSource_(s, 1, sources, nullptr);
        glCompileShader_(s);
        GLint compiled = 0;
        glGetShaderiv_(s, GL_COMPILE_STATUS, &compiled);
        if (compiled) {
            gGLSLVersion = it;
            break;
        }
    }

    if (gGLSLVersion == -1)
        neoFatal("Failed to initialize OpenGL\n");

#if defined(DEBUG_GL)
    if (has(gl::ARB_debug_output)) {
        glEnable_(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        ((MYPFNGLDEBUGMESSAGECALLBACKARBPROC)neoGetProcAddress("glDebugMessageCallbackARB"))(&debugCallback, nullptr);
    }
#endif
}

GLuint CreateShader(GLenum shaderType GL_INFOP) {
    GLuint result = glCreateShader_(shaderType);
    GL_CHECK("2", shaderType);
    return result;
}

void ShaderSource(GLuint shader, GLsizei count, const GLchar** string, const GLint* length GL_INFOP) {
    glShaderSource_(shader, count, string, length);
    GL_CHECK("b8*0*7", shader, count, string, length);
}

void CompileShader(GLuint shader GL_INFOP) {
    glCompileShader_(shader);
    GL_CHECK("b", shader);
}

void AttachShader(GLuint program, GLuint shader GL_INFOP) {
    glAttachShader_(program, shader);
    GL_CHECK("bb", program, shader);
}

GLuint CreateProgram(GL_INFO) {
    GLuint result = glCreateProgram_();
    GL_CHECK("",0);
    return result;
}

void LinkProgram(GLuint program GL_INFOP) {
    glLinkProgram_(program);
    GL_CHECK("b", program);
}

void UseProgram(GLuint program GL_INFOP) {
    glUseProgram_(program);
    GL_CHECK("b", program);
}

GLint GetUniformLocation(GLuint program, const GLchar* name GL_INFOP) {
    GLint result = glGetUniformLocation_(program, name);
    GL_CHECK("b*1", program, name);
    return result;
}

void EnableVertexAttribArray(GLuint index GL_INFOP) {
    glEnableVertexAttribArray_(index);
    GL_CHECK("b", index);
}

void DisableVertexAttribArray(GLuint index GL_INFOP) {
    glDisableVertexAttribArray_(index);
    GL_CHECK("b", index);
}

void UniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value GL_INFOP) {
    glUniformMatrix4fv_(location, count, transpose, value);
    GL_CHECK("783*c", location, count, transpose, value);
}

void BindBuffer(GLenum target, GLuint buffer GL_INFOP) {
    glBindBuffer_(target, buffer);
    GL_CHECK("2b", target, buffer);
}

void GenBuffers(GLsizei n, GLuint* buffers GL_INFOP) {
    glGenBuffers_(n, buffers);
    GL_CHECK("8*b", n, buffers);
}

void VertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer GL_INFOP) {
    glVertexAttribPointer_(index, size, type, normalized, stride, pointer);
    GL_CHECK("b7238*0", index, size, type, normalized, stride, pointer);
}

void BufferData(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage GL_INFOP) {
    glBufferData_(target, size, data, usage);
    GL_CHECK("2f*02", target, size, data, usage);
}

void ValidateProgram(GLuint program GL_INFOP) {
    glValidateProgram_(program);
    GL_CHECK("b", program);
}

void GenVertexArrays(GLsizei n, GLuint* arrays GL_INFOP) {
    glGenVertexArrays_(n, arrays);
    GL_CHECK("8*b", n, arrays);
}

void BindVertexArray(GLuint array GL_INFOP) {
    glBindVertexArray_(array);
    GL_CHECK("b", array);
}

void DeleteProgram(GLuint program GL_INFOP) {
    glDeleteProgram_(program);
    GL_CHECK("b", program);
}

void DeleteBuffers(GLsizei n, const GLuint* buffers GL_INFOP) {
    glDeleteBuffers_(n, buffers);
    GL_CHECK("8*b", n, buffers);
}

void DeleteVertexArrays(GLsizei n, const GLuint* arrays GL_INFOP) {
    glDeleteVertexArrays_(n, arrays);
    GL_CHECK("8*b", n, arrays);
}

void Uniform1i(GLint location, GLint v0 GL_INFOP) {
    glUniform1i_(location, v0);
    GL_CHECK("77", location, v0);
}

void Uniform2i(GLint location, GLint v0, GLint v1 GL_INFOP) {
    glUniform2i_(location, v0, v1);
    GL_CHECK("777", location, v0, v1);
}

void Uniform1f(GLint location, GLfloat v0 GL_INFOP) {
    glUniform1f_(location, v0);
    GL_CHECK("7c", location, v0);
}

void Uniform2f(GLint location, GLfloat v0, GLfloat v1 GL_INFOP) {
    glUniform2f_(location, v0, v1);
    GL_CHECK("7cc", location, v0, v1);
}

void Uniform2fv(GLint location, GLsizei count, const GLfloat* value GL_INFOP) {
    glUniform2fv_(location, count, value);
    GL_CHECK("78*c", location, count, value);
}

void Uniform3fv(GLint location, GLsizei count, const GLfloat* value GL_INFOP) {
    glUniform3fv_(location, count, value);
    GL_CHECK("78*c", location, count, value);
}

void Uniform4fv(GLint location, GLsizei count, const GLfloat* value GL_INFOP) {
    glUniform4fv_(location, count, value);
    GL_CHECK("78*c", location, count, value);
}

void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value GL_INFOP) {
    glUniformMatrix3x4fv_(location, count, transpose, value);
    GL_CHECK("783*c", location, count, transpose, value);
}

void GenerateMipmap(GLenum target GL_INFOP) {
    glGenerateMipmap_(target);
    GL_CHECK("2", target);
}

void DeleteShader(GLuint shader GL_INFOP) {
    glDeleteShader_(shader);
    GL_CHECK("b", shader);
}

void GetShaderiv(GLuint shader, GLenum pname, GLint* params GL_INFOP) {
    glGetShaderiv_(shader, pname, params);
    GL_CHECK("b2*7", shader, pname, params);
}

void GetProgramiv(GLuint program, GLenum pname, GLint* params GL_INFOP) {
    glGetProgramiv_(program, pname, params);
    GL_CHECK("b2*7", program, pname, params);
}

void GetShaderInfoLog(GLuint shader, GLsizei maxLength, GLsizei* length, GLchar* infoLog GL_INFOP) {
    glGetShaderInfoLog_(shader, maxLength, length, infoLog);
    GL_CHECK("b8*8*1", shader, maxLength, length, infoLog);
}

void ActiveTexture(GLenum texture GL_INFOP) {
    glActiveTexture_(texture);
    GL_CHECK("2", texture);
}

void GenFramebuffers(GLsizei n, GLuint* ids GL_INFOP) {
    glGenFramebuffers_(n, ids);
    GL_CHECK("8*b", n, ids);
}

void BindFramebuffer(GLenum target, GLuint framebuffer GL_INFOP) {
    glBindFramebuffer_(target, framebuffer);
    GL_CHECK("2b", target, framebuffer);
}

void FramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level GL_INFOP) {
    glFramebufferTexture2D_(target, attachment, textarget, texture, level);
    GL_CHECK("222b7", target, attachment, textarget, texture, level);
}

void DrawBuffers(GLsizei n, const GLenum* bufs GL_INFOP) {
    glDrawBuffers_(n, bufs);
    GL_CHECK("8*2", n, bufs);
}

GLenum CheckFramebufferStatus(GLenum target GL_INFOP) {
    GLenum result = glCheckFramebufferStatus_(target);
    GL_CHECK("2", target);
    return result;
}

void DeleteFramebuffers(GLsizei n, const GLuint* framebuffers GL_INFOP) {
    glDeleteFramebuffers_(n, framebuffers);
    GL_CHECK("8*b", n, framebuffers);
}

void Clear(GLbitfield mask GL_INFOP) {
    glClear_(mask);
    GL_CHECK("4", mask);
}

void ClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha GL_INFOP) {
    glClearColor_(red, green, blue, alpha);
    GL_CHECK("cccc", red, green, blue, alpha);
}

void FrontFace(GLenum mode GL_INFOP) {
    glFrontFace_(mode);
    GL_CHECK("2", mode);
}

void CullFace(GLenum mode GL_INFOP) {
    glCullFace_(mode);
    GL_CHECK("2", mode);
}

void Enable(GLenum cap GL_INFOP) {
    glEnable_(cap);
    GL_CHECK("2", cap);
}

void Disable(GLenum cap GL_INFOP) {
    glDisable_(cap);
    GL_CHECK("2", cap);
}

void DrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices GL_INFOP) {
    glDrawElements_(mode, count, type, indices);
    GL_CHECK("282*0", mode, count, type, indices);
}

void DepthMask(GLboolean flag GL_INFOP) {
    glDepthMask_(flag);
    GL_CHECK("3", flag);
}

void BindTexture(GLenum target, GLuint texture GL_INFOP) {
    glBindTexture_(target, texture);
    GL_CHECK("2b", target, texture);
}

void TexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* data GL_INFOP) {
    glTexImage2D_(target, level, internalFormat, width, height, border, format, type, data);
    GL_CHECK("27788722*0", target, level, internalFormat, width, height, border, format, type, data);
}

void DeleteTextures(GLsizei n, const GLuint* textures GL_INFOP) {
    glDeleteTextures_(n, textures);
    GL_CHECK("8*b", n, textures);
}

void GenTextures(GLsizei n, GLuint* textures GL_INFOP) {
    glGenTextures_(n, textures);
    GL_CHECK("8*b", n, textures);
}

void TexParameterf(GLenum target, GLenum pname, GLfloat param GL_INFOP) {
    glTexParameterf_(target, pname, param);
    GL_CHECK("22c", target, pname, param);
}

void TexParameteri(GLenum target, GLenum pname, GLint param GL_INFOP) {
    glTexParameteri_(target, pname, param);
    GL_CHECK("227", target, pname, param);
}

void DrawArrays(GLenum mode, GLint first, GLsizei count GL_INFOP) {
    glDrawArrays_(mode, first, count);
    GL_CHECK("278", mode, first, count);
}

void BlendEquation(GLenum mode GL_INFOP) {
    glBlendEquation_(mode);
    GL_CHECK("2", mode);
}

void BlendFunc(GLenum sfactor, GLenum dfactor GL_INFOP) {
    glBlendFunc_(sfactor, dfactor);
    GL_CHECK("22", sfactor, dfactor);
}

void DepthFunc(GLenum func GL_INFOP) {
    glDepthFunc_(func);
    GL_CHECK("2", func);
}

void ColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha GL_INFOP) {
    glColorMask_(red, green, blue, alpha);
    GL_CHECK("3333", red, green, blue, alpha);
}

void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* data GL_INFOP) {
    glReadPixels_(x, y, width, height, format, type, data);
    GL_CHECK("778822*0", x, y, width, height, format, type, data);
}

void Viewport(GLint x, GLint y, GLsizei width, GLsizei height GL_INFOP) {
    glViewport_(x, y, width, height);
    GL_CHECK("7788", x, y, width, height);
}

void GetIntegerv(GLenum pname, GLint* data GL_INFOP) {
    glGetIntegerv_(pname, data);
    GL_CHECK("2*7", pname, data);
}

const GLubyte* GetString(GLenum name GL_INFOP) {
    const GLubyte* result = glGetString_(name);
    GL_CHECK("2", name);
    return result;
}

const GLubyte* GetStringi(GLenum name, GLuint index GL_INFOP) {
    const GLubyte* result = glGetStringi_(name, index);
    GL_CHECK("2b", name, index);
    return result;
}

void GetFloatv(GLenum pname, GLfloat* params GL_INFOP) {
    glGetFloatv_(pname, params);
    GL_CHECK("2*c", pname, params);
}

GLenum GetError(GL_INFO) {
    GLenum result = glGetError_();
    GL_CHECK("",0);
    return result;
}

void GetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params GL_INFOP) {
    glGetTexLevelParameteriv_(target, level, pname, params);
    GL_CHECK("272*7", target, level, pname, params);
}

void GetCompressedTexImage(GLenum target, GLint lod, GLvoid* img GL_INFOP) {
    glGetCompressedTexImage_(target, lod, img);
    GL_CHECK("27*0", target, lod, img);
}

void CompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data GL_INFOP) {
    glCompressedTexImage2D_(target, level, internalformat, width, height, border, imageSize, data);
    GL_CHECK("2728878*0", target, level, internalformat, width, height, border, imageSize, data);
}

void PixelStorei(GLenum pname, GLint param GL_INFOP) {
    glPixelStorei_(pname, param);
    GL_CHECK("27", pname, param);
}

void Scissor(GLint x, GLint y, GLsizei width, GLsizei height GL_INFOP) {
    glScissor_(x, y, width, height);
    GL_CHECK("7788", x, y, width, height);
}

void PolygonMode(GLenum face, GLenum mode GL_INFOP) {
    glPolygonMode_(face, mode);
    GL_CHECK("22", face, mode);
}

void Hint(GLenum target, GLenum mode GL_INFOP) {
    glHint_(target, mode);
    GL_CHECK("22", target, mode);
}

void GenQueries(GLsizei n, GLuint* ids GL_INFOP) {
    glGenQueries_(n, ids);
    GL_CHECK("8*b", n, ids);
}

void BeginQuery(GLenum target, GLuint id GL_INFOP) {
    glBeginQuery_(target, id);
    GL_CHECK("2b", target, id);
}

void EndQuery(GLenum target, GLuint id GL_INFOP) {
    glEndQuery_(target, id);
    GL_CHECK("2b", target, id);
}

void DeleteQueries(GLsizei n, const GLuint* ids GL_INFOP) {
    glDeleteQueries_(n, ids);
    GL_CHECK("8*b", n, ids);
}

void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params GL_INFOP) {
    glGetQueryObjectuiv_(id, pname, params);
    GL_CHECK("b2*b", id, pname, params);
}

void Flush(GL_INFO) {
    glFlush_();
    GL_CHECK("",0);
}

void StencilFunc(GLenum func, GLint ref, GLuint mask GL_INFOP) {
    glStencilFunc_(func, ref, mask);
    GL_CHECK("27b", func, ref, mask);
}

void StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass GL_INFOP) {
    glStencilOp_(sfail, dpfail, dppass);
    GL_CHECK("222", sfail, dpfail, dppass);
}

void TexImage3D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* data GL_INFOP) {
    glTexImage3D_(target, level, internalFormat, width, height, depth, border, format, type, data);
    GL_CHECK("277888722*0", target, level, internalFormat, width, height, depth, border, format, type, data);
}

void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid * data GL_INFOP) {
    glTexSubImage3D_(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, data);
    GL_CHECK("2777788822*0", target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, data);
}

void GetProgramInfoLog(GLuint program, GLsizei maxLength, GLsizei* length, GLchar* infoLog GL_INFOP) {
    glGetProgramInfoLog_(program, maxLength, length, infoLog);
    GL_CHECK("b8*8*1", program, maxLength, length, infoLog);
}

void BindAttribLocation(GLuint program, GLuint index, const GLchar* name GL_INFOP) {
    glBindAttribLocation_(program, index, name);
    GL_CHECK("bb*1", program, index, name);
}

void BindFragDataLocation(GLuint program, GLuint colorNumber, const GLchar* name GL_INFOP) {
    glBindFragDataLocation_(program, colorNumber, name);
    GL_CHECK("bb*1", program, colorNumber, name);
}

void TexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* data GL_INFOP) {
    glTexSubImage2D_(target, level, xoffset, yoffset, width, height, format, type, data);
    GL_CHECK("27778822*0", target, level, xoffset, yoffset, width, height, format, type, data);
}

void DrawBuffer(GLenum mode GL_INFOP) {
    glDrawBuffer_(mode);
    GL_CHECK("2", mode);
}

void ReadBuffer(GLenum mode GL_INFOP) {
    glReadBuffer_(mode);
    GL_CHECK("2", mode);
}

void BufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data GL_INFOP) {
    glBufferSubData_(target, offset, size, data);
    GL_CHECK("2ef*0", target, offset, size, data);
}

void PolygonOffset(GLfloat factor, GLfloat units GL_INFOP) {
    glPolygonOffset_(factor, units);
    GL_CHECK("cc", factor, units);
}

void DepthRange(GLclampd nearVal, GLclampd farVal GL_INFOP) {
    glDepthRange_(nearVal, farVal);
    GL_CHECK("gg", nearVal, farVal);
}

void ProgramParameteri(GLuint program, GLenum pname, GLint value GL_INFOP) {
    glProgramParameteri_(program, pname, value);
    GL_CHECK("b27", program, pname, value);
}

void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary GL_INFOP) {
    glGetProgramBinary_(program, bufSize, length, binaryFormat, binary);
    GL_CHECK("b8*8*2*0", program, bufSize, length, binaryFormat, binary);
}

void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length GL_INFOP) {
    glProgramBinary_(program, binaryFormat, binary, length);
    GL_CHECK("b2*08", program, binaryFormat, binary, length);
}

}


text:
/**
	file msg_send.h
	@desc Header file for message send
	@author Gilson Varghese
	@date  11 Sep 2016
**/

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <sys/types.h>

/**
	Macros
*/

#define TEST_MSG_KEY 10
#define TEST_MSG_TYPE 100
#define MSG_SIZE 256
#define TEST_MSG "It works"

#define SUCCESS 0
#define FAILURE -1

/**
	Structure declarations
*/

typedef struct MessageQID {
	int msgID;
}messageQID;

typedef struct MessageBuf {
	long mtype;
	char msg[MSG_SIZE];
}messageBuf;

/**
	Function Declarations
*/

int createMsgQ(messageQID*);
int sendMsg(messageQID*, messageBuf*);

/**
	Null structure definitions
*/

static messageQID nullMessageQID;
static messageBuf nullMessageBuf;


text:
/**
 * 判断是否已安装
 */
angular.module('services').factory('checkInstallResolve', ['$q', '$state', '$http',
  function ($q, $state, $http) {
    'use strict';

    return {
      leaveToSignInOrNone: function () {
        var deferred = $q.defer();

        $http.get('/api/install')
          .then(function (res) {
            var data = res.data;

            if (!data.hasInstall) {
              deferred.resolve();
            } else {
              $state.go('signIn');
            }
          }, function () {
            $state.go('signIn');
          });

        return deferred.promise;
      },
      enterToInstallOrNone: function () {
        var deferred = $q.defer();

        $http.get('/api/install')
          .then(function (res) {
            var data = res.data;

            if (!data.hasInstall) {
              $state.go('install');
            } else {
              deferred.resolve();
            }
          }, function () {
            deferred.resolve();
          });

        return deferred.promise;
      }
    }
  }
]);


text:
FileBrowser::FileBrowser( TTF_Font* font )
    : m_CurrentFile(-1)
    , m_HistoryIndex(-1)
    , m_Search(0)
{

    SDL_Rect rect = {LEFTOFFSET,TOPOFFSET,WIDGETWIDTH,WIDGETHEIGHT};

    for (int i=0; i<FILEWIDGETCOUNT; ++i)
    {
        FileWidget* widget = new FileWidget();

        widget->SetRect(rect);
        widget->SetFont(font);

        m_FileWidgets.push_back(widget);

        rect.y += WIDGETHEIGHT;
    }
// current directory
    SDL_Rect cd_rect = {LEFTOFFSETDIR,TOPOFFSETDIR,WIDGETWIDTH,WIDGETHEIGHT};
    m_DirWidget.SetRect(cd_rect);
    m_DirWidget.SetFont(font);
}

FileBrowser::~FileBrowser()
{
    for (size_t i=0,n=m_FileWidgets.size(); i<n; ++i)
    {
        delete m_FileWidgets[i];
    }
}

bool FileBrowser::SetStartFile(const FileStat& start_file)
{
    if (UpdateFileList(start_file))
    {
        m_CurrentFile = Find(start_file,m_FileList,0);
        m_History.clear();
        m_History.push_back(start_file);
        m_HistoryIndex = 0;

        UpdateWidgets();
        return true;
    }
    return false;
}

const FileStat& FileBrowser::GetCurrentFile() const
{
    if (m_CurrentFile>=0 && m_CurrentFile<m_FileList.size())
    {
        return m_FileList[m_CurrentFile];
    }
    return EmptyFileStat;
}

bool FileBrowser::UpdateFileList(const FileStat& file)
{
    FileList file_list;
    ListDir(file,&file_list);
    if (file_list.size())
    {
        m_FileList = file_list;
        m_CurrentFile = 0;

        UpdateWidgets();

        return true;
    }
    return false;
}

void FileBrowser::Next()
{
    if (m_FileList.size())
    {
        int last_file = m_CurrentFile;
        ++ m_CurrentFile %= m_FileList.size();

        if (m_CurrentFile!=last_file)
            UpdateWidgets();
    }
}

void FileBrowser::Prev()
{
    if (m_FileList.size())
    {
        int last_file = m_CurrentFile;
        -- m_CurrentFile;

        if (m_CurrentFile<0)
            m_CurrentFile = m_FileList.size()-1;

        if (last_file!=m_CurrentFile)
            UpdateWidgets();
    }
}

void FileBrowser::Enter()
{
    if (GetCurrentFile().IsDir())
    {
        if (m_HistoryIndex+1<m_History.size())
            m_History.erase(m_History.begin()+m_HistoryIndex+1,m_History.end());

        m_HistoryIndex = m_History.size();
        m_History.push_back(GetCurrentFile());

        UpdateFileList(GetCurrentFile());
    }
}

void FileBrowser::Search(char chr)
{
    int search_start[] = {
        m_CurrentFile,
        -1
    };

    for (int start=0; start<2;++start)
    {
        for (int i=search_start[start]+1, n=m_FileList.size(); i<n; ++i)
        {
            const FileStat& file = m_FileList[i];
            char file_chr = file.GetName().size() ? file.GetName()[0] : 0;

            if (tolower(file_chr)==tolower(chr))
            {
                m_Search = chr;
                m_CurrentFile = i;
                UpdateWidgets();
                return;
            }
        }
    }

    m_Search = 0;
}

void FileBrowser::NextHistory()
{
    if (m_History.size() && m_HistoryIndex+1<m_History.size())
    {
        m_HistoryIndex ++;
        m_CurrentFile = 0;
        UpdateFileList(m_History[m_HistoryIndex]);
    }
}

void FileBrowser::PrevHistory()
{
    if (m_History.size() && m_HistoryIndex-1>=0)
    {
        m_HistoryIndex --;
        m_CurrentFile = 0;
        UpdateFileList(m_History[m_HistoryIndex]);
    }
}

void FileBrowser::BlitTo(SDL_Surface* screen)
{
    for(size_t i=0,n=m_FileWidgets.size(); i<n; ++i)
    {
        m_FileWidgets[i]->BlitTo(screen);
    }
    m_DirWidget.BlitTo(screen);
}

bool FileBrowser::OnKeyDown(const SDL_Event& event)
{
    if ((event.key.keysym.mod & (KMOD_CTRL|KMOD_ALT|KMOD_SHIFT))==0
        && event.key.keysym.sym>=SDLK_SPACE
        && event.key.keysym.sym<=SDLK_z)
    {
        Search(char(event.key.keysym.sym&0xFF));
        return true;
    }
    switch(event.key.keysym.sym)
    {
    case SDLK_UP:
        Prev();
        return true;
    case SDLK_DOWN:
        Next();
        return true;
    case SDLK_LEFT:
        PrevHistory();
        return true;
    case SDLK_RIGHT:
        NextHistory();
        return true;

#ifdef PANDORA
    case SDLK_HOME:
    case SDLK_END:
    case SDLK_PAGEUP:
    case SDLK_PAGEDOWN:
#endif

    case SDLK_RETURN:
        {
            const FileStat& current_file = GetCurrentFile();
            if (current_file.IsDir())
            {
                Enter();
                return true;
            }
        }
        break;
    default:
        return false;
    }
    return false;
}

void FileBrowser::UpdateWidgets()
{
    const int nfiles = m_FileList.size();
    const int nwidgets = m_FileWidgets.size();
    const int half = nwidgets/2 ;

    int file = m_CurrentFile - half ;

    if (file<0) file = 0;
    if (file+nwidgets>=nfiles) file = nfiles - nwidgets;
    if (file<0) file = 0;

    int iwidget = 0;

    while (iwidget<nwidgets)
    {
        if ( file < nfiles )
        {
            m_FileWidgets[iwidget]->SetFileStat(m_FileList[file]);
        }
        else
        {
            m_FileWidgets[iwidget]->SetFileStat(EmptyFileStat);
        }

        m_FileWidgets[iwidget]->SetSelected(m_CurrentFile==file);

        ++ file;
        ++ iwidget;
    }

    if (m_CurrentFile>=0 && m_CurrentFile<m_FileList.size())
    {
        m_DirWidget.SetText(m_FileList[m_CurrentFile].GetDir());
    }
    else
    {
        m_DirWidget.SetText("");
    }
}


text:
!function(){
var S = document.createElement("style");
S.innerHTML="span  {  position: absolute; left : 0px;  }";
document.head.appendChild(S);
S.

}();


text:
/**
 */
package exploitation.tests;

import exploitation.ExploitationFactory;
import exploitation.Ressource;

import junit.framework.TestCase;

import junit.textui.TestRunner;

/**
 *
 * A test case for the model object 'Ressource'.
 *
 * @generated
 */
public class RessourceTest extends TestCase {

	/**
	 * The fixture for this Ressource test case.
	 *
	 *
	 * @generated
	 */
	protected Ressource fixture = null;

	/**
	 *
	 *
	 * @generated
	 */
	public static void main(String[] args) {
		TestRunner.run(RessourceTest.class);
	}

	/**
	 * Constructs a new Ressource test case with the given name.
	 *
	 *
	 * @generated
	 */
	public RessourceTest(String name) {
		super(name);
	}

	/**
	 * Sets the fixture for this Ressource test case.
	 *
	 *
	 * @generated
	 */
	protected void setFixture(Ressource fixture) {
		this.fixture = fixture;
	}

	/**
	 * Returns the fixture for this Ressource test case.
	 *
	 *
	 * @generated
	 */
	protected Ressource getFixture() {
		return fixture;
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
	@Override
	protected void setUp() throws Exception {
		setFixture(ExploitationFactory.eINSTANCE.createRessource());
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
	@Override
	protected void tearDown() throws Exception {
		setFixture(null);
	}

} //RessourceTest