Android Build Tools

This commit is contained in:
Isuru Samarathunga
2025-10-16 00:43:42 +05:30
parent f742dcfaff
commit 160bf65a1f
5549 changed files with 1752060 additions and 0 deletions

View File

@ -0,0 +1,29 @@
# Copyright 2020 The Shaderc Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_CPP_EXTENSION := .cc .cpp .cxx
LOCAL_MODULE:=shaderc
LOCAL_EXPORT_C_INCLUDES:=$(LOCAL_PATH)/include
LOCAL_SRC_FILES:=src/shaderc.cc
# The Shaderc third_party/Android.mk deduces SPVHEADERS_LOCAL_PATH,
# or delegates that responsibility to SPIRV-Tools' Android.mk.
LOCAL_C_INCLUDES:=$(LOCAL_PATH)/include $(SPVHEADERS_LOCAL_PATH)/include
LOCAL_STATIC_LIBRARIES:=shaderc_util SPIRV-Tools-opt
LOCAL_CXXFLAGS:=-std=c++11 -fno-exceptions -fno-rtti -DENABLE_HLSL=1
LOCAL_EXPORT_CPPFLAGS:=-std=c++11
LOCAL_EXPORT_LDFLAGS:=-latomic
include $(BUILD_STATIC_LIBRARY)

View File

@ -0,0 +1,72 @@
// Copyright 2018 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SHADERC_ENV_H_
#define SHADERC_ENV_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
shaderc_target_env_vulkan, // SPIR-V under Vulkan semantics
shaderc_target_env_opengl, // SPIR-V under OpenGL semantics
// NOTE: SPIR-V code generation is not supported for shaders under OpenGL
// compatibility profile.
shaderc_target_env_opengl_compat, // SPIR-V under OpenGL semantics,
// including compatibility profile
// functions
shaderc_target_env_webgpu, // Deprecated, SPIR-V under WebGPU
// semantics
shaderc_target_env_default = shaderc_target_env_vulkan
} shaderc_target_env;
typedef enum {
// For Vulkan, use Vulkan's mapping of version numbers to integers.
// See vulkan.h
shaderc_env_version_vulkan_1_0 = ((1u << 22)),
shaderc_env_version_vulkan_1_1 = ((1u << 22) | (1 << 12)),
shaderc_env_version_vulkan_1_2 = ((1u << 22) | (2 << 12)),
shaderc_env_version_vulkan_1_3 = ((1u << 22) | (3 << 12)),
// For OpenGL, use the number from #version in shaders.
// TODO(dneto): Currently no difference between OpenGL 4.5 and 4.6.
// See glslang/Standalone/Standalone.cpp
// TODO(dneto): Glslang doesn't accept a OpenGL client version of 460.
shaderc_env_version_opengl_4_5 = 450,
shaderc_env_version_webgpu, // Deprecated, WebGPU env never defined versions
} shaderc_env_version;
// The known versions of SPIR-V.
typedef enum {
// Use the values used for word 1 of a SPIR-V binary:
// - bits 24 to 31: zero
// - bits 16 to 23: major version number
// - bits 8 to 15: minor version number
// - bits 0 to 7: zero
shaderc_spirv_version_1_0 = 0x010000u,
shaderc_spirv_version_1_1 = 0x010100u,
shaderc_spirv_version_1_2 = 0x010200u,
shaderc_spirv_version_1_3 = 0x010300u,
shaderc_spirv_version_1_4 = 0x010400u,
shaderc_spirv_version_1_5 = 0x010500u,
shaderc_spirv_version_1_6 = 0x010600u
} shaderc_spirv_version;
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // SHADERC_ENV_H_

View File

@ -0,0 +1,589 @@
// Copyright 2015 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SHADERC_SHADERC_H_
#define SHADERC_SHADERC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "shaderc/env.h"
#include "shaderc/status.h"
#include "shaderc/visibility.h"
// Source language kind.
typedef enum {
shaderc_source_language_glsl,
shaderc_source_language_hlsl,
} shaderc_source_language;
typedef enum {
// Forced shader kinds. These shader kinds force the compiler to compile the
// source code as the specified kind of shader.
shaderc_vertex_shader,
shaderc_fragment_shader,
shaderc_compute_shader,
shaderc_geometry_shader,
shaderc_tess_control_shader,
shaderc_tess_evaluation_shader,
shaderc_glsl_vertex_shader = shaderc_vertex_shader,
shaderc_glsl_fragment_shader = shaderc_fragment_shader,
shaderc_glsl_compute_shader = shaderc_compute_shader,
shaderc_glsl_geometry_shader = shaderc_geometry_shader,
shaderc_glsl_tess_control_shader = shaderc_tess_control_shader,
shaderc_glsl_tess_evaluation_shader = shaderc_tess_evaluation_shader,
// Deduce the shader kind from #pragma annotation in the source code. Compiler
// will emit error if #pragma annotation is not found.
shaderc_glsl_infer_from_source,
// Default shader kinds. Compiler will fall back to compile the source code as
// the specified kind of shader when #pragma annotation is not found in the
// source code.
shaderc_glsl_default_vertex_shader,
shaderc_glsl_default_fragment_shader,
shaderc_glsl_default_compute_shader,
shaderc_glsl_default_geometry_shader,
shaderc_glsl_default_tess_control_shader,
shaderc_glsl_default_tess_evaluation_shader,
shaderc_spirv_assembly,
shaderc_raygen_shader,
shaderc_anyhit_shader,
shaderc_closesthit_shader,
shaderc_miss_shader,
shaderc_intersection_shader,
shaderc_callable_shader,
shaderc_glsl_raygen_shader = shaderc_raygen_shader,
shaderc_glsl_anyhit_shader = shaderc_anyhit_shader,
shaderc_glsl_closesthit_shader = shaderc_closesthit_shader,
shaderc_glsl_miss_shader = shaderc_miss_shader,
shaderc_glsl_intersection_shader = shaderc_intersection_shader,
shaderc_glsl_callable_shader = shaderc_callable_shader,
shaderc_glsl_default_raygen_shader,
shaderc_glsl_default_anyhit_shader,
shaderc_glsl_default_closesthit_shader,
shaderc_glsl_default_miss_shader,
shaderc_glsl_default_intersection_shader,
shaderc_glsl_default_callable_shader,
shaderc_task_shader,
shaderc_mesh_shader,
shaderc_glsl_task_shader = shaderc_task_shader,
shaderc_glsl_mesh_shader = shaderc_mesh_shader,
shaderc_glsl_default_task_shader,
shaderc_glsl_default_mesh_shader,
} shaderc_shader_kind;
typedef enum {
shaderc_profile_none, // Used if and only if GLSL version did not specify
// profiles.
shaderc_profile_core,
shaderc_profile_compatibility, // Disabled. This generates an error
shaderc_profile_es,
} shaderc_profile;
// Optimization level.
typedef enum {
shaderc_optimization_level_zero, // no optimization
shaderc_optimization_level_size, // optimize towards reducing code size
shaderc_optimization_level_performance, // optimize towards performance
} shaderc_optimization_level;
// Resource limits.
typedef enum {
shaderc_limit_max_lights,
shaderc_limit_max_clip_planes,
shaderc_limit_max_texture_units,
shaderc_limit_max_texture_coords,
shaderc_limit_max_vertex_attribs,
shaderc_limit_max_vertex_uniform_components,
shaderc_limit_max_varying_floats,
shaderc_limit_max_vertex_texture_image_units,
shaderc_limit_max_combined_texture_image_units,
shaderc_limit_max_texture_image_units,
shaderc_limit_max_fragment_uniform_components,
shaderc_limit_max_draw_buffers,
shaderc_limit_max_vertex_uniform_vectors,
shaderc_limit_max_varying_vectors,
shaderc_limit_max_fragment_uniform_vectors,
shaderc_limit_max_vertex_output_vectors,
shaderc_limit_max_fragment_input_vectors,
shaderc_limit_min_program_texel_offset,
shaderc_limit_max_program_texel_offset,
shaderc_limit_max_clip_distances,
shaderc_limit_max_compute_work_group_count_x,
shaderc_limit_max_compute_work_group_count_y,
shaderc_limit_max_compute_work_group_count_z,
shaderc_limit_max_compute_work_group_size_x,
shaderc_limit_max_compute_work_group_size_y,
shaderc_limit_max_compute_work_group_size_z,
shaderc_limit_max_compute_uniform_components,
shaderc_limit_max_compute_texture_image_units,
shaderc_limit_max_compute_image_uniforms,
shaderc_limit_max_compute_atomic_counters,
shaderc_limit_max_compute_atomic_counter_buffers,
shaderc_limit_max_varying_components,
shaderc_limit_max_vertex_output_components,
shaderc_limit_max_geometry_input_components,
shaderc_limit_max_geometry_output_components,
shaderc_limit_max_fragment_input_components,
shaderc_limit_max_image_units,
shaderc_limit_max_combined_image_units_and_fragment_outputs,
shaderc_limit_max_combined_shader_output_resources,
shaderc_limit_max_image_samples,
shaderc_limit_max_vertex_image_uniforms,
shaderc_limit_max_tess_control_image_uniforms,
shaderc_limit_max_tess_evaluation_image_uniforms,
shaderc_limit_max_geometry_image_uniforms,
shaderc_limit_max_fragment_image_uniforms,
shaderc_limit_max_combined_image_uniforms,
shaderc_limit_max_geometry_texture_image_units,
shaderc_limit_max_geometry_output_vertices,
shaderc_limit_max_geometry_total_output_components,
shaderc_limit_max_geometry_uniform_components,
shaderc_limit_max_geometry_varying_components,
shaderc_limit_max_tess_control_input_components,
shaderc_limit_max_tess_control_output_components,
shaderc_limit_max_tess_control_texture_image_units,
shaderc_limit_max_tess_control_uniform_components,
shaderc_limit_max_tess_control_total_output_components,
shaderc_limit_max_tess_evaluation_input_components,
shaderc_limit_max_tess_evaluation_output_components,
shaderc_limit_max_tess_evaluation_texture_image_units,
shaderc_limit_max_tess_evaluation_uniform_components,
shaderc_limit_max_tess_patch_components,
shaderc_limit_max_patch_vertices,
shaderc_limit_max_tess_gen_level,
shaderc_limit_max_viewports,
shaderc_limit_max_vertex_atomic_counters,
shaderc_limit_max_tess_control_atomic_counters,
shaderc_limit_max_tess_evaluation_atomic_counters,
shaderc_limit_max_geometry_atomic_counters,
shaderc_limit_max_fragment_atomic_counters,
shaderc_limit_max_combined_atomic_counters,
shaderc_limit_max_atomic_counter_bindings,
shaderc_limit_max_vertex_atomic_counter_buffers,
shaderc_limit_max_tess_control_atomic_counter_buffers,
shaderc_limit_max_tess_evaluation_atomic_counter_buffers,
shaderc_limit_max_geometry_atomic_counter_buffers,
shaderc_limit_max_fragment_atomic_counter_buffers,
shaderc_limit_max_combined_atomic_counter_buffers,
shaderc_limit_max_atomic_counter_buffer_size,
shaderc_limit_max_transform_feedback_buffers,
shaderc_limit_max_transform_feedback_interleaved_components,
shaderc_limit_max_cull_distances,
shaderc_limit_max_combined_clip_and_cull_distances,
shaderc_limit_max_samples,
} shaderc_limit;
// Uniform resource kinds.
// In Vulkan, uniform resources are bound to the pipeline via descriptors
// with numbered bindings and sets.
typedef enum {
// Image and image buffer.
shaderc_uniform_kind_image,
// Pure sampler.
shaderc_uniform_kind_sampler,
// Sampled texture in GLSL, and Shader Resource View in HLSL.
shaderc_uniform_kind_texture,
// Uniform Buffer Object (UBO) in GLSL. Cbuffer in HLSL.
shaderc_uniform_kind_buffer,
// Shader Storage Buffer Object (SSBO) in GLSL.
shaderc_uniform_kind_storage_buffer,
// Unordered Access View, in HLSL. (Writable storage image or storage
// buffer.)
shaderc_uniform_kind_unordered_access_view,
} shaderc_uniform_kind;
// Usage examples:
//
// Aggressively release compiler resources, but spend time in initialization
// for each new use.
// shaderc_compiler_t compiler = shaderc_compiler_initialize();
// shaderc_compilation_result_t result = shaderc_compile_into_spv(
// compiler, "#version 450\nvoid main() {}", 27,
// shaderc_glsl_vertex_shader, "main.vert", "main", nullptr);
// // Do stuff with compilation results.
// shaderc_result_release(result);
// shaderc_compiler_release(compiler);
//
// Keep the compiler object around for a long time, but pay for extra space
// occupied.
// shaderc_compiler_t compiler = shaderc_compiler_initialize();
// // On the same, other or multiple simultaneous threads.
// shaderc_compilation_result_t result = shaderc_compile_into_spv(
// compiler, "#version 450\nvoid main() {}", 27,
// shaderc_glsl_vertex_shader, "main.vert", "main", nullptr);
// // Do stuff with compilation results.
// shaderc_result_release(result);
// // Once no more compilations are to happen.
// shaderc_compiler_release(compiler);
// An opaque handle to an object that manages all compiler state.
typedef struct shaderc_compiler* shaderc_compiler_t;
// Returns a shaderc_compiler_t that can be used to compile modules.
// A return of NULL indicates that there was an error initializing the compiler.
// Any function operating on shaderc_compiler_t must offer the basic
// thread-safety guarantee.
// [http://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/]
// That is: concurrent invocation of these functions on DIFFERENT objects needs
// no synchronization; concurrent invocation of these functions on the SAME
// object requires synchronization IF AND ONLY IF some of them take a non-const
// argument.
SHADERC_EXPORT shaderc_compiler_t shaderc_compiler_initialize(void);
// Releases the resources held by the shaderc_compiler_t.
// After this call it is invalid to make any future calls to functions
// involving this shaderc_compiler_t.
SHADERC_EXPORT void shaderc_compiler_release(shaderc_compiler_t);
// An opaque handle to an object that manages options to a single compilation
// result.
typedef struct shaderc_compile_options* shaderc_compile_options_t;
// Returns a default-initialized shaderc_compile_options_t that can be used
// to modify the functionality of a compiled module.
// A return of NULL indicates that there was an error initializing the options.
// Any function operating on shaderc_compile_options_t must offer the
// basic thread-safety guarantee.
SHADERC_EXPORT shaderc_compile_options_t
shaderc_compile_options_initialize(void);
// Returns a copy of the given shaderc_compile_options_t.
// If NULL is passed as the parameter the call is the same as
// shaderc_compile_options_init.
SHADERC_EXPORT shaderc_compile_options_t shaderc_compile_options_clone(
const shaderc_compile_options_t options);
// Releases the compilation options. It is invalid to use the given
// shaderc_compile_options_t object in any future calls. It is safe to pass
// NULL to this function, and doing such will have no effect.
SHADERC_EXPORT void shaderc_compile_options_release(
shaderc_compile_options_t options);
// Adds a predefined macro to the compilation options. This has the same
// effect as passing -Dname=value to the command-line compiler. If value
// is NULL, it has the same effect as passing -Dname to the command-line
// compiler. If a macro definition with the same name has previously been
// added, the value is replaced with the new value. The macro name and
// value are passed in with char pointers, which point to their data, and
// the lengths of their data. The strings that the name and value pointers
// point to must remain valid for the duration of the call, but can be
// modified or deleted after this function has returned. In case of adding
// a valueless macro, the value argument should be a null pointer or the
// value_length should be 0u.
SHADERC_EXPORT void shaderc_compile_options_add_macro_definition(
shaderc_compile_options_t options, const char* name, size_t name_length,
const char* value, size_t value_length);
// Sets the source language. The default is GLSL.
SHADERC_EXPORT void shaderc_compile_options_set_source_language(
shaderc_compile_options_t options, shaderc_source_language lang);
// Sets the compiler mode to generate debug information in the output.
SHADERC_EXPORT void shaderc_compile_options_set_generate_debug_info(
shaderc_compile_options_t options);
// Sets the compiler optimization level to the given level. Only the last one
// takes effect if multiple calls of this function exist.
SHADERC_EXPORT void shaderc_compile_options_set_optimization_level(
shaderc_compile_options_t options, shaderc_optimization_level level);
// Forces the GLSL language version and profile to a given pair. The version
// number is the same as would appear in the #version annotation in the source.
// Version and profile specified here overrides the #version annotation in the
// source. Use profile: 'shaderc_profile_none' for GLSL versions that do not
// define profiles, e.g. versions below 150.
SHADERC_EXPORT void shaderc_compile_options_set_forced_version_profile(
shaderc_compile_options_t options, int version, shaderc_profile profile);
// Source text inclusion via #include is supported with a pair of callbacks
// to an "includer" on the client side. The first callback processes an
// inclusion request, and returns an include result. The includer owns
// the contents of the result, and those contents must remain valid until the
// second callback is invoked to release the result. Both callbacks take a
// user_data argument to specify the client context.
// To return an error, set the source_name to an empty string and put your
// error message in content.
// An include result.
typedef struct shaderc_include_result {
// The name of the source file. The name should be fully resolved
// in the sense that it should be a unique name in the context of the
// includer. For example, if the includer maps source names to files in
// a filesystem, then this name should be the absolute path of the file.
// For a failed inclusion, this string is empty.
const char* source_name;
size_t source_name_length;
// The text contents of the source file in the normal case.
// For a failed inclusion, this contains the error message.
const char* content;
size_t content_length;
// User data to be passed along with this request.
void* user_data;
} shaderc_include_result;
// The kinds of include requests.
enum shaderc_include_type {
shaderc_include_type_relative, // E.g. #include "source"
shaderc_include_type_standard // E.g. #include <source>
};
// An includer callback type for mapping an #include request to an include
// result. The user_data parameter specifies the client context. The
// requested_source parameter specifies the name of the source being requested.
// The type parameter specifies the kind of inclusion request being made.
// The requesting_source parameter specifies the name of the source containing
// the #include request. The includer owns the result object and its contents,
// and both must remain valid until the release callback is called on the result
// object.
typedef shaderc_include_result* (*shaderc_include_resolve_fn)(
void* user_data, const char* requested_source, int type,
const char* requesting_source, size_t include_depth);
// An includer callback type for destroying an include result.
typedef void (*shaderc_include_result_release_fn)(
void* user_data, shaderc_include_result* include_result);
// Sets includer callback functions.
SHADERC_EXPORT void shaderc_compile_options_set_include_callbacks(
shaderc_compile_options_t options, shaderc_include_resolve_fn resolver,
shaderc_include_result_release_fn result_releaser, void* user_data);
// Sets the compiler mode to suppress warnings, overriding warnings-as-errors
// mode. When both suppress-warnings and warnings-as-errors modes are
// turned on, warning messages will be inhibited, and will not be emitted
// as error messages.
SHADERC_EXPORT void shaderc_compile_options_set_suppress_warnings(
shaderc_compile_options_t options);
// Sets the target shader environment, affecting which warnings or errors will
// be issued. The version will be for distinguishing between different versions
// of the target environment. The version value should be either 0 or
// a value listed in shaderc_env_version. The 0 value maps to Vulkan 1.0 if
// |target| is Vulkan, and it maps to OpenGL 4.5 if |target| is OpenGL.
SHADERC_EXPORT void shaderc_compile_options_set_target_env(
shaderc_compile_options_t options,
shaderc_target_env target,
uint32_t version);
// Sets the target SPIR-V version. The generated module will use this version
// of SPIR-V. Each target environment determines what versions of SPIR-V
// it can consume. Defaults to the highest version of SPIR-V 1.0 which is
// required to be supported by the target environment. E.g. Default to SPIR-V
// 1.0 for Vulkan 1.0 and SPIR-V 1.3 for Vulkan 1.1.
SHADERC_EXPORT void shaderc_compile_options_set_target_spirv(
shaderc_compile_options_t options, shaderc_spirv_version version);
// Sets the compiler mode to treat all warnings as errors. Note the
// suppress-warnings mode overrides this option, i.e. if both
// warning-as-errors and suppress-warnings modes are set, warnings will not
// be emitted as error messages.
SHADERC_EXPORT void shaderc_compile_options_set_warnings_as_errors(
shaderc_compile_options_t options);
// Sets a resource limit.
SHADERC_EXPORT void shaderc_compile_options_set_limit(
shaderc_compile_options_t options, shaderc_limit limit, int value);
// Sets whether the compiler should automatically assign bindings to uniforms
// that aren't already explicitly bound in the shader source.
SHADERC_EXPORT void shaderc_compile_options_set_auto_bind_uniforms(
shaderc_compile_options_t options, bool auto_bind);
// Sets whether the compiler should automatically remove sampler variables
// and convert image variables to combined image-sampler variables.
SHADERC_EXPORT void shaderc_compile_options_set_auto_combined_image_sampler(
shaderc_compile_options_t options, bool upgrade);
// Sets whether the compiler should use HLSL IO mapping rules for bindings.
// Defaults to false.
SHADERC_EXPORT void shaderc_compile_options_set_hlsl_io_mapping(
shaderc_compile_options_t options, bool hlsl_iomap);
// Sets whether the compiler should determine block member offsets using HLSL
// packing rules instead of standard GLSL rules. Defaults to false. Only
// affects GLSL compilation. HLSL rules are always used when compiling HLSL.
SHADERC_EXPORT void shaderc_compile_options_set_hlsl_offsets(
shaderc_compile_options_t options, bool hlsl_offsets);
// Sets the base binding number used for for a uniform resource type when
// automatically assigning bindings. For GLSL compilation, sets the lowest
// automatically assigned number. For HLSL compilation, the regsiter number
// assigned to the resource is added to this specified base.
SHADERC_EXPORT void shaderc_compile_options_set_binding_base(
shaderc_compile_options_t options,
shaderc_uniform_kind kind,
uint32_t base);
// Like shaderc_compile_options_set_binding_base, but only takes effect when
// compiling a given shader stage. The stage is assumed to be one of vertex,
// fragment, tessellation evaluation, tesselation control, geometry, or compute.
SHADERC_EXPORT void shaderc_compile_options_set_binding_base_for_stage(
shaderc_compile_options_t options, shaderc_shader_kind shader_kind,
shaderc_uniform_kind kind, uint32_t base);
// Sets whether the compiler should automatically assign locations to
// uniform variables that don't have explicit locations in the shader source.
SHADERC_EXPORT void shaderc_compile_options_set_auto_map_locations(
shaderc_compile_options_t options, bool auto_map);
// Sets a descriptor set and binding for an HLSL register in the given stage.
// This method keeps a copy of the string data.
SHADERC_EXPORT void shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
shaderc_compile_options_t options, shaderc_shader_kind shader_kind,
const char* reg, const char* set, const char* binding);
// Like shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage,
// but affects all shader stages.
SHADERC_EXPORT void shaderc_compile_options_set_hlsl_register_set_and_binding(
shaderc_compile_options_t options, const char* reg, const char* set,
const char* binding);
// Sets whether the compiler should enable extension
// SPV_GOOGLE_hlsl_functionality1.
SHADERC_EXPORT void shaderc_compile_options_set_hlsl_functionality1(
shaderc_compile_options_t options, bool enable);
// Sets whether 16-bit types are supported in HLSL or not.
SHADERC_EXPORT void shaderc_compile_options_set_hlsl_16bit_types(
shaderc_compile_options_t options, bool enable);
// Sets whether the compiler should invert position.Y output in vertex shader.
SHADERC_EXPORT void shaderc_compile_options_set_invert_y(
shaderc_compile_options_t options, bool enable);
// Sets whether the compiler generates code for max and min builtins which,
// if given a NaN operand, will return the other operand. Similarly, the clamp
// builtin will favour the non-NaN operands, as if clamp were implemented
// as a composition of max and min.
SHADERC_EXPORT void shaderc_compile_options_set_nan_clamp(
shaderc_compile_options_t options, bool enable);
// An opaque handle to the results of a call to any shaderc_compile_into_*()
// function.
typedef struct shaderc_compilation_result* shaderc_compilation_result_t;
// Takes a GLSL source string and the associated shader kind, input file
// name, compiles it according to the given additional_options. If the shader
// kind is not set to a specified kind, but shaderc_glslc_infer_from_source,
// the compiler will try to deduce the shader kind from the source
// string and a failure in deducing will generate an error. Currently only
// #pragma annotation is supported. If the shader kind is set to one of the
// default shader kinds, the compiler will fall back to the default shader
// kind in case it failed to deduce the shader kind from source string.
// The input_file_name is a null-termintated string. It is used as a tag to
// identify the source string in cases like emitting error messages. It
// doesn't have to be a 'file name'.
// The source string will be compiled into SPIR-V binary and a
// shaderc_compilation_result will be returned to hold the results.
// The entry_point_name null-terminated string defines the name of the entry
// point to associate with this GLSL source. If the additional_options
// parameter is not null, then the compilation is modified by any options
// present. May be safely called from multiple threads without explicit
// synchronization. If there was failure in allocating the compiler object,
// null will be returned.
SHADERC_EXPORT shaderc_compilation_result_t shaderc_compile_into_spv(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options);
// Like shaderc_compile_into_spv, but the result contains SPIR-V assembly text
// instead of a SPIR-V binary module. The SPIR-V assembly syntax is as defined
// by the SPIRV-Tools open source project.
SHADERC_EXPORT shaderc_compilation_result_t shaderc_compile_into_spv_assembly(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options);
// Like shaderc_compile_into_spv, but the result contains preprocessed source
// code instead of a SPIR-V binary module
SHADERC_EXPORT shaderc_compilation_result_t shaderc_compile_into_preprocessed_text(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options);
// Takes an assembly string of the format defined in the SPIRV-Tools project
// (https://github.com/KhronosGroup/SPIRV-Tools/blob/master/syntax.md),
// assembles it into SPIR-V binary and a shaderc_compilation_result will be
// returned to hold the results.
// The assembling will pick options suitable for assembling specified in the
// additional_options parameter.
// May be safely called from multiple threads without explicit synchronization.
// If there was failure in allocating the compiler object, null will be
// returned.
SHADERC_EXPORT shaderc_compilation_result_t shaderc_assemble_into_spv(
const shaderc_compiler_t compiler, const char* source_assembly,
size_t source_assembly_size,
const shaderc_compile_options_t additional_options);
// The following functions, operating on shaderc_compilation_result_t objects,
// offer only the basic thread-safety guarantee.
// Releases the resources held by the result object. It is invalid to use the
// result object for any further operations.
SHADERC_EXPORT void shaderc_result_release(shaderc_compilation_result_t result);
// Returns the number of bytes of the compilation output data in a result
// object.
SHADERC_EXPORT size_t shaderc_result_get_length(const shaderc_compilation_result_t result);
// Returns the number of warnings generated during the compilation.
SHADERC_EXPORT size_t shaderc_result_get_num_warnings(
const shaderc_compilation_result_t result);
// Returns the number of errors generated during the compilation.
SHADERC_EXPORT size_t shaderc_result_get_num_errors(const shaderc_compilation_result_t result);
// Returns the compilation status, indicating whether the compilation succeeded,
// or failed due to some reasons, like invalid shader stage or compilation
// errors.
SHADERC_EXPORT shaderc_compilation_status shaderc_result_get_compilation_status(
const shaderc_compilation_result_t);
// Returns a pointer to the start of the compilation output data bytes, either
// SPIR-V binary or char string. When the source string is compiled into SPIR-V
// binary, this is guaranteed to be castable to a uint32_t*. If the result
// contains assembly text or preprocessed source text, the pointer will point to
// the resulting array of characters.
SHADERC_EXPORT const char* shaderc_result_get_bytes(const shaderc_compilation_result_t result);
// Returns a null-terminated string that contains any error messages generated
// during the compilation.
SHADERC_EXPORT const char* shaderc_result_get_error_message(
const shaderc_compilation_result_t result);
// Provides the version & revision of the SPIR-V which will be produced
SHADERC_EXPORT void shaderc_get_spv_version(unsigned int* version, unsigned int* revision);
// Parses the version and profile from a given null-terminated string
// containing both version and profile, like: '450core'. Returns false if
// the string can not be parsed. Returns true when the parsing succeeds. The
// parsed version and profile are returned through arguments.
SHADERC_EXPORT bool shaderc_parse_version_profile(const char* str, int* version,
shaderc_profile* profile);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // SHADERC_SHADERC_H_

View File

@ -0,0 +1,607 @@
// Copyright 2015 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SHADERC_SHADERC_HPP_
#define SHADERC_SHADERC_HPP_
#include <memory>
#include <string>
#include <vector>
#include "shaderc.h"
namespace shaderc {
// A CompilationResult contains the compiler output, compilation status,
// and messages.
//
// The compiler output is stored as an array of elements and accessed
// via random access iterators provided by cbegin() and cend(). The iterators
// are contiguous in the sense of "Contiguous Iterators: A Refinement of
// Random Access Iterators", Nevin Liber, C++ Library Evolution Working
// Group Working Paper N3884.
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3884.pdf
//
// Methods begin() and end() are also provided to enable range-based for.
// They are synonyms to cbegin() and cend(), respectively.
template <typename OutputElementType>
class CompilationResult {
public:
typedef OutputElementType element_type;
// The type used to describe the begin and end iterators on the
// compiler output.
typedef const OutputElementType* const_iterator;
// Upon creation, the CompilationResult takes ownership of the
// shaderc_compilation_result instance. During destruction of the
// CompilationResult, the shaderc_compilation_result will be released.
explicit CompilationResult(shaderc_compilation_result_t compilation_result)
: compilation_result_(compilation_result) {}
CompilationResult() : compilation_result_(nullptr) {}
~CompilationResult() { shaderc_result_release(compilation_result_); }
CompilationResult(CompilationResult&& other) : compilation_result_(nullptr) {
*this = std::move(other);
}
CompilationResult& operator=(CompilationResult&& other) {
if (compilation_result_) {
shaderc_result_release(compilation_result_);
}
compilation_result_ = other.compilation_result_;
other.compilation_result_ = nullptr;
return *this;
}
// Returns any error message found during compilation.
std::string GetErrorMessage() const {
if (!compilation_result_) {
return "";
}
return shaderc_result_get_error_message(compilation_result_);
}
// Returns the compilation status, indicating whether the compilation
// succeeded, or failed due to some reasons, like invalid shader stage or
// compilation errors.
shaderc_compilation_status GetCompilationStatus() const {
if (!compilation_result_) {
return shaderc_compilation_status_null_result_object;
}
return shaderc_result_get_compilation_status(compilation_result_);
}
// Returns a random access (contiguous) iterator pointing to the start
// of the compilation output. It is valid for the lifetime of this object.
// If there is no compilation result, then returns nullptr.
const_iterator cbegin() const {
if (!compilation_result_) return nullptr;
return reinterpret_cast<const_iterator>(
shaderc_result_get_bytes(compilation_result_));
}
// Returns a random access (contiguous) iterator pointing to the end of
// the compilation output. It is valid for the lifetime of this object.
// If there is no compilation result, then returns nullptr.
const_iterator cend() const {
if (!compilation_result_) return nullptr;
return cbegin() +
shaderc_result_get_length(compilation_result_) /
sizeof(OutputElementType);
}
// Returns the same iterator as cbegin().
const_iterator begin() const { return cbegin(); }
// Returns the same iterator as cend().
const_iterator end() const { return cend(); }
// Returns the number of warnings generated during the compilation.
size_t GetNumWarnings() const {
if (!compilation_result_) {
return 0;
}
return shaderc_result_get_num_warnings(compilation_result_);
}
// Returns the number of errors generated during the compilation.
size_t GetNumErrors() const {
if (!compilation_result_) {
return 0;
}
return shaderc_result_get_num_errors(compilation_result_);
}
private:
CompilationResult(const CompilationResult& other) = delete;
CompilationResult& operator=(const CompilationResult& other) = delete;
shaderc_compilation_result_t compilation_result_;
};
// A compilation result for a SPIR-V binary module, which is an array
// of uint32_t words.
using SpvCompilationResult = CompilationResult<uint32_t>;
// A compilation result in SPIR-V assembly syntax.
using AssemblyCompilationResult = CompilationResult<char>;
// Preprocessed source text.
using PreprocessedSourceCompilationResult = CompilationResult<char>;
// Contains any options that can have default values for a compilation.
class CompileOptions {
public:
CompileOptions() { options_ = shaderc_compile_options_initialize(); }
~CompileOptions() { shaderc_compile_options_release(options_); }
CompileOptions(const CompileOptions& other) {
options_ = shaderc_compile_options_clone(other.options_);
}
CompileOptions(CompileOptions&& other) {
options_ = other.options_;
other.options_ = nullptr;
}
// Adds a predefined macro to the compilation options. It behaves the same as
// shaderc_compile_options_add_macro_definition in shaderc.h.
void AddMacroDefinition(const char* name, size_t name_length,
const char* value, size_t value_length) {
shaderc_compile_options_add_macro_definition(options_, name, name_length,
value, value_length);
}
// Adds a valueless predefined macro to the compilation options.
void AddMacroDefinition(const std::string& name) {
AddMacroDefinition(name.c_str(), name.size(), nullptr, 0u);
}
// Adds a predefined macro to the compilation options.
void AddMacroDefinition(const std::string& name, const std::string& value) {
AddMacroDefinition(name.c_str(), name.size(), value.c_str(), value.size());
}
// Sets the compiler mode to generate debug information in the output.
void SetGenerateDebugInfo() {
shaderc_compile_options_set_generate_debug_info(options_);
}
// Sets the compiler optimization level to the given level. Only the last one
// takes effect if multiple calls of this function exist.
void SetOptimizationLevel(shaderc_optimization_level level) {
shaderc_compile_options_set_optimization_level(options_, level);
}
// A C++ version of the libshaderc includer interface.
class IncluderInterface {
public:
// Handles shaderc_include_resolver_fn callbacks.
virtual shaderc_include_result* GetInclude(const char* requested_source,
shaderc_include_type type,
const char* requesting_source,
size_t include_depth) = 0;
// Handles shaderc_include_result_release_fn callbacks.
virtual void ReleaseInclude(shaderc_include_result* data) = 0;
virtual ~IncluderInterface() = default;
};
// Sets the includer instance for libshaderc to call during compilation, as
// described in shaderc_compile_options_set_include_callbacks(). Callbacks
// are routed to this includer's methods.
void SetIncluder(std::unique_ptr<IncluderInterface>&& includer) {
includer_ = std::move(includer);
shaderc_compile_options_set_include_callbacks(
options_,
[](void* user_data, const char* requested_source, int type,
const char* requesting_source, size_t include_depth) {
auto* sub_includer = static_cast<IncluderInterface*>(user_data);
return sub_includer->GetInclude(
requested_source, static_cast<shaderc_include_type>(type),
requesting_source, include_depth);
},
[](void* user_data, shaderc_include_result* include_result) {
auto* sub_includer = static_cast<IncluderInterface*>(user_data);
return sub_includer->ReleaseInclude(include_result);
},
includer_.get());
}
// Forces the GLSL language version and profile to a given pair. The version
// number is the same as would appear in the #version annotation in the
// source. Version and profile specified here overrides the #version
// annotation in the source. Use profile: 'shaderc_profile_none' for GLSL
// versions that do not define profiles, e.g. versions below 150.
void SetForcedVersionProfile(int version, shaderc_profile profile) {
shaderc_compile_options_set_forced_version_profile(options_, version,
profile);
}
// Sets the compiler mode to suppress warnings. Note this option overrides
// warnings-as-errors mode. When both suppress-warnings and warnings-as-errors
// modes are turned on, warning messages will be inhibited, and will not be
// emitted as error message.
void SetSuppressWarnings() {
shaderc_compile_options_set_suppress_warnings(options_);
}
// Sets the source language. The default is GLSL.
void SetSourceLanguage(shaderc_source_language lang) {
shaderc_compile_options_set_source_language(options_, lang);
}
// Sets the target shader environment, affecting which warnings or errors will
// be issued. The version will be for distinguishing between different
// versions of the target environment. The version value should be either 0
// or a value listed in shaderc_env_version. The 0 value maps to Vulkan 1.0
// if |target| is Vulkan, and it maps to OpenGL 4.5 if |target| is OpenGL.
void SetTargetEnvironment(shaderc_target_env target, uint32_t version) {
shaderc_compile_options_set_target_env(options_, target, version);
}
// Sets the target SPIR-V version. The generated module will use this version
// of SPIR-V. Each target environment determines what versions of SPIR-V
// it can consume. Defaults to the highest version of SPIR-V 1.0 which is
// required to be supported by the target environment. E.g. Default to SPIR-V
// 1.0 for Vulkan 1.0 and SPIR-V 1.3 for Vulkan 1.1.
void SetTargetSpirv(shaderc_spirv_version version) {
shaderc_compile_options_set_target_spirv(options_, version);
}
// Sets the compiler mode to make all warnings into errors. Note the
// suppress-warnings mode overrides this option, i.e. if both
// warning-as-errors and suppress-warnings modes are set on, warnings will not
// be emitted as error message.
void SetWarningsAsErrors() {
shaderc_compile_options_set_warnings_as_errors(options_);
}
// Sets a resource limit.
void SetLimit(shaderc_limit limit, int value) {
shaderc_compile_options_set_limit(options_, limit, value);
}
// Sets whether the compiler should automatically assign bindings to uniforms
// that aren't already explicitly bound in the shader source.
void SetAutoBindUniforms(bool auto_bind) {
shaderc_compile_options_set_auto_bind_uniforms(options_, auto_bind);
}
// Sets whether the compiler should automatically remove sampler variables
// and convert image variables to combined image sampler variables.
void SetAutoSampledTextures(bool auto_sampled) {
shaderc_compile_options_set_auto_combined_image_sampler(options_,
auto_sampled);
}
// Sets whether the compiler should use HLSL IO mapping rules for bindings.
// Defaults to false.
void SetHlslIoMapping(bool hlsl_iomap) {
shaderc_compile_options_set_hlsl_io_mapping(options_, hlsl_iomap);
}
// Sets whether the compiler should determine block member offsets using HLSL
// packing rules instead of standard GLSL rules. Defaults to false. Only
// affects GLSL compilation. HLSL rules are always used when compiling HLSL.
void SetHlslOffsets(bool hlsl_offsets) {
shaderc_compile_options_set_hlsl_offsets(options_, hlsl_offsets);
}
// Sets the base binding number used for for a uniform resource type when
// automatically assigning bindings. For GLSL compilation, sets the lowest
// automatically assigned number. For HLSL compilation, the regsiter number
// assigned to the resource is added to this specified base.
void SetBindingBase(shaderc_uniform_kind kind, uint32_t base) {
shaderc_compile_options_set_binding_base(options_, kind, base);
}
// Like SetBindingBase, but only takes effect when compiling a given shader
// stage. The stage is assumed to be one of vertex, fragment, tessellation
// evaluation, tesselation control, geometry, or compute.
void SetBindingBaseForStage(shaderc_shader_kind shader_kind,
shaderc_uniform_kind kind, uint32_t base) {
shaderc_compile_options_set_binding_base_for_stage(options_, shader_kind,
kind, base);
}
// Sets whether the compiler automatically assigns locations to
// uniform variables that don't have explicit locations.
void SetAutoMapLocations(bool auto_map) {
shaderc_compile_options_set_auto_map_locations(options_, auto_map);
}
// Sets a descriptor set and binding for an HLSL register in the given stage.
// Copies the parameter strings.
void SetHlslRegisterSetAndBindingForStage(shaderc_shader_kind shader_kind,
const std::string& reg,
const std::string& set,
const std::string& binding) {
shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
options_, shader_kind, reg.c_str(), set.c_str(), binding.c_str());
}
// Sets a descriptor set and binding for an HLSL register in any stage.
// Copies the parameter strings.
void SetHlslRegisterSetAndBinding(const std::string& reg,
const std::string& set,
const std::string& binding) {
shaderc_compile_options_set_hlsl_register_set_and_binding(
options_, reg.c_str(), set.c_str(), binding.c_str());
}
// Sets whether the compiler should enable extension
// SPV_GOOGLE_hlsl_functionality1.
void SetHlslFunctionality1(bool enable) {
shaderc_compile_options_set_hlsl_functionality1(options_, enable);
}
// Sets whether 16-bit types are supported in HLSL or not.
void SetHlsl16BitTypes(bool enable) {
shaderc_compile_options_set_hlsl_16bit_types(options_, enable);
}
// Sets whether the compiler should invert position.Y output in vertex shader.
void SetInvertY(bool enable) {
shaderc_compile_options_set_invert_y(options_, enable);
}
// Sets whether the compiler should generates code for max an min which,
// if given a NaN operand, will return the other operand. Similarly, the
// clamp builtin will favour the non-NaN operands, as if clamp were
// implemented as a composition of max and min.
void SetNanClamp(bool enable) {
shaderc_compile_options_set_nan_clamp(options_, enable);
}
private:
CompileOptions& operator=(const CompileOptions& other) = delete;
shaderc_compile_options_t options_;
std::unique_ptr<IncluderInterface> includer_;
friend class Compiler;
};
// The compilation context for compiling source to SPIR-V.
class Compiler {
public:
Compiler() : compiler_(shaderc_compiler_initialize()) {}
~Compiler() { shaderc_compiler_release(compiler_); }
Compiler(Compiler&& other) {
compiler_ = other.compiler_;
other.compiler_ = nullptr;
}
bool IsValid() const { return compiler_ != nullptr; }
// Compiles the given source GLSL and returns a SPIR-V binary module
// compilation result.
// The source_text parameter must be a valid pointer.
// The source_text_size parameter must be the length of the source text.
// The shader_kind parameter either forces the compilation to be done with a
// specified shader kind, or hint the compiler how to determine the exact
// shader kind. If the shader kind is set to shaderc_glslc_infer_from_source,
// the compiler will try to deduce the shader kind from the source string and
// a failure in this proess will generate an error. Currently only #pragma
// annotation is supported. If the shader kind is set to one of the default
// shader kinds, the compiler will fall back to the specified default shader
// kind in case it failed to deduce the shader kind from the source string.
// The input_file_name is a null-termintated string. It is used as a tag to
// identify the source string in cases like emitting error messages. It
// doesn't have to be a 'file name'.
// The entry_point_name parameter is a null-terminated string specifying
// the entry point name for HLSL compilation. For GLSL compilation, the
// entry point name is assumed to be "main".
// The compilation is passed any options specified in the CompileOptions
// parameter.
// It is valid for the returned CompilationResult object to outlive this
// compiler object.
// Note when the options_ has disassembly mode or preprocessing only mode set
// on, the returned CompilationResult will hold a text string, instead of a
// SPIR-V binary generated with default options.
SpvCompilationResult CompileGlslToSpv(const char* source_text,
size_t source_text_size,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const char* entry_point_name,
const CompileOptions& options) const {
shaderc_compilation_result_t compilation_result = shaderc_compile_into_spv(
compiler_, source_text, source_text_size, shader_kind, input_file_name,
entry_point_name, options.options_);
return SpvCompilationResult(compilation_result);
}
// Compiles the given source shader and returns a SPIR-V binary module
// compilation result.
// Like the first CompileGlslToSpv method but assumes the entry point name
// is "main".
SpvCompilationResult CompileGlslToSpv(const char* source_text,
size_t source_text_size,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const CompileOptions& options) const {
return CompileGlslToSpv(source_text, source_text_size, shader_kind,
input_file_name, "main", options);
}
// Compiles the given source GLSL and returns a SPIR-V binary module
// compilation result.
// Like the previous CompileGlslToSpv method but uses default options.
SpvCompilationResult CompileGlslToSpv(const char* source_text,
size_t source_text_size,
shaderc_shader_kind shader_kind,
const char* input_file_name) const {
shaderc_compilation_result_t compilation_result =
shaderc_compile_into_spv(compiler_, source_text, source_text_size,
shader_kind, input_file_name, "main", nullptr);
return SpvCompilationResult(compilation_result);
}
// Compiles the given source shader and returns a SPIR-V binary module
// compilation result.
// Like the first CompileGlslToSpv method but the source is provided as
// a std::string, and we assume the entry point is "main".
SpvCompilationResult CompileGlslToSpv(const std::string& source_text,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const CompileOptions& options) const {
return CompileGlslToSpv(source_text.data(), source_text.size(), shader_kind,
input_file_name, options);
}
// Compiles the given source shader and returns a SPIR-V binary module
// compilation result.
// Like the first CompileGlslToSpv method but the source is provided as
// a std::string.
SpvCompilationResult CompileGlslToSpv(const std::string& source_text,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const char* entry_point_name,
const CompileOptions& options) const {
return CompileGlslToSpv(source_text.data(), source_text.size(), shader_kind,
input_file_name, entry_point_name, options);
}
// Compiles the given source GLSL and returns a SPIR-V binary module
// compilation result.
// Like the previous CompileGlslToSpv method but assumes the entry point
// name is "main".
SpvCompilationResult CompileGlslToSpv(const std::string& source_text,
shaderc_shader_kind shader_kind,
const char* input_file_name) const {
return CompileGlslToSpv(source_text.data(), source_text.size(), shader_kind,
input_file_name);
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// The assembly should follow the syntax defined in the SPIRV-Tools project
// (https://github.com/KhronosGroup/SPIRV-Tools/blob/master/syntax.md).
// It is valid for the returned CompilationResult object to outlive this
// compiler object.
// The assembling will pick options suitable for assembling specified in the
// CompileOptions parameter.
SpvCompilationResult AssembleToSpv(const char* source_assembly,
size_t source_assembly_size,
const CompileOptions& options) const {
return SpvCompilationResult(shaderc_assemble_into_spv(
compiler_, source_assembly, source_assembly_size, options.options_));
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// Like the first AssembleToSpv method but uses the default compiler options.
SpvCompilationResult AssembleToSpv(const char* source_assembly,
size_t source_assembly_size) const {
return SpvCompilationResult(shaderc_assemble_into_spv(
compiler_, source_assembly, source_assembly_size, nullptr));
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// Like the first AssembleToSpv method but the source is provided as a
// std::string.
SpvCompilationResult AssembleToSpv(const std::string& source_assembly,
const CompileOptions& options) const {
return SpvCompilationResult(
shaderc_assemble_into_spv(compiler_, source_assembly.data(),
source_assembly.size(), options.options_));
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// Like the first AssembleToSpv method but the source is provided as a
// std::string and also uses default compiler options.
SpvCompilationResult AssembleToSpv(const std::string& source_assembly) const {
return SpvCompilationResult(shaderc_assemble_into_spv(
compiler_, source_assembly.data(), source_assembly.size(), nullptr));
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// compilation result.
// Options are similar to the first CompileToSpv method.
AssemblyCompilationResult CompileGlslToSpvAssembly(
const char* source_text, size_t source_text_size,
shaderc_shader_kind shader_kind, const char* input_file_name,
const char* entry_point_name, const CompileOptions& options) const {
shaderc_compilation_result_t compilation_result =
shaderc_compile_into_spv_assembly(
compiler_, source_text, source_text_size, shader_kind,
input_file_name, entry_point_name, options.options_);
return AssemblyCompilationResult(compilation_result);
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// compilation result.
// Similare to the previous method, but assumes entry point name is "main".
AssemblyCompilationResult CompileGlslToSpvAssembly(
const char* source_text, size_t source_text_size,
shaderc_shader_kind shader_kind, const char* input_file_name,
const CompileOptions& options) const {
return CompileGlslToSpvAssembly(source_text, source_text_size, shader_kind,
input_file_name, "main", options);
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// result. Like the first CompileGlslToSpvAssembly method but the source
// is provided as a std::string. Options are otherwise similar to
// the first CompileToSpv method.
AssemblyCompilationResult CompileGlslToSpvAssembly(
const std::string& source_text, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const CompileOptions& options) const {
return CompileGlslToSpvAssembly(source_text.data(), source_text.size(),
shader_kind, input_file_name,
entry_point_name, options);
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// result. Like the previous CompileGlslToSpvAssembly method but assumes
// the entry point name is "main".
AssemblyCompilationResult CompileGlslToSpvAssembly(
const std::string& source_text, shaderc_shader_kind shader_kind,
const char* input_file_name, const CompileOptions& options) const {
return CompileGlslToSpvAssembly(source_text, shader_kind, input_file_name,
"main", options);
}
// Preprocesses the given source GLSL and returns the preprocessed
// source text as a compilation result.
// Options are similar to the first CompileToSpv method.
PreprocessedSourceCompilationResult PreprocessGlsl(
const char* source_text, size_t source_text_size,
shaderc_shader_kind shader_kind, const char* input_file_name,
const CompileOptions& options) const {
shaderc_compilation_result_t compilation_result =
shaderc_compile_into_preprocessed_text(
compiler_, source_text, source_text_size, shader_kind,
input_file_name, "main", options.options_);
return PreprocessedSourceCompilationResult(compilation_result);
}
// Preprocesses the given source GLSL and returns text result. Like the first
// PreprocessGlsl method but the source is provided as a std::string.
// Options are otherwise similar to the first CompileToSpv method.
PreprocessedSourceCompilationResult PreprocessGlsl(
const std::string& source_text, shaderc_shader_kind shader_kind,
const char* input_file_name, const CompileOptions& options) const {
return PreprocessGlsl(source_text.data(), source_text.size(), shader_kind,
input_file_name, options);
}
private:
Compiler(const Compiler&) = delete;
Compiler& operator=(const Compiler& other) = delete;
shaderc_compiler_t compiler_;
};
} // namespace shaderc
#endif // SHADERC_SHADERC_HPP_

View File

@ -0,0 +1,39 @@
// Copyright 2018 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SHADERC_STATUS_H_
#define SHADERC_STATUS_H_
#ifdef __cplusplus
extern "C" {
#endif
// Indicate the status of a compilation.
typedef enum {
shaderc_compilation_status_success = 0,
shaderc_compilation_status_invalid_stage = 1, // error stage deduction
shaderc_compilation_status_compilation_error = 2,
shaderc_compilation_status_internal_error = 3, // unexpected failure
shaderc_compilation_status_null_result_object = 4,
shaderc_compilation_status_invalid_assembly = 5,
shaderc_compilation_status_validation_error = 6,
shaderc_compilation_status_transformation_error = 7,
shaderc_compilation_status_configuration_error = 8,
} shaderc_compilation_status;
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // SHADERC_STATUS_H_

View File

@ -0,0 +1,37 @@
// Copyright 2018 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SHADERC_VISIBILITY_H_
#define SHADERC_VISIBILITY_H_
// SHADERC_EXPORT tags symbol that will be exposed by the shared libraries.
#if defined(SHADERC_SHAREDLIB)
#if defined(_WIN32)
#if defined(SHADERC_IMPLEMENTATION)
#define SHADERC_EXPORT __declspec(dllexport)
#else
#define SHADERC_EXPORT __declspec(dllimport)
#endif
#else
#if defined(SHADERC_IMPLEMENTATION)
#define SHADERC_EXPORT __attribute__((visibility("default")))
#else
#define SHADERC_EXPORT
#endif
#endif
#else
#define SHADERC_EXPORT
#endif
#endif // SHADERC_VISIBILITY_H_

View File

@ -0,0 +1,799 @@
// Copyright 2015 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <memory>
#include <sstream>
#include <vector>
#include "libshaderc_util/compiler.h"
#include "libshaderc_util/counting_includer.h"
#include "libshaderc_util/resources.h"
#include "libshaderc_util/spirv_tools_wrapper.h"
#include "libshaderc_util/version_profile.h"
#include "shaderc_private.h"
#include "spirv/unified1/spirv.hpp"
#if (defined(_MSC_VER) && !defined(_CPPUNWIND)) || !defined(__EXCEPTIONS)
#define TRY_IF_EXCEPTIONS_ENABLED
#define CATCH_IF_EXCEPTIONS_ENABLED(X) if (0)
#else
#define TRY_IF_EXCEPTIONS_ENABLED try
#define CATCH_IF_EXCEPTIONS_ENABLED(X) catch (X)
#endif
namespace {
// Returns shader stage (ie: vertex, fragment, etc.) in response to forced
// shader kinds. If the shader kind is not a forced kind, returns EshLangCount
// to let #pragma annotation or shader stage deducer determine the stage to
// use.
EShLanguage GetForcedStage(shaderc_shader_kind kind) {
switch (kind) {
case shaderc_glsl_vertex_shader:
return EShLangVertex;
case shaderc_glsl_fragment_shader:
return EShLangFragment;
case shaderc_glsl_compute_shader:
return EShLangCompute;
case shaderc_glsl_geometry_shader:
return EShLangGeometry;
case shaderc_glsl_tess_control_shader:
return EShLangTessControl;
case shaderc_glsl_tess_evaluation_shader:
return EShLangTessEvaluation;
case shaderc_glsl_raygen_shader:
return EShLangRayGenNV;
case shaderc_glsl_anyhit_shader:
return EShLangAnyHitNV;
case shaderc_glsl_closesthit_shader:
return EShLangClosestHitNV;
case shaderc_glsl_miss_shader:
return EShLangMissNV;
case shaderc_glsl_intersection_shader:
return EShLangIntersectNV;
case shaderc_glsl_callable_shader:
return EShLangCallableNV;
case shaderc_glsl_task_shader:
return EShLangTaskNV;
case shaderc_glsl_mesh_shader:
return EShLangMeshNV;
case shaderc_glsl_infer_from_source:
case shaderc_glsl_default_vertex_shader:
case shaderc_glsl_default_fragment_shader:
case shaderc_glsl_default_compute_shader:
case shaderc_glsl_default_geometry_shader:
case shaderc_glsl_default_tess_control_shader:
case shaderc_glsl_default_tess_evaluation_shader:
case shaderc_glsl_default_raygen_shader:
case shaderc_glsl_default_anyhit_shader:
case shaderc_glsl_default_closesthit_shader:
case shaderc_glsl_default_miss_shader:
case shaderc_glsl_default_intersection_shader:
case shaderc_glsl_default_callable_shader:
case shaderc_glsl_default_task_shader:
case shaderc_glsl_default_mesh_shader:
case shaderc_spirv_assembly:
return EShLangCount;
}
assert(0 && "Unhandled shaderc_shader_kind");
return EShLangCount;
}
// A wrapper functor class to be used as stage deducer for libshaderc_util
// Compile() interface. When the given shader kind is one of the default shader
// kinds, this functor will be called if #pragma is not found in the source
// code. And it returns the corresponding shader stage. When the shader kind is
// a forced shader kind, this functor won't be called and it simply returns
// EShLangCount to make the syntax correct. When the shader kind is set to
// shaderc_glsl_deduce_from_pragma, this functor also returns EShLangCount, but
// the compiler should emit error if #pragma annotation is not found in this
// case.
class StageDeducer {
public:
explicit StageDeducer(
shaderc_shader_kind kind = shaderc_glsl_infer_from_source)
: kind_(kind), error_(false){}
// The method that underlying glslang will call to determine the shader stage
// to be used in current compilation. It is called only when there is neither
// forced shader kind (or say stage, in the view of glslang), nor #pragma
// annotation in the source code. This method transforms an user defined
// 'default' shader kind to the corresponding shader stage. As this is the
// last trial to determine the shader stage, failing to find the corresponding
// shader stage will record an error.
// Note that calling this method more than once during one compilation will
// have the error recorded for the previous call been overwriten by the next
// call.
EShLanguage operator()(std::ostream* /*error_stream*/,
const shaderc_util::string_piece& /*error_tag*/) {
EShLanguage stage = GetDefaultStage(kind_);
if (stage == EShLangCount) {
error_ = true;
} else {
error_ = false;
}
return stage;
}
// Returns true if there is error during shader stage deduction.
bool error() const { return error_; }
private:
// Gets the corresponding shader stage for a given 'default' shader kind. All
// other kinds are mapped to EShLangCount which should not be used.
EShLanguage GetDefaultStage(shaderc_shader_kind kind) const {
switch (kind) {
case shaderc_glsl_vertex_shader:
case shaderc_glsl_fragment_shader:
case shaderc_glsl_compute_shader:
case shaderc_glsl_geometry_shader:
case shaderc_glsl_tess_control_shader:
case shaderc_glsl_tess_evaluation_shader:
case shaderc_glsl_infer_from_source:
case shaderc_glsl_raygen_shader:
case shaderc_glsl_anyhit_shader:
case shaderc_glsl_closesthit_shader:
case shaderc_glsl_miss_shader:
case shaderc_glsl_intersection_shader:
case shaderc_glsl_callable_shader:
case shaderc_glsl_task_shader:
case shaderc_glsl_mesh_shader:
return EShLangCount;
case shaderc_glsl_default_vertex_shader:
return EShLangVertex;
case shaderc_glsl_default_fragment_shader:
return EShLangFragment;
case shaderc_glsl_default_compute_shader:
return EShLangCompute;
case shaderc_glsl_default_geometry_shader:
return EShLangGeometry;
case shaderc_glsl_default_tess_control_shader:
return EShLangTessControl;
case shaderc_glsl_default_tess_evaluation_shader:
return EShLangTessEvaluation;
case shaderc_glsl_default_raygen_shader:
return EShLangRayGenNV;
case shaderc_glsl_default_anyhit_shader:
return EShLangAnyHitNV;
case shaderc_glsl_default_closesthit_shader:
return EShLangClosestHitNV;
case shaderc_glsl_default_miss_shader:
return EShLangMissNV;
case shaderc_glsl_default_intersection_shader:
return EShLangIntersectNV;
case shaderc_glsl_default_callable_shader:
return EShLangCallableNV;
case shaderc_glsl_default_task_shader:
return EShLangTaskNV;
case shaderc_glsl_default_mesh_shader:
return EShLangMeshNV;
case shaderc_spirv_assembly:
return EShLangCount;
}
assert(0 && "Unhandled shaderc_shader_kind");
return EShLangCount;
}
shaderc_shader_kind kind_;
bool error_;
};
// A bridge between the libshaderc includer and libshaderc_util includer.
class InternalFileIncluder : public shaderc_util::CountingIncluder {
public:
InternalFileIncluder(const shaderc_include_resolve_fn resolver,
const shaderc_include_result_release_fn result_releaser,
void* user_data)
: resolver_(resolver),
result_releaser_(result_releaser),
user_data_(user_data){}
InternalFileIncluder()
: resolver_(nullptr), result_releaser_(nullptr), user_data_(nullptr){}
private:
// Check the validity of the callbacks.
bool AreValidCallbacks() const {
return resolver_ != nullptr && result_releaser_ != nullptr;
}
// Maps CountingIncluder IncludeType value to a shaderc_include_type
// value.
shaderc_include_type GetIncludeType(IncludeType type) {
switch (type) {
case IncludeType::Local:
return shaderc_include_type_relative;
case IncludeType::System:
return shaderc_include_type_standard;
default:
break;
}
assert(0 && "Unhandled IncludeType");
return shaderc_include_type_relative;
}
// Resolves an include request for the requested source of the given
// type in the context of the specified requesting source. On success,
// returns a newly allocated IncludeResponse containing the fully resolved
// name of the requested source and the contents of that source.
// On failure, returns a newly allocated IncludeResponse where the
// resolved name member is an empty string, and the contents members
// contains error details.
virtual glslang::TShader::Includer::IncludeResult* include_delegate(
const char* requested_source, const char* requesting_source,
IncludeType type, size_t include_depth) override {
if (!AreValidCallbacks()) {
static const char kUnexpectedIncludeError[] =
"#error unexpected include directive";
return new glslang::TShader::Includer::IncludeResult{
"", kUnexpectedIncludeError, strlen(kUnexpectedIncludeError),
nullptr};
}
shaderc_include_result* include_result =
resolver_(user_data_, requested_source, GetIncludeType(type),
requesting_source, include_depth);
// Make a glslang IncludeResult from a shaderc_include_result. The
// user_data member of the IncludeResult is a pointer to the
// shaderc_include_result object, so we can later release the latter.
return new glslang::TShader::Includer::IncludeResult{
std::string(include_result->source_name,
include_result->source_name_length),
include_result->content, include_result->content_length,
include_result};
}
// Releases the given IncludeResult.
virtual void release_delegate(
glslang::TShader::Includer::IncludeResult* result) override {
if (result && result_releaser_) {
result_releaser_(user_data_,
static_cast<shaderc_include_result*>(result->userData));
}
delete result;
}
const shaderc_include_resolve_fn resolver_;
const shaderc_include_result_release_fn result_releaser_;
void* user_data_;
};
// Converts the target env to the corresponding one in shaderc_util::Compiler.
shaderc_util::Compiler::TargetEnv GetCompilerTargetEnv(shaderc_target_env env) {
switch (env) {
case shaderc_target_env_opengl:
return shaderc_util::Compiler::TargetEnv::OpenGL;
case shaderc_target_env_opengl_compat:
return shaderc_util::Compiler::TargetEnv::OpenGLCompat;
case shaderc_target_env_webgpu:
assert(false);
break;
case shaderc_target_env_vulkan:
default:
break;
}
return shaderc_util::Compiler::TargetEnv::Vulkan;
}
shaderc_util::Compiler::TargetEnvVersion GetCompilerTargetEnvVersion(
uint32_t version_number) {
using namespace shaderc_util;
if (static_cast<uint32_t>(Compiler::TargetEnvVersion::Vulkan_1_0) ==
version_number) {
return Compiler::TargetEnvVersion::Vulkan_1_0;
}
if (static_cast<uint32_t>(Compiler::TargetEnvVersion::Vulkan_1_1) ==
version_number) {
return Compiler::TargetEnvVersion::Vulkan_1_1;
}
if (static_cast<uint32_t>(Compiler::TargetEnvVersion::Vulkan_1_2) ==
version_number) {
return Compiler::TargetEnvVersion::Vulkan_1_2;
}
if (static_cast<uint32_t>(Compiler::TargetEnvVersion::Vulkan_1_3) ==
version_number) {
return Compiler::TargetEnvVersion::Vulkan_1_3;
}
if (static_cast<uint32_t>(Compiler::TargetEnvVersion::OpenGL_4_5) ==
version_number) {
return Compiler::TargetEnvVersion::OpenGL_4_5;
}
return Compiler::TargetEnvVersion::Default;
}
// Returns the Compiler::Limit enum for the given shaderc_limit enum.
shaderc_util::Compiler::Limit CompilerLimit(shaderc_limit limit) {
switch (limit) {
#define RESOURCE(NAME, FIELD, CNAME) \
case shaderc_limit_##CNAME: \
return shaderc_util::Compiler::Limit::NAME;
#include "libshaderc_util/resources.inc"
#undef RESOURCE
default:
break;
}
assert(0 && "Should not have reached here");
return static_cast<shaderc_util::Compiler::Limit>(0);
}
// Returns the Compiler::UniformKind for the given shaderc_uniform_kind.
shaderc_util::Compiler::UniformKind GetUniformKind(shaderc_uniform_kind kind) {
switch (kind) {
case shaderc_uniform_kind_texture:
return shaderc_util::Compiler::UniformKind::Texture;
case shaderc_uniform_kind_sampler:
return shaderc_util::Compiler::UniformKind::Sampler;
case shaderc_uniform_kind_image:
return shaderc_util::Compiler::UniformKind::Image;
case shaderc_uniform_kind_buffer:
return shaderc_util::Compiler::UniformKind::Buffer;
case shaderc_uniform_kind_storage_buffer:
return shaderc_util::Compiler::UniformKind::StorageBuffer;
case shaderc_uniform_kind_unordered_access_view:
return shaderc_util::Compiler::UniformKind::UnorderedAccessView;
}
assert(0 && "Should not have reached here");
return static_cast<shaderc_util::Compiler::UniformKind>(0);
}
// Returns the Compiler::Stage for generic stage values in shaderc_shader_kind.
shaderc_util::Compiler::Stage GetStage(shaderc_shader_kind kind) {
switch (kind) {
case shaderc_vertex_shader:
return shaderc_util::Compiler::Stage::Vertex;
case shaderc_fragment_shader:
return shaderc_util::Compiler::Stage::Fragment;
case shaderc_compute_shader:
return shaderc_util::Compiler::Stage::Compute;
case shaderc_tess_control_shader:
return shaderc_util::Compiler::Stage::TessControl;
case shaderc_tess_evaluation_shader:
return shaderc_util::Compiler::Stage::TessEval;
case shaderc_geometry_shader:
return shaderc_util::Compiler::Stage::Geometry;
default:
break;
}
assert(0 && "Should not have reached here");
return static_cast<shaderc_util::Compiler::Stage>(0);
}
} // anonymous namespace
struct shaderc_compile_options {
shaderc_target_env target_env = shaderc_target_env_default;
uint32_t target_env_version = 0;
shaderc_util::Compiler compiler;
shaderc_include_resolve_fn include_resolver = nullptr;
shaderc_include_result_release_fn include_result_releaser = nullptr;
void* include_user_data = nullptr;
};
shaderc_compile_options_t shaderc_compile_options_initialize() {
return new (std::nothrow) shaderc_compile_options;
}
shaderc_compile_options_t shaderc_compile_options_clone(
const shaderc_compile_options_t options) {
if (!options) {
return shaderc_compile_options_initialize();
}
return new (std::nothrow) shaderc_compile_options(*options);
}
void shaderc_compile_options_release(shaderc_compile_options_t options) {
delete options;
}
void shaderc_compile_options_add_macro_definition(
shaderc_compile_options_t options, const char* name, size_t name_length,
const char* value, size_t value_length) {
options->compiler.AddMacroDefinition(name, name_length, value, value_length);
}
void shaderc_compile_options_set_source_language(
shaderc_compile_options_t options, shaderc_source_language set_lang) {
auto lang = shaderc_util::Compiler::SourceLanguage::GLSL;
if (set_lang == shaderc_source_language_hlsl)
lang = shaderc_util::Compiler::SourceLanguage::HLSL;
options->compiler.SetSourceLanguage(lang);
}
void shaderc_compile_options_set_generate_debug_info(
shaderc_compile_options_t options) {
options->compiler.SetGenerateDebugInfo();
}
void shaderc_compile_options_set_optimization_level(
shaderc_compile_options_t options, shaderc_optimization_level level) {
auto opt_level = shaderc_util::Compiler::OptimizationLevel::Zero;
switch (level) {
case shaderc_optimization_level_size:
opt_level = shaderc_util::Compiler::OptimizationLevel::Size;
break;
case shaderc_optimization_level_performance:
opt_level = shaderc_util::Compiler::OptimizationLevel::Performance;
break;
default:
break;
}
options->compiler.SetOptimizationLevel(opt_level);
}
void shaderc_compile_options_set_forced_version_profile(
shaderc_compile_options_t options, int version, shaderc_profile profile) {
// Transfer the profile parameter from public enum type to glslang internal
// enum type. No default case here so that compiler will complain if new enum
// member is added later but not handled here.
switch (profile) {
case shaderc_profile_none:
options->compiler.SetForcedVersionProfile(version, ENoProfile);
break;
case shaderc_profile_core:
options->compiler.SetForcedVersionProfile(version, ECoreProfile);
break;
case shaderc_profile_compatibility:
options->compiler.SetForcedVersionProfile(version, ECompatibilityProfile);
break;
case shaderc_profile_es:
options->compiler.SetForcedVersionProfile(version, EEsProfile);
break;
}
}
void shaderc_compile_options_set_include_callbacks(
shaderc_compile_options_t options, shaderc_include_resolve_fn resolver,
shaderc_include_result_release_fn result_releaser, void* user_data) {
options->include_resolver = resolver;
options->include_result_releaser = result_releaser;
options->include_user_data = user_data;
}
void shaderc_compile_options_set_suppress_warnings(
shaderc_compile_options_t options) {
options->compiler.SetSuppressWarnings();
}
void shaderc_compile_options_set_target_env(shaderc_compile_options_t options,
shaderc_target_env target,
uint32_t version) {
options->target_env = target;
options->compiler.SetTargetEnv(GetCompilerTargetEnv(target),
GetCompilerTargetEnvVersion(version));
}
void shaderc_compile_options_set_target_spirv(shaderc_compile_options_t options,
shaderc_spirv_version ver) {
// We made the values match, so we can get away with a static cast.
options->compiler.SetTargetSpirv(
static_cast<shaderc_util::Compiler::SpirvVersion>(ver));
}
void shaderc_compile_options_set_warnings_as_errors(
shaderc_compile_options_t options) {
options->compiler.SetWarningsAsErrors();
}
void shaderc_compile_options_set_limit(shaderc_compile_options_t options,
shaderc_limit limit, int value) {
options->compiler.SetLimit(CompilerLimit(limit), value);
}
void shaderc_compile_options_set_auto_bind_uniforms(
shaderc_compile_options_t options, bool auto_bind) {
options->compiler.SetAutoBindUniforms(auto_bind);
}
void shaderc_compile_options_set_auto_combined_image_sampler(
shaderc_compile_options_t options, bool upgrade) {
options->compiler.SetAutoCombinedImageSampler(upgrade);
}
void shaderc_compile_options_set_hlsl_io_mapping(
shaderc_compile_options_t options, bool hlsl_iomap) {
options->compiler.SetHlslIoMapping(hlsl_iomap);
}
void shaderc_compile_options_set_hlsl_offsets(shaderc_compile_options_t options,
bool hlsl_offsets) {
options->compiler.SetHlslOffsets(hlsl_offsets);
}
void shaderc_compile_options_set_binding_base(shaderc_compile_options_t options,
shaderc_uniform_kind kind,
uint32_t base) {
options->compiler.SetAutoBindingBase(GetUniformKind(kind), base);
}
void shaderc_compile_options_set_binding_base_for_stage(
shaderc_compile_options_t options, shaderc_shader_kind shader_kind,
shaderc_uniform_kind kind, uint32_t base) {
options->compiler.SetAutoBindingBaseForStage(GetStage(shader_kind),
GetUniformKind(kind), base);
}
void shaderc_compile_options_set_auto_map_locations(
shaderc_compile_options_t options, bool auto_map) {
options->compiler.SetAutoMapLocations(auto_map);
}
void shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
shaderc_compile_options_t options, shaderc_shader_kind shader_kind,
const char* reg, const char* set, const char* binding) {
options->compiler.SetHlslRegisterSetAndBindingForStage(GetStage(shader_kind),
reg, set, binding);
}
void shaderc_compile_options_set_hlsl_register_set_and_binding(
shaderc_compile_options_t options, const char* reg, const char* set,
const char* binding) {
options->compiler.SetHlslRegisterSetAndBinding(reg, set, binding);
}
void shaderc_compile_options_set_hlsl_functionality1(
shaderc_compile_options_t options, bool enable) {
options->compiler.EnableHlslFunctionality1(enable);
}
void shaderc_compile_options_set_hlsl_16bit_types(
shaderc_compile_options_t options, bool enable) {
options->compiler.EnableHlsl16BitTypes(enable);
}
void shaderc_compile_options_set_invert_y(
shaderc_compile_options_t options, bool enable) {
options->compiler.EnableInvertY(enable);
}
void shaderc_compile_options_set_nan_clamp(shaderc_compile_options_t options,
bool enable) {
options->compiler.SetNanClamp(enable);
}
shaderc_compiler_t shaderc_compiler_initialize() {
shaderc_compiler_t compiler = new (std::nothrow) shaderc_compiler;
if (compiler) {
compiler->initializer.reset(new shaderc_util::GlslangInitializer);
}
return compiler;
}
void shaderc_compiler_release(shaderc_compiler_t compiler) {
delete compiler;
}
namespace {
shaderc_compilation_result_t CompileToSpecifiedOutputType(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options,
shaderc_util::Compiler::OutputType output_type) {
auto* result = new (std::nothrow) shaderc_compilation_result_vector;
if (!result) return nullptr;
if (!input_file_name) {
result->messages = "Input file name string was null.";
result->num_errors = 1;
result->compilation_status = shaderc_compilation_status_compilation_error;
return result;
}
result->compilation_status = shaderc_compilation_status_invalid_stage;
bool compilation_succeeded = false; // In case we exit early.
std::vector<uint32_t> compilation_output_data;
size_t compilation_output_data_size_in_bytes = 0u;
if (!compiler->initializer) return result;
TRY_IF_EXCEPTIONS_ENABLED {
std::stringstream errors;
size_t total_warnings = 0;
size_t total_errors = 0;
std::string input_file_name_str(input_file_name);
EShLanguage forced_stage = GetForcedStage(shader_kind);
shaderc_util::string_piece source_string =
shaderc_util::string_piece(source_text, source_text + source_text_size);
StageDeducer stage_deducer(shader_kind);
if (additional_options) {
InternalFileIncluder includer(additional_options->include_resolver,
additional_options->include_result_releaser,
additional_options->include_user_data);
// Depends on return value optimization to avoid extra copy.
std::tie(compilation_succeeded, compilation_output_data,
compilation_output_data_size_in_bytes) =
additional_options->compiler.Compile(
source_string, forced_stage, input_file_name_str, entry_point_name,
// stage_deducer has a flag: error_, which we need to check later.
// We need to make this a reference wrapper, so that std::function
// won't make a copy for this callable object.
std::ref(stage_deducer), includer, output_type, &errors,
&total_warnings, &total_errors);
} else {
// Compile with default options.
InternalFileIncluder includer;
std::tie(compilation_succeeded, compilation_output_data,
compilation_output_data_size_in_bytes) =
shaderc_util::Compiler().Compile(
source_string, forced_stage, input_file_name_str, entry_point_name,
std::ref(stage_deducer), includer, output_type, &errors,
&total_warnings, &total_errors);
}
result->messages = errors.str();
result->SetOutputData(std::move(compilation_output_data));
result->output_data_size = compilation_output_data_size_in_bytes;
result->num_warnings = total_warnings;
result->num_errors = total_errors;
if (compilation_succeeded) {
result->compilation_status = shaderc_compilation_status_success;
} else {
// Check whether the error is caused by failing to deduce the shader
// stage. If it is the case, set the error type to shader kind error.
// Otherwise, set it to compilation error.
result->compilation_status =
stage_deducer.error() ? shaderc_compilation_status_invalid_stage
: shaderc_compilation_status_compilation_error;
}
}
CATCH_IF_EXCEPTIONS_ENABLED(...) {
result->compilation_status = shaderc_compilation_status_internal_error;
}
return result;
}
} // anonymous namespace
shaderc_compilation_result_t shaderc_compile_into_spv(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options) {
return CompileToSpecifiedOutputType(
compiler, source_text, source_text_size, shader_kind, input_file_name,
entry_point_name, additional_options,
shaderc_util::Compiler::OutputType::SpirvBinary);
}
shaderc_compilation_result_t shaderc_compile_into_spv_assembly(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options) {
return CompileToSpecifiedOutputType(
compiler, source_text, source_text_size, shader_kind, input_file_name,
entry_point_name, additional_options,
shaderc_util::Compiler::OutputType::SpirvAssemblyText);
}
shaderc_compilation_result_t shaderc_compile_into_preprocessed_text(
const shaderc_compiler_t compiler, const char* source_text,
size_t source_text_size, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const shaderc_compile_options_t additional_options) {
return CompileToSpecifiedOutputType(
compiler, source_text, source_text_size, shader_kind, input_file_name,
entry_point_name, additional_options,
shaderc_util::Compiler::OutputType::PreprocessedText);
}
shaderc_compilation_result_t shaderc_assemble_into_spv(
const shaderc_compiler_t compiler, const char* source_assembly,
size_t source_assembly_size,
const shaderc_compile_options_t additional_options) {
auto* result = new (std::nothrow) shaderc_compilation_result_spv_binary;
if (!result) return nullptr;
result->compilation_status = shaderc_compilation_status_invalid_assembly;
if (!compiler->initializer) return result;
if (source_assembly == nullptr) return result;
TRY_IF_EXCEPTIONS_ENABLED {
spv_binary assembling_output_data = nullptr;
std::string errors;
const auto target_env = additional_options ? additional_options->target_env
: shaderc_target_env_default;
const uint32_t target_env_version =
additional_options ? additional_options->target_env_version : 0;
const bool assembling_succeeded = shaderc_util::SpirvToolsAssemble(
GetCompilerTargetEnv(target_env),
GetCompilerTargetEnvVersion(target_env_version),
{source_assembly, source_assembly + source_assembly_size},
&assembling_output_data, &errors);
result->num_errors = !assembling_succeeded;
if (assembling_succeeded) {
result->SetOutputData(assembling_output_data);
result->output_data_size =
assembling_output_data->wordCount * sizeof(uint32_t);
result->compilation_status = shaderc_compilation_status_success;
} else {
result->messages = std::move(errors);
result->compilation_status = shaderc_compilation_status_invalid_assembly;
}
}
CATCH_IF_EXCEPTIONS_ENABLED(...) {
result->compilation_status = shaderc_compilation_status_internal_error;
}
return result;
}
size_t shaderc_result_get_length(const shaderc_compilation_result_t result) {
return result->output_data_size;
}
size_t shaderc_result_get_num_warnings(
const shaderc_compilation_result_t result) {
return result->num_warnings;
}
size_t shaderc_result_get_num_errors(
const shaderc_compilation_result_t result) {
return result->num_errors;
}
const char* shaderc_result_get_bytes(
const shaderc_compilation_result_t result) {
return result->GetBytes();
}
void shaderc_result_release(shaderc_compilation_result_t result) {
delete result;
}
const char* shaderc_result_get_error_message(
const shaderc_compilation_result_t result) {
return result->messages.c_str();
}
shaderc_compilation_status shaderc_result_get_compilation_status(
const shaderc_compilation_result_t result) {
return result->compilation_status;
}
void shaderc_get_spv_version(unsigned int* version, unsigned int* revision) {
*version = spv::Version;
*revision = spv::Revision;
}
bool shaderc_parse_version_profile(const char* str, int* version,
shaderc_profile* profile) {
EProfile glslang_profile;
bool success = shaderc_util::ParseVersionProfile(
std::string(str, strlen(str)), version, &glslang_profile);
if (!success) return false;
switch (glslang_profile) {
case EEsProfile:
*profile = shaderc_profile_es;
return true;
case ECoreProfile:
*profile = shaderc_profile_core;
return true;
case ECompatibilityProfile:
*profile = shaderc_profile_compatibility;
return true;
case ENoProfile:
*profile = shaderc_profile_none;
return true;
case EBadProfile:
case EProfileCount:
return false;
}
// Shouldn't reach here, all profile enum should be handled above.
// Be strict to return false.
return false;
}

View File

@ -0,0 +1,54 @@
// Copyright 2016 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "shaderc/shaderc.h"
#include <assert.h>
#include <string.h>
// Because we want to test this as a plain old C file, we cannot use
// gtest, so just run a simple smoke test.
int main() {
const char* test_program =
"#version 310 es\n"
"layout(location = 0) in highp vec4 vtxColor;\n"
"layout(location = 0) out highp vec4 outColor;\n"
"void main() {\n"
" outColor = vtxColor;"
"}\n";
shaderc_compiler_t compiler;
shaderc_compilation_result_t result;
shaderc_compile_options_t options;
compiler = shaderc_compiler_initialize();
options = shaderc_compile_options_initialize();
shaderc_compile_options_add_macro_definition(options, "FOO", 3, "1", 1);
result = shaderc_compile_into_spv(
compiler, test_program, strlen(test_program),
shaderc_glsl_fragment_shader, "a.glsl", "main", options);
assert(result);
if (shaderc_result_get_compilation_status(result) !=
shaderc_compilation_status_success) {
// Early exit on failure.
return -1;
}
shaderc_result_release(result);
shaderc_compile_options_release(options);
shaderc_compiler_release(compiler);
return 0;
}

View File

@ -0,0 +1,139 @@
// Copyright 2015 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef LIBSHADERC_SRC_SHADERC_PRIVATE_H_
#define LIBSHADERC_SRC_SHADERC_PRIVATE_H_
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
#include "shaderc/shaderc.h"
#include "libshaderc_util/compiler.h"
#include "spirv-tools/libspirv.h"
// Described in shaderc.h.
struct shaderc_compilation_result {
virtual ~shaderc_compilation_result() {}
// Returns the data from this compilation as a sequence of bytes.
virtual const char* GetBytes() const = 0;
// The size of the output data in term of bytes.
size_t output_data_size = 0;
// Compilation messages.
std::string messages;
// Number of errors.
size_t num_errors = 0;
// Number of warnings.
size_t num_warnings = 0;
// Compilation status.
shaderc_compilation_status compilation_status =
shaderc_compilation_status_null_result_object;
};
// Compilation result class using a vector for holding the compilation
// output data.
class shaderc_compilation_result_vector : public shaderc_compilation_result {
public:
~shaderc_compilation_result_vector() = default;
void SetOutputData(std::vector<uint32_t>&& data) {
output_data_ = std::move(data);
}
const char* GetBytes() const override {
return reinterpret_cast<const char*>(output_data_.data());
}
private:
// Compilation output data. In normal compilation mode, it contains the
// compiled SPIR-V binary code. In disassembly and preprocessing-only mode, it
// contains a null-terminated string which is the text output. For text
// output, extra bytes with value 0x00 might be appended to complete the last
// uint32_t element.
std::vector<uint32_t> output_data_;
};
// Compilation result class using a spv_binary for holding the compilation
// output data.
class shaderc_compilation_result_spv_binary
: public shaderc_compilation_result {
public:
~shaderc_compilation_result_spv_binary() { spvBinaryDestroy(output_data_); }
void SetOutputData(spv_binary data) { output_data_ = data; }
const char* GetBytes() const override {
return reinterpret_cast<const char*>(output_data_->code);
}
private:
spv_binary output_data_ = nullptr;
};
namespace shaderc_util {
class GlslangInitializer;
}
struct shaderc_compiler {
std::unique_ptr<shaderc_util::GlslangInitializer> initializer;
};
// Converts a shader stage from shaderc_shader_kind into a shaderc_util::Compiler::Stage.
// This is only valid for a specifically named shader stage, e.g. vertex through fragment,
// or compute.
inline shaderc_util::Compiler::Stage shaderc_convert_specific_stage(
shaderc_shader_kind kind) {
switch (kind) {
case shaderc_vertex_shader:
return shaderc_util::Compiler::Stage::Vertex;
case shaderc_fragment_shader:
return shaderc_util::Compiler::Stage::Fragment;
case shaderc_tess_control_shader:
return shaderc_util::Compiler::Stage::TessControl;
case shaderc_tess_evaluation_shader:
return shaderc_util::Compiler::Stage::TessEval;
case shaderc_geometry_shader:
return shaderc_util::Compiler::Stage::Geometry;
case shaderc_compute_shader:
return shaderc_util::Compiler::Stage::Compute;
case shaderc_raygen_shader:
return shaderc_util::Compiler::Stage::RayGenNV;
case shaderc_intersection_shader:
return shaderc_util::Compiler::Stage::IntersectNV;
case shaderc_anyhit_shader:
return shaderc_util::Compiler::Stage::AnyHitNV;
case shaderc_closesthit_shader:
return shaderc_util::Compiler::Stage::ClosestHitNV;
case shaderc_miss_shader:
return shaderc_util::Compiler::Stage::MissNV;
case shaderc_callable_shader:
return shaderc_util::Compiler::Stage::CallableNV;
case shaderc_task_shader:
return shaderc_util::Compiler::Stage::TaskNV;
case shaderc_mesh_shader:
return shaderc_util::Compiler::Stage::MeshNV;
default:
// We don't care about the other kinds.
break;
}
// This should not occur.
assert(false && "Should have specified a specific stage");
return shaderc_util::Compiler::Stage::TessEval;
}
#endif // LIBSHADERC_SRC_SHADERC_PRIVATE_H_