File size: 10,807 Bytes
d46d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cf78b
 
 
 
d46d640
 
 
59cf78b
 
 
 
 
 
d46d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296

import omni
import random
import numpy as np
from pxr import Usd, UsdGeom, Gf, Sdf, UsdShade
from scipy.spatial.transform import Rotation

# --- Asset and Scene Configuration ---

CROP_ASSETS = {
    "soybean": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"],
    "sorghum": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"],
    "cotton": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"],
    "corn": ["_1", "_2", "_3", "_4", "_5", "_6", "_61", "_62", "_7", "_71", "_72", "_8", "_81", "_9", "_91", "_92"],
    "cane": ["_1", "_2"]
}

CROP_AGES = {
    "y": ["_1", "_2"],
    "y-m": ["_3", "_4", "_5"],
    "m-l": ["_5", "_6", "_7"],
    "l": ["_8", "_9"]
}

ROW_SPACING = {
    "corn": 0.45,
    "soybean": 0.45,
    "sorghum": 0.45,
    "cotton": 0.9,
    "cane": 1.0
}

WEED_ASSETS = [
    "/World/weed/broadleaf_1",
    "/World/weed/broadleaf_2",
    "/World/weed/grass_1",
    "/World/weed/grass_2"
]

OBSTACLE_ASSETS = [
    "/World/obstacle/cones/c1",
    "/World/obstacle/cones/c2",
    "/World/obstacle/cones/c3",
    "/World/obstacle/cones/c4",
    "/World/obstacle/female_adult_police_01_new",
    "/World/obstacle/male_adult_construction_01_new",
    # "/World/ood/Tractor"
]

# Weed
VOLUME_MAPPING = {
    "none": 0,
    "some": 50,  # Number of assets to spawn
    "lot": 500
}

OBSTACLE_VOLUME_MAPPING = {
    "none": 0,
    "some": 5,
    "lot": 15
}

TIME_OF_DAY_MAPPING = {
    "early": 85,
    "noon": 0,
    "late": -75
}

# 
GROUND_MATERIALS = [
        "/FlatGrid/Looks/Dirt",
        "/FlatGrid/Looks/Mulch_Brown",
        "/FlatGrid/Looks/Mulch_Dry"
]

# --- Helper Functions ---

def change_ground_material(stage):
    """Changes the ground material using the MaterialBindingAPI."""
    ground_path = "/FlatGrid/Environment"
    ground_prim = stage.GetPrimAtPath(ground_path)
    
    if not ground_prim:
        print(f"Ground prim not found at {ground_path}.")
        return

    material_path = random.choice(GROUND_MATERIALS)
    material_prim = stage.GetPrimAtPath(material_path)
    
    if not material_prim:
        print(f"Material prim not found at {material_path}.")
        return

    # Ensure the target prim is actually a Material
    material = UsdShade.Material(material_prim)
    if not material:
        print(f"Prim at {material_path} is not a valid UsdShadeMaterial.")
        return

    # Apply the MaterialBindingAPI to the ground prim
    binding_api = UsdShade.MaterialBindingAPI.Apply(ground_prim)
    
    # Bind the material. 
    # UsdShade.Tokens.strongerThanDescendants ensures this material 
    # overrides any materials assigned to child prims.
    binding_api.Bind(material, bindingStrength=UsdShade.Tokens.strongerThanDescendants)

    print(f"Successfully bound {ground_path} to {material_path}")


def set_time_of_day(stage, time_of_day):
    """Sets the absolute time of day by finding or creating the rotation op."""
    sun_path = "/World/CumulusLight/AxisNorth/AxisLatitude/AxisSHA"
    sun_prim = stage.GetPrimAtPath(sun_path)
    
    if not sun_prim:
        print(f"Warning: Sun prim not found at {sun_path}.")
        return

    angle = TIME_OF_DAY_MAPPING.get(time_of_day, 180)
    xform = UsdGeom.Xformable(sun_prim)
    
    # 1. Look for an existing RotateX operation in the stack
    rotate_op = None
    for op in xform.GetOrderedXformOps():
        if op.GetOpType() == UsdGeom.XformOp.TypeRotateX:
            rotate_op = op
            break
    
    # 2. If it exists, set the absolute value. If not, create it.
    if rotate_op:
        rotate_op.Set(float(angle))
    else:
        # This adds the op to the stack and sets the initial absolute value
        xform.AddRotateXOp(precision=UsdGeom.XformOp.PrecisionFloat).Set(float(angle))

def set_robust_transform(prim, translation=None, rotation_euler=None, scale=None):
    """
    Robustly updates or adds transform operations to a prim.
    Handles existing Ops, different precisions, and Quaternion vs Euler rotations.
    """
    xform = UsdGeom.Xformable(prim)
    # We use this to track which ops we've updated to avoid duplicates
    found_ops = {"translate": None, "rotate": None, "scale": None}
    
    for op in xform.GetOrderedXformOps():
        op_type = op.GetOpType()
        if op_type in [UsdGeom.XformOp.TypeTranslate]:
            found_ops["translate"] = op
        elif op_type in [UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.TypeOrient]:
            found_ops["rotate"] = op
        elif op_type in [UsdGeom.XformOp.TypeScale]:
            found_ops["scale"] = op

    # --- Handle Translation ---
    if translation is not None:
        if found_ops["translate"]:
            found_ops["translate"].Set(translation)
        else:
            xform.AddTranslateOp().Set(translation)

    # --- Handle Rotation (Euler Z to XYZ or Quat) ---
    if rotation_euler is not None:
        z_deg = rotation_euler[2] # Assuming we mostly care about Z for plants
        if found_ops["rotate"]:
            op = found_ops["rotate"]
            attr_type = op.GetAttr().GetTypeName()
            
            if attr_type in (Sdf.ValueTypeNames.Quatf, Sdf.ValueTypeNames.Quatd):
                # Convert Euler to Quat
                r = Rotation.from_euler('z', z_deg, degrees=True)
                q = r.as_quat() # x, y, z, w
                quat_val = Gf.Quatd(q[3], q[0], q[1], q[2]) if attr_type == Sdf.ValueTypeNames.Quatd else Gf.Quatf(q[3], q[0], q[1], q[2])
                op.Set(quat_val)
            else:
                # Standard Euler (Vec3f or Vec3d)
                current_rot = op.Get() or Gf.Vec3f(0)
                op.Set(Gf.Vec3f(current_rot[0], current_rot[1], z_deg))
        else:
            xform.AddRotateXYZOp().Set(Gf.Vec3f(0, 0, z_deg))

    # --- Handle Scale ---
    if scale is not None:
        if found_ops["scale"]:
            found_ops["scale"].Set(scale)
        else:
            xform.AddScaleOp().Set(scale)

def scatter_assets(stage, asset_paths, num_assets, area_min, area_max, root_path):
    if num_assets == 0: return
    stage.DefinePrim(root_path, "Xform")
    
    for i in range(num_assets):
        asset_path = random.choice(asset_paths)
        new_path = f"{root_path}/item_{i}"
        omni.usd.duplicate_prim(stage, asset_path, new_path)
        
        prim = stage.GetPrimAtPath(new_path)
        pos = Gf.Vec3f(random.uniform(area_min[0], area_max[0]), 
                       random.uniform(area_min[1], area_max[1]), 0)
        rot = Gf.Vec3f(0, 0, random.uniform(0, 360))
        
        set_robust_transform(prim, translation=pos, rotation_euler=rot, scale=Gf.Vec3f(1.0))

def get_crop_paths (crop_type, crop_age):
    """Get valid prim paths for the selected crop type and age."""
    base_path = f"/World/base/{crop_type}"
    age_suffixes = CROP_AGES.get(crop_age, [])
    available_suffixes = CROP_ASSETS.get(crop_type, [])
    valid_suffixes = [s for s in age_suffixes if s in available_suffixes]
    if not valid_suffixes:
        raise ValueError(f"No assets found for crop {crop_type} with age {crop_age}'.")
    return [f"{base_path}/{suffix}" for suffix in valid_suffixes]

def generate_scene(config):
    stage = omni.usd.get_context().get_stage()
    # ... [Config parsing logic] ...

    # --- Field Generation ---
    root_crop_path = Sdf.Path(f"/root/{config['crop_type']}_{config['crop_age']}_field")
    if stage.GetPrimAtPath(root_crop_path): stage.RemovePrim(root_crop_path)
    stage.DefinePrim(root_crop_path, "Xform")

    curve_effect = np.sin(np.linspace(0, 6 * np.pi, config["num_plants_in_row"])) * 0.35 if config["curve"] else np.zeros(config["num_plants_in_row"])

    print(f"Generating {config['num_rows']} rows with {config['num_plants_in_row']} plants each (Curve: {config['curve']})")

    for i in range(config["num_rows"]):
        for j in range(config["num_plants_in_row"]):
            if random.random() < 0.1: continue

            new_prim_path = f"{root_crop_path}/row_{i}_plant_{j}"
            omni.usd.duplicate_prim(stage, random.choice(get_crop_paths(config["crop_type"], config["crop_age"])), new_prim_path)
            
            prim = stage.GetPrimAtPath(new_prim_path)
            
            # Position logic
            offset = random.uniform(-0.02, 0.02)
            x_pos = i * ROW_SPACING.get(config["crop_type"], 0.45) + offset + curve_effect[j]
            y_pos = j * 0.1 + offset
            
            # Scale logic
            s = 1.0 + random.uniform(-0.05, 0.05)
            
            set_robust_transform(
                prim, 
                translation=Gf.Vec3f(x_pos, y_pos, 0), 
                rotation_euler=Gf.Vec3f(0, 0, random.uniform(0, 360)),
                scale=Gf.Vec3f(s, s, s)
            )

    # Scatter Weeds/Obstacles
    field_w = config["num_rows"] * ROW_SPACING.get(config["crop_type"], 0.45)
    field_l = config["num_plants_in_row"] * 0.1

    print(f"Scattering weeds and obstacles (Weeds: {config['weed_volume']}, Obstacles: {config['obstacle_volume']})")
    scatter_assets(stage, WEED_ASSETS, VOLUME_MAPPING[config["weed_volume"]], (0,0), (field_w, field_l), Sdf.Path("/root/Weeds"))
    print(f"Scattering obstacles (Volume: {config['obstacle_volume']})")
    scatter_assets(stage, OBSTACLE_ASSETS, OBSTACLE_VOLUME_MAPPING[config["obstacle_volume"]], (0,0), (field_w, field_l), Sdf.Path("/root/Obstacles"))
    # print(f"Setting time of day to {config['time_of_day']}")
    # set_time_of_day(stage, config["time_of_day"])
    # print("Changing ground material")
    # change_ground_material(stage)
    print("Scene generation complete!")


# --- USER CONFIGURATION ---
# Modify the values in this dictionary to change the generated scene.
CONFIG = {
    "crop_type": "cane",           # Options: "soybean", "sorghum", "cotton", "corn"
    "crop_age": "y",             # Options: "y", "y-m", "m-l", "l"
    "curve": False,                 # Options: True or False
    "num_plants_in_row": 250,        # Number of plants in each row
    "num_rows": 20,                 # Number of rows in the field
    "weed_volume": "none",         # Options: "none", "some", "lot"
    "obstacle_volume": "none",     # Options: "none", "some", "lot"
    "time_of_day": "noon"          # Options: "early", "noon", "late"
}
# --- END USER CONFIGURATION ---

# Execute the scene generation
generate_scene(CONFIG)

# for crop_type in ["soybean", "sorghum", "cotton", "corn"]:
#     for crop_age in ["y", "y-m", "m-l", "l"]:
#         CONFIG = {
#             "crop_type": crop_type,
#             "crop_age": crop_age,
#             "curve": False,
#             "num_plants_in_row": 250,
#             "num_rows": 20,
#             "weed_volume": "some",
#             "obstacle_volume": "some",
#             "time_of_day": "noon"
#         }
#         generate_scene(CONFIG)