Skip to content

Commit

Permalink
Support shader float and color uniforms
Browse files Browse the repository at this point in the history
  • Loading branch information
yiqunw700 committed Jan 11, 2025
1 parent b2cc317 commit 4473b8c
Show file tree
Hide file tree
Showing 75 changed files with 849 additions and 95 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,12 @@ private class DesignModuleVisitor(
out += " customizations.setMeterValue(\"$nodeName\", $propertyName)\n"
CustomizationType.MeterState ->
out += " customizations.setMeterState(\"$nodeName\", $propertyName)\n"
CustomizationType.ShaderUniformTimeState -> {
CustomizationType.ShaderUniformList -> {
out += " customizations.setShaderUniformList(\"$nodeName\", $propertyName)\n"
}
CustomizationType.ShaderUniformStateList -> {
out +=
" customizations.setShaderUniformTimeState(\"$nodeName\", $propertyName)\n"
" customizations.setShaderUniformStateList(\"$nodeName\", $propertyName)\n"
}
CustomizationType.ScrollCallbacks ->
out += " customizations.setScrollCallbacks(\"$nodeName\", $propertyName)\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ class BuilderProcessor(private val codeGenerator: CodeGenerator, val logger: KSP
private var meterCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var meterStateCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var shaderUniformTimeStateCustomizations:
private var shaderUniformListCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var shaderUniformStateListCustomizations:
HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var scrollCallbackCustomizations: HashMap<String, Vector<Pair<String, String>>> =
Expand Down Expand Up @@ -747,12 +749,19 @@ class BuilderProcessor(private val codeGenerator: CodeGenerator, val logger: KSP
out.appendText(" customizations.setMeterState(\"$node\", $value)\n")
}

val shaderUniformTimeStateCustom =
shaderUniformTimeStateCustomizations[function.toString()]
val shaderUniformListCustom =
shaderUniformListCustomizations[function.toString()]
?: Vector<Pair<String, String>>()
for ((node, value) in shaderUniformListCustom) {
out.appendText(" customizations.setShaderUniformList(\"$node\", $value)\n")
}

val shaderUniformStateListCustom =
shaderUniformStateListCustomizations[function.toString()]
?: Vector<Pair<String, String>>()
for ((node, value) in shaderUniformTimeStateCustom) {
for ((node, value) in shaderUniformStateListCustom) {
out.appendText(
" customizations.setShaderUniformTimeState(\"$node\", $value)\n"
" customizations.setShaderUniformStateList(\"$node\", $value)\n"
)
}

Expand Down Expand Up @@ -882,11 +891,13 @@ class BuilderProcessor(private val codeGenerator: CodeGenerator, val logger: KSP
addCustomization(valueParameter, annotation, meterCustomizations)
CustomizationType.MeterState ->
addCustomization(valueParameter, annotation, meterStateCustomizations)
CustomizationType.ShaderUniformTimeState ->
CustomizationType.ShaderUniformList ->
addCustomization(valueParameter, annotation, shaderUniformListCustomizations)
CustomizationType.ShaderUniformStateList ->
addCustomization(
valueParameter,
annotation,
shaderUniformTimeStateCustomizations,
shaderUniformStateListCustomizations,
)
CustomizationType.ScrollCallbacks ->
addCustomization(valueParameter, annotation, scrollCallbackCustomizations)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ internal enum class CustomizationType {
VariantProperty,
Meter,
MeterState,
ShaderUniformTimeState,
ShaderUniformList,
ShaderUniformStateList,
ScrollCallbacks,
Module,
Unknown,
Expand Down Expand Up @@ -125,7 +126,8 @@ internal fun createNewFile(
file += "import com.android.designcompose.setBrushFunction\n"
file += "import com.android.designcompose.setMeterValue\n"
file += "import com.android.designcompose.setMeterState\n"
file += "import com.android.designcompose.setShaderUniformTimeState\n"
file += "import com.android.designcompose.setShaderUniformList\n"
file += "import com.android.designcompose.setShaderUniformStateList\n"
file += "import com.android.designcompose.DesignScrollCallbacks\n"
file += "import com.android.designcompose.setScrollCallbacks\n"
file += "import com.android.designcompose.setModifier\n"
Expand Down Expand Up @@ -195,8 +197,9 @@ internal fun stringTypeToCustomizationType(strType: String): CustomizationType {
"TextStyle" -> CustomizationType.TextStyle
"com.android.designcompose.Meter" -> CustomizationType.Meter
"com.android.designcompose.MeterState" -> CustomizationType.MeterState
"com.android.designcompose.ShaderUniformTimeState" ->
CustomizationType.ShaderUniformTimeState
"com.android.designcompose.ShaderUniformList" -> CustomizationType.ShaderUniformList
"com.android.designcompose.ShaderUniformStateList" ->
CustomizationType.ShaderUniformStateList
"com.android.designcompose.DesignScrollCallbacks" -> CustomizationType.ScrollCallbacks
else -> CustomizationType.Unknown
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ package com.android.designcompose.common

// LINT.IfChange
// Current serialized doc version
const val FSAAS_DOC_VERSION = 25
// LINT.ThenChange(crates/dc_bundle/src/legacy_definition.rs)
const val FSAAS_DOC_VERSION = 26
// LINT.ThenChange(crates/dc_bundle/src/definition.rs)
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ abstract class FeedbackImpl {
)
}

fun shaderUniformNotFound(shader: String, uniform: String, docId: DesignDocId) {}

open fun setStatus(str: String, level: FeedbackLevel, docId: DesignDocId) {
// Ignore log levels we don't care about
if (level < logLevel) return
Expand Down
1 change: 1 addition & 0 deletions crates/dc_bundle/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ prost.workspace = true
thiserror.workspace = true
serde.workspace = true
serde_bytes.workspace = true
log.workspace = true

[build-dependencies]
prost-build.workspace = true
2 changes: 1 addition & 1 deletion crates/dc_bundle/src/definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub mod view;
include!(concat!(env!("OUT_DIR"), "/designcompose.definition.rs"));

// LINT.IfChange
pub static CURRENT_VERSION: u32 = 25;
pub static CURRENT_VERSION: u32 = 26;
// Lint.ThenChange(common/src/main/java/com/android/designcompose/common/DCDVersion.kt)

impl DesignComposeDefinitionHeader {
Expand Down
16 changes: 6 additions & 10 deletions crates/dc_bundle/src/definition/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/
use crate::definition::element::line_height::LineHeightType;
use crate::definition::element::{
background, Background, Color, FontStretch, FontStyle, FontWeight, LineHeight, NumOrVar,
Rectangle, Size, Stroke, TextDecoration, ViewShape,
background, Background, FontStretch, FontStyle, FontWeight, LineHeight, NumOrVar, Rectangle,
Size, Stroke, TextDecoration, ViewShape,
};
use crate::definition::interaction::{PointerEvents, Reaction};
use crate::definition::layout::{
Expand Down Expand Up @@ -317,8 +317,7 @@ impl View {
reactions: Option<Vec<Reaction>>,
scroll_info: ScrollInfo,
frame_extras: Option<FrameExtras>,
shader: Option<String>,
shader_fallback_color: Option<Color>,
shader_data: Option<ShaderData>,
design_absolute_bounding_box: Option<Rectangle>,
render_method: RenderMethod,
explicit_variable_modes: HashMap<String, String>,
Expand All @@ -340,8 +339,7 @@ impl View {
design_absolute_bounding_box,
render_method: i32::from(render_method),
explicit_variable_modes,
shader,
shader_fallback_color,
shader_data,
}
}
pub fn new_text(
Expand Down Expand Up @@ -373,8 +371,7 @@ impl View {
design_absolute_bounding_box,
render_method: i32::from(render_method),
explicit_variable_modes,
shader: None,
shader_fallback_color: None,
shader_data: None,
}
}
pub fn new_styled_text(
Expand Down Expand Up @@ -405,8 +402,7 @@ impl View {
design_absolute_bounding_box,
render_method: i32::from(render_method),
explicit_variable_modes: HashMap::new(),
shader: None,
shader_fallback_color: None,
shader_data: None,
}
}
pub fn add_child(&mut self, child: View) {
Expand Down
1 change: 1 addition & 0 deletions crates/figma_import/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,4 @@ pub use design_definition::load_design_def_header_v0;
/// languages
#[cfg(feature = "reflection")]
pub mod reflection;
pub mod shader_schema;
87 changes: 87 additions & 0 deletions crates/figma_import/src/shader_schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright 2025 Google LLC
*
* 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.
*/
use crate::figma_schema::FigmaColor;
use dc_bundle::definition::view::shader_uniform_value::FloatVec;
use dc_bundle::definition::view::shader_uniform_value::ValueType::{
FloatColorValue, FloatValue, FloatVecValue,
};
use dc_bundle::definition::view::{ShaderUniform, ShaderUniformValue};
use log::error;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct ShaderUniformJson {
#[serde(rename = "uniformName")]
pub uniform_name: String,
#[serde(rename = "uniformType")]
pub uniform_type: String,
#[serde(rename = "uniformValue")]
pub uniform_value: serde_json::Value,
}

impl Into<(String, ShaderUniform)> for ShaderUniformJson {
fn into(self) -> (String, ShaderUniform) {
let uniform_value = match self.uniform_type.as_str() {
"float" => {
if let Some(float_val) = self.uniform_value.as_f64() {
Some(ShaderUniformValue { value_type: Some(FloatValue(float_val as f32)) })
} else {
error!("Error parsing float for shader float uniform {}", self.uniform_name);
None
}
}
"float2" | "float3" | "float4" => {
if let Some(uniform_array) = self.uniform_value.as_array() {
let float_array: Vec<f32> = uniform_array
.iter()
.filter_map(|value| value.as_f64().map(|v| v as f32))
.collect();
match float_array.len() {
2 if self.uniform_type == "float2" => Some(float_array),
3 if self.uniform_type == "float3" => Some(float_array),
4 if self.uniform_type == "float4" => Some(float_array),
_ => None,
}
.map(|float_vec| ShaderUniformValue {
value_type: Some(FloatVecValue(FloatVec { floats: float_vec })),
})
} else {
error!(
"Error parsing float array for shader {} uniform {}",
self.uniform_type, self.uniform_name
);
None
}
}
"color" => serde_json::from_str::<FigmaColor>(self.uniform_value.to_string().as_str())
.ok()
.map(|figma_color| (&figma_color).into())
.map(|parsed_color| ShaderUniformValue {
value_type: Some(FloatColorValue(parsed_color)),
}),
_ => None,
};

(
self.uniform_name.clone(),
ShaderUniform {
name: self.uniform_name.clone(),
r#type: self.uniform_type,
value: uniform_value,
},
)
}
}
41 changes: 27 additions & 14 deletions crates/figma_import/src/transform_flexbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,12 @@ use dc_bundle::definition::plugin::{
use dc_bundle::definition::plugin::meter_data::MeterDataType;
use log::error;

use crate::shader_schema::ShaderUniformJson;
use dc_bundle::definition::element::line_height::LineHeightType;
use dc_bundle::definition::view::view::RenderMethod;
use dc_bundle::definition::view::{ComponentInfo, StyledTextRun, TextStyle, View, ViewStyle};
use dc_bundle::definition::view::{
ComponentInfo, ShaderData, ShaderUniform, StyledTextRun, TextStyle, View, ViewStyle,
};
use unicode_segmentation::UnicodeSegmentation;

// If an Auto content preview widget specifies a "Hug contents" sizing policy, this
Expand Down Expand Up @@ -960,22 +963,32 @@ fn visit_node(
};

// We have shader which is a string that can be used to draw the background.
let shader: Option<String> = {
if let Some(vsw_data) = plugin_data {
if let Some(extras) = vsw_data.get("shader") {
Option::from(extras.to_owned())
} else {
None
}
} else {
None
}
};
let shader: Option<String> =
plugin_data.and_then(|vsw_data| vsw_data.get("shader")).map(|extras| extras.to_owned());
// Shader fallback color is the color used when shader isn't supported on lower sdks.
let shader_fallback_color: Option<Color> = plugin_data
.and_then(|vsw_data| vsw_data.get("shaderFallbackColor"))
.and_then(|extras| serde_json::from_str::<FigmaColor>(extras).ok())
.map(|figma_color| (&figma_color).into());
error!("shader_fallback_color: {:?}", shader_fallback_color);
// Shader uniforms: float, float array, color and color with alpha
let shader_uniforms: HashMap<String, ShaderUniform> = plugin_data
.and_then(|vsw_data| vsw_data.get("shaderUniforms"))
.and_then(|shader_uniforms| {
serde_json::from_str::<Vec<ShaderUniformJson>>(shader_uniforms.as_str()).ok()
})
.unwrap_or_default()
.into_iter()
.map(ShaderUniformJson::into)
.collect();
error!("shader_uniforms: {:?}", shader_uniforms);

let shader_data = if let Some(shader_code) = shader {
Some(ShaderData { shader: shader_code, shader_fallback_color, shader_uniforms })
} else {
None
};
error!("shader_data: {:?}", shader_data);

let mut scroll_info = ScrollInfo::new_default();

Expand Down Expand Up @@ -1784,8 +1797,7 @@ fn visit_node(
reactions,
scroll_info,
frame_extras,
shader,
shader_fallback_color,
shader_data,
node.absolute_bounding_box.map(|r| (&r).into()),
RenderMethod::None,
node.explicit_variable_modes.as_ref().unwrap_or(&HashMap::new()).clone(),
Expand All @@ -1809,6 +1821,7 @@ fn visit_node(
}
}
}
error!("This is the end of the visit node......");
Ok(view)
}

Expand Down
Binary file modified crates/figma_import/tests/layout-unit-tests.dcf
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit 4473b8c

Please sign in to comment.